file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
list
attention_mask
list
labels
list
// 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); } // File @openzeppelin/contracts/token/ERC721/[email protected] 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/[email protected] 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/token/ERC721/extensions/[email protected] 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/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/utils/[email protected] 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; } } // File @openzeppelin/contracts/utils/[email protected] 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/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File @openzeppelin/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @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(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] 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/extensions/[email protected] pragma solidity ^0.8.0; /** * @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(); } } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @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); } } // File @openzeppelin/contracts/access/[email protected] 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() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } pragma solidity ^0.8.4; interface IMintable { function mintFor( address to, uint256 quantity, bytes calldata mintingBlob ) external; } pragma solidity ^0.8.4; library Bytes { /** * @dev Converts a `uint256` to a `string`. * via OraclizeAPI - MIT licence * https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol */ function fromUint(uint256 value) internal pure returns (string memory) { 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); } bytes constant alphabet = "0123456789abcdef"; /** * Index Of * * Locates and returns the position of a character within a string starting * from a defined offset * * @param _base When being used for a data type this is the extended object * otherwise this is the string acting as the haystack to be * searched * @param _value The needle to search for, at present this is currently * limited to one character * @param _offset The starting point to start searching from which can start * from 0, but must not exceed the length of the string * @return int The position of the needle starting from 0 and returning -1 * in the case of no matches found */ function indexOf( bytes memory _base, string memory _value, uint256 _offset ) internal pure returns (int256) { bytes memory _valueBytes = bytes(_value); assert(_valueBytes.length == 1); for (uint256 i = _offset; i < _base.length; i++) { if (_base[i] == _valueBytes[0]) { return int256(i); } } return -1; } function substring( bytes memory strBytes, uint256 startIndex, uint256 endIndex ) internal pure returns (string memory) { bytes memory result = new bytes(endIndex - startIndex); for (uint256 i = startIndex; i < endIndex; i++) { result[i - startIndex] = strBytes[i]; } return string(result); } function toUint(bytes memory b) internal pure returns (uint256) { uint256 result = 0; for (uint256 i = 0; i < b.length; i++) { uint256 val = uint256(uint8(b[i])); if (val >= 48 && val <= 57) { result = result * 10 + (val - 48); } } return result; } } pragma solidity ^0.8.4; library Minting { // Split the minting blob into token_id and blueprint portions // {token_id}:{blueprint} function split(bytes calldata blob) internal pure returns (uint256, bytes memory) { int256 index = Bytes.indexOf(blob, ":", 0); require(index >= 0, "Separator must exist"); // Trim the { and } from the parameters uint256 tokenID = Bytes.toUint(blob[1:uint256(index) - 1]); uint256 blueprintLength = blob.length - uint256(index) - 3; if (blueprintLength == 0) { return (tokenID, bytes("")); } bytes calldata blueprint = blob[uint256(index) + 2:blob.length - 1]; return (tokenID, blueprint); } } pragma solidity ^0.8.4; abstract contract Mintable is Ownable, IMintable { address public imx; mapping(uint256 => bytes) public blueprints; event AssetMinted(address to, uint256 id, bytes blueprint); constructor(address _owner, address _imx) { imx = _imx; require(_owner != address(0), "Owner must not be empty"); transferOwnership(_owner); } modifier onlyIMX() { require(msg.sender == imx, "Function can only be called by IMX"); _; } function mintFor( address user, uint256 quantity, bytes calldata mintingBlob ) external override onlyIMX { require(quantity == 1, "Mintable: invalid quantity"); (uint256 id, bytes memory blueprint) = Minting.split(mintingBlob); _mintFor(user, id, blueprint); blueprints[id] = blueprint; emit AssetMinted(user, id, blueprint); } function _mintFor( address to, uint256 id, bytes memory blueprint ) internal virtual; } pragma solidity ^0.8.2; contract BATTLECATZ is ERC721, ERC721Enumerable, ERC721Burnable, Ownable, Mintable { using Counters for Counters.Counter; string public baseURI; Counters.Counter private _tokenIdCounter; // Where funds should be sent to address payable public fundsTo; // Maximum supply of the NFT uint256 public maxSupply; // Maximum mints per transaction uint256 public maxPerTx; // Is sale on? bool public sale; // Sale price uint256 public pricePer; uint256 public pricePerPre; uint256 public maxPreMint; uint256 public maxWallet = 3; uint256 public totalSupplied = 0; bool public presale = false; bool public checkwhitelist = true; mapping (address => bool) userAddr; mapping(address => uint256) public minted; // To check how many tokens an address has minted mapping(address => uint256) public mintedLog; // To check how many tokens an address has minted event Deposit(address indexed _from,uint256 _value,uint256 _nfcount); function _mintFor( address user, uint256 id, bytes memory ) internal override { _safeMint(user, id); minted[user] += 1; } constructor(address _owner, address _imx,address payable fundsTo_, uint256 maxSupply_, uint256 maxPerTx_, uint256 pricePer_, uint256 pricePerPre_) ERC721("BATTLECATZ", "BATTLECATZ") Mintable(_owner, _imx){ imx = _imx; require(_owner != address(0), "Owner must not be empty"); transferOwnership(_owner); fundsTo = fundsTo_; maxSupply = maxSupply_; maxPerTx = maxPerTx_; sale = false; pricePer = pricePer_; pricePerPre = pricePerPre_; } function updateFundsTo(address payable newFundsTo) public onlyOwner { fundsTo = newFundsTo; } function enableSale() public onlyOwner { sale = true; } function claimBalance() public onlyOwner { (bool success, ) = fundsTo.call{value: address(this).balance}(""); require(success, "transfer failed"); } function safeMintOwner(address to, uint256 quantity) public onlyOwner { require(quantity != 0, "Requested quantity cannot be zero"); // Cannot mint more than maximum require(quantity <= maxPerTx, "Requested quantity more than maximum"); // Transaction must have at least quantity * price (any more is considered a tip) require(super.totalSupply() + quantity <= maxSupply, "Total supply will exceed limit"); for (uint256 i = 0; i < quantity; i++) { _safeMint(to, _tokenIdCounter.current()); _tokenIdCounter.increment(); } minted[to] += quantity; } function setBaseURI(string memory __baseURI) external onlyOwner { baseURI = __baseURI; } function setMaxPreMint(uint __maxPreMint) external onlyOwner { maxPreMint = __maxPreMint; } function setMaxPerTX(uint __maxPerTX) external onlyOwner { maxPerTx = __maxPerTX; } function _baseURI() internal view override returns (string memory) { return baseURI; } function flipSaleState() public onlyOwner { sale = !sale; } function flipPresaleState() public onlyOwner { presale = !presale; } function flipCheckWhitelist() public onlyOwner { checkwhitelist = !checkwhitelist; } function setMaxWallet(uint _newMaxWallet) external onlyOwner { maxWallet = _newMaxWallet; } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } function whitelistAddress (address user) public onlyOwner { userAddr[user] = true; } function _iswhitelistAddress (address user) public view returns (bool) { return userAddr[user]; } function setPrePrice(uint256 prePrice_) external onlyOwner { pricePerPre = prePrice_; } function setPostPrice(uint256 postPrice_) external onlyOwner { pricePer = postPrice_; } function _preMintPrice() public view returns (uint256) { return pricePerPre; } function _totalMintLog() public view returns (uint256) { return totalSupplied; } function _salePrice() public view returns (uint256) { return pricePer; } function checkTokenExists(uint256 tokenId) public view returns(bool) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return true; } function transfer(uint256 quantity) external payable { // Sale must NOT be enabled require(sale, "Sale already in progress"); require(quantity != 0, "Requested quantity cannot be zero"); require(quantity <= maxPerTx, "Requested quantity more than maximum"); require(quantity * pricePer <= msg.value, "Not enough ether sent"); require(totalSupplied + quantity <= maxSupply, "Purchase would exceed max tokens for presale"); require(mintedLog[msg.sender] + quantity <= maxWallet, "Purchase would exceed max tokens per wallet"); require(!Address.isContract(msg.sender), "Contracts are not allowed to mint"); totalSupplied += quantity; mintedLog[msg.sender] += quantity; emit Deposit(msg.sender,msg.value,quantity); } function transferPreSale(uint256 quantity) external payable { // Sale must NOT be enabled require(!sale, "Sale already in progress"); require(presale,"Presale must be active"); require(quantity != 0, "Requested quantity cannot be zero"); require(quantity <= maxPerTx, "Requested quantity more than maximum"); require(quantity * pricePerPre <= msg.value, "Not enough ether sent"); require(totalSupplied + quantity <= maxPreMint, "Purchase would exceed max tokens for presale"); require(mintedLog[msg.sender] + quantity <= maxWallet, "Purchase would exceed max tokens per wallet"); require(!Address.isContract(msg.sender), "Contracts are not allowed to mint"); mintedLog[msg.sender] += quantity; totalSupplied += quantity; emit Deposit(msg.sender,msg.value,quantity); } }
Sale must NOT be enabled
function transferPreSale(uint256 quantity) external payable { require(!sale, "Sale already in progress"); require(presale,"Presale must be active"); require(quantity != 0, "Requested quantity cannot be zero"); require(quantity <= maxPerTx, "Requested quantity more than maximum"); require(quantity * pricePerPre <= msg.value, "Not enough ether sent"); require(totalSupplied + quantity <= maxPreMint, "Purchase would exceed max tokens for presale"); require(mintedLog[msg.sender] + quantity <= maxWallet, "Purchase would exceed max tokens per wallet"); require(!Address.isContract(msg.sender), "Contracts are not allowed to mint"); mintedLog[msg.sender] += quantity; totalSupplied += quantity; emit Deposit(msg.sender,msg.value,quantity); }
6,884,413
[ 1, 30746, 1297, 4269, 506, 3696, 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, 7412, 1386, 30746, 12, 11890, 5034, 10457, 13, 3903, 8843, 429, 288, 203, 3639, 2583, 12, 5, 87, 5349, 16, 315, 30746, 1818, 316, 4007, 8863, 203, 3639, 2583, 12, 12202, 5349, 10837, 12236, 5349, 1297, 506, 2695, 8863, 203, 3639, 2583, 12, 16172, 480, 374, 16, 315, 11244, 10457, 2780, 506, 3634, 8863, 203, 3639, 2583, 12, 16172, 1648, 943, 2173, 4188, 16, 315, 11244, 10457, 1898, 2353, 4207, 8863, 203, 3639, 2583, 12, 16172, 380, 6205, 2173, 1386, 1648, 1234, 18, 1132, 16, 315, 1248, 7304, 225, 2437, 3271, 8863, 203, 3639, 2583, 12, 4963, 3088, 3110, 397, 10457, 1648, 943, 1386, 49, 474, 16, 315, 23164, 4102, 9943, 943, 2430, 364, 4075, 5349, 8863, 203, 540, 2583, 12, 81, 474, 329, 1343, 63, 3576, 18, 15330, 65, 397, 10457, 1648, 943, 16936, 16, 315, 23164, 4102, 9943, 943, 2430, 1534, 9230, 8863, 203, 3639, 2583, 12, 5, 1887, 18, 291, 8924, 12, 3576, 18, 15330, 3631, 315, 20723, 854, 486, 2935, 358, 312, 474, 8863, 203, 540, 203, 3639, 312, 474, 329, 1343, 63, 3576, 18, 15330, 65, 1011, 10457, 31, 203, 3639, 2078, 3088, 3110, 1011, 10457, 31, 203, 3639, 3626, 4019, 538, 305, 12, 3576, 18, 15330, 16, 3576, 18, 1132, 16, 16172, 1769, 203, 565, 289, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-03-22 */ // SPDX-License-Identifier: GPL-3.0 // File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library 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 = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (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/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (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() { _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); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @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 * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface 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/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (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/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/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: erc721a/contracts/ERC721A.sol // Creator: Chiru Labs pragma solidity ^0.8.4; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerQueryForNonexistentToken(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @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 override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); 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 override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _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 { _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 { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev This is equivalent to _burn(tokenId, false) */ function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: contracts/SKULLTOONS V3.sol //Developer : FazelPejmanfar , Twitter :@Pejmanfarfazel pragma solidity >=0.7.0 <0.9.0; contract SKULLTOONS is ERC721A, Ownable { using Strings for uint256; string public baseURI; string public baseExtension = ".json"; string public notRevealedUri; uint256 public cost = 0.25 ether; uint256 public wlcost = 0.20 ether; uint256 public maxSupply = 3333; uint256 public MaxperWallet = 100; uint256 public MaxperWalletWl = 2; uint256 public MaxperTxWl = 2; uint256 public maxpertx = 50 ; // max mint per tx bool public paused = false; bool public revealed = false; bool public preSale = true; bool public publicSale = false; bytes32 public merkleRoot = 0x7d47dd9d8fd212164c3a9e8d23f89077455d468a3e287590d7f66b9c5ed8dcfd; constructor( string memory _initBaseURI, string memory _initNotRevealedUri ) ERC721A("Skulltoons", "Skulltoon") { setBaseURI(_initBaseURI); setNotRevealedURI(_initNotRevealedUri); } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function _startTokenId() internal view virtual override returns (uint256) { return 1; } // public function mint(uint256 tokens) public payable { require(!paused, "TAS: oops contract is paused"); require(publicSale, "TAS: Sale Hasn't started yet"); uint256 supply = totalSupply(); uint256 ownerTokenCount = balanceOf(_msgSender()); require(tokens > 0, "TAS: need to mint at least 1 NFT"); require(tokens <= maxpertx, "TAS: max mint amount per tx exceeded"); require(supply + tokens <= maxSupply, "TAS: We Soldout"); require(ownerTokenCount + tokens <= MaxperWallet, "TAS: Max NFT Per Wallet exceeded"); require(msg.value >= cost * tokens, "TAS: insufficient funds"); _safeMint(_msgSender(), tokens); } /// @dev presale mint for whitelisted function presalemint(uint256 tokens, bytes32[] calldata merkleProof) public payable { require(!paused, "TAS: oops contract is paused"); require(preSale, "TAS: Presale Hasn't started yet"); require(MerkleProof.verify(merkleProof, merkleRoot, keccak256(abi.encodePacked(msg.sender))), "TAS: You are not Whitelisted"); uint256 supply = totalSupply(); uint256 ownerTokenCount = balanceOf(_msgSender()); require(ownerTokenCount + tokens <= MaxperWalletWl, "TAS: Max NFT Per Wallet exceeded"); require(tokens > 0, "TAS: need to mint at least 1 NFT"); require(tokens <= MaxperTxWl, "TAS: max mint per Tx exceeded"); require(supply + tokens <= maxSupply, "TAS: Whitelist MaxSupply exceeded"); require(msg.value >= wlcost * tokens, "TAS: insufficient funds"); _safeMint(_msgSender(), tokens); } /// @dev use it for giveaway and mint for yourself function gift(uint256 _mintAmount, address destination) public onlyOwner { require(_mintAmount > 0, "need to mint at least 1 NFT"); uint256 supply = totalSupply(); require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded"); _safeMint(destination, _mintAmount); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721AMetadata: URI query for nonexistent token" ); if(revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } //only owner function reveal(bool _state) public onlyOwner { revealed = _state; } function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner { merkleRoot = _merkleRoot; } function setMaxPerWallet(uint256 _limit) public onlyOwner { MaxperWallet = _limit; } function setWlMaxPerWallet(uint256 _limit) public onlyOwner { MaxperWalletWl = _limit; } function setmaxpertx(uint256 _maxpertx) public onlyOwner { maxpertx = _maxpertx; } function setWLMaxpertx(uint256 _wlmaxpertx) public onlyOwner { MaxperTxWl = _wlmaxpertx; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setWlCost(uint256 _newWlCost) public onlyOwner { wlcost = _newWlCost; } function setMaxsupply(uint256 _newsupply) public onlyOwner { maxSupply = _newsupply; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function pause(bool _state) public onlyOwner { paused = _state; } function togglepreSale(bool _state) external onlyOwner { preSale = _state; } function togglepublicSale(bool _state) external onlyOwner { publicSale = _state; } function withdraw() public payable onlyOwner { (bool success, ) = payable(msg.sender).call{value: address(this).balance}(""); require(success); } }
File: contracts/SKULLTOONS V3.solDeveloper : FazelPejmanfar , Twitter :@Pejmanfarfazel
contract SKULLTOONS is ERC721A, Ownable { using Strings for uint256; string public baseURI; string public baseExtension = ".json"; string public notRevealedUri; uint256 public cost = 0.25 ether; uint256 public wlcost = 0.20 ether; uint256 public maxSupply = 3333; uint256 public MaxperWallet = 100; uint256 public MaxperWalletWl = 2; uint256 public MaxperTxWl = 2; bool public paused = false; bool public revealed = false; bool public preSale = true; bool public publicSale = false; bytes32 public merkleRoot = 0x7d47dd9d8fd212164c3a9e8d23f89077455d468a3e287590d7f66b9c5ed8dcfd; constructor( string memory _initBaseURI, string memory _initNotRevealedUri function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity } pragma solidity >=0.7.0 <0.9.0; ) ERC721A("Skulltoons", "Skulltoon") { setBaseURI(_initBaseURI); setNotRevealedURI(_initNotRevealedUri); } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function _startTokenId() internal view virtual override returns (uint256) { return 1; } function mint(uint256 tokens) public payable { require(!paused, "TAS: oops contract is paused"); require(publicSale, "TAS: Sale Hasn't started yet"); uint256 supply = totalSupply(); uint256 ownerTokenCount = balanceOf(_msgSender()); require(tokens > 0, "TAS: need to mint at least 1 NFT"); require(tokens <= maxpertx, "TAS: max mint amount per tx exceeded"); require(supply + tokens <= maxSupply, "TAS: We Soldout"); require(ownerTokenCount + tokens <= MaxperWallet, "TAS: Max NFT Per Wallet exceeded"); require(msg.value >= cost * tokens, "TAS: insufficient funds"); _safeMint(_msgSender(), tokens); } function presalemint(uint256 tokens, bytes32[] calldata merkleProof) public payable { require(!paused, "TAS: oops contract is paused"); require(preSale, "TAS: Presale Hasn't started yet"); require(MerkleProof.verify(merkleProof, merkleRoot, keccak256(abi.encodePacked(msg.sender))), "TAS: You are not Whitelisted"); uint256 supply = totalSupply(); uint256 ownerTokenCount = balanceOf(_msgSender()); require(ownerTokenCount + tokens <= MaxperWalletWl, "TAS: Max NFT Per Wallet exceeded"); require(tokens > 0, "TAS: need to mint at least 1 NFT"); require(tokens <= MaxperTxWl, "TAS: max mint per Tx exceeded"); require(supply + tokens <= maxSupply, "TAS: Whitelist MaxSupply exceeded"); require(msg.value >= wlcost * tokens, "TAS: insufficient funds"); _safeMint(_msgSender(), tokens); } function gift(uint256 _mintAmount, address destination) public onlyOwner { require(_mintAmount > 0, "need to mint at least 1 NFT"); uint256 supply = totalSupply(); require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded"); _safeMint(destination, _mintAmount); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721AMetadata: URI query for nonexistent token" ); if(revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721AMetadata: URI query for nonexistent token" ); if(revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } function reveal(bool _state) public onlyOwner { revealed = _state; } function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner { merkleRoot = _merkleRoot; } function setMaxPerWallet(uint256 _limit) public onlyOwner { MaxperWallet = _limit; } function setWlMaxPerWallet(uint256 _limit) public onlyOwner { MaxperWalletWl = _limit; } function setmaxpertx(uint256 _maxpertx) public onlyOwner { maxpertx = _maxpertx; } function setWLMaxpertx(uint256 _wlmaxpertx) public onlyOwner { MaxperTxWl = _wlmaxpertx; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setWlCost(uint256 _newWlCost) public onlyOwner { wlcost = _newWlCost; } function setMaxsupply(uint256 _newsupply) public onlyOwner { maxSupply = _newsupply; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function pause(bool _state) public onlyOwner { paused = _state; } function togglepreSale(bool _state) external onlyOwner { preSale = _state; } function togglepublicSale(bool _state) external onlyOwner { publicSale = _state; } function withdraw() public payable onlyOwner { require(success); } (bool success, ) = payable(msg.sender).call{value: address(this).balance}(""); }
15,146,540
[ 1, 812, 30, 20092, 19, 11129, 2705, 4296, 673, 55, 776, 23, 18, 18281, 28145, 294, 478, 27478, 11227, 78, 4728, 31246, 269, 19551, 294, 36, 11227, 78, 4728, 31246, 507, 94, 292, 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, 16351, 12038, 2705, 4296, 673, 55, 353, 4232, 39, 27, 5340, 37, 16, 14223, 6914, 288, 203, 225, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 225, 533, 1071, 1026, 3098, 31, 203, 225, 533, 1071, 1026, 3625, 273, 3552, 1977, 14432, 203, 225, 533, 1071, 486, 426, 537, 18931, 3006, 31, 203, 225, 2254, 5034, 1071, 6991, 273, 374, 18, 2947, 225, 2437, 31, 203, 225, 2254, 5034, 1071, 19564, 12398, 273, 374, 18, 3462, 225, 2437, 31, 203, 225, 2254, 5034, 1071, 943, 3088, 1283, 273, 890, 3707, 23, 31, 203, 225, 2254, 5034, 1071, 4238, 457, 16936, 273, 2130, 31, 203, 225, 2254, 5034, 1071, 4238, 457, 16936, 59, 80, 273, 576, 31, 203, 225, 2254, 5034, 1071, 4238, 457, 4188, 59, 80, 273, 576, 31, 203, 225, 1426, 1071, 17781, 273, 629, 31, 203, 225, 1426, 1071, 283, 537, 18931, 273, 629, 31, 203, 225, 1426, 1071, 675, 30746, 273, 638, 31, 203, 225, 1426, 1071, 1071, 30746, 273, 629, 31, 203, 225, 1731, 1578, 1071, 30235, 2375, 273, 374, 92, 27, 72, 9462, 449, 29, 72, 28, 8313, 22, 2138, 23147, 71, 23, 69, 29, 73, 28, 72, 4366, 74, 6675, 20, 4700, 24, 2539, 72, 8749, 28, 69, 23, 73, 6030, 5877, 9349, 72, 27, 74, 6028, 70, 29, 71, 25, 329, 28, 7201, 8313, 31, 203, 203, 225, 3885, 12, 203, 565, 533, 3778, 389, 2738, 2171, 3098, 16, 203, 565, 533, 3778, 389, 2738, 1248, 426, 537, 18931, 3006, 203, 565, 445, 389, 5771, 1345, 1429, 2 ]
./partial_match/5/0xC9a3DdadC753e6a7675Aa125991096623d06c437/sources/project_/contracts/governance/GoodDollarStaking.sol
* @dev interest rate per one block in 1e18 precision. for example APY=5% then per block = nroot(1+0.05,numberOfBlocksPerYear) nroot(1.05,6000000) = 1.000000008131694 in 1e18 = 1000000008131694000 @param _interestRatePerBlock nth blocks per year root of APY - nroot(1+0.05,numberOfBlocksPerYear)/
function setGdApy(uint128 _interestRatePerBlock) public { _onlyAvatar(); _setAPY(_interestRatePerBlock); require( Math64x64.mulu( Math64x64.pow(interestRatePerBlockX64, numberOfBlocksPerYear), 1e4 ) < 12000 ); emit APYSet(_interestRatePerBlock); }
16,856,433
[ 1, 2761, 395, 4993, 1534, 1245, 1203, 316, 404, 73, 2643, 6039, 18, 364, 3454, 14410, 61, 33, 25, 9, 1508, 1534, 1203, 273, 290, 3085, 12, 21, 15, 20, 18, 6260, 16, 2696, 951, 6450, 2173, 5593, 13, 290, 3085, 12, 21, 18, 6260, 16, 26, 9449, 13, 273, 404, 18, 12648, 28, 3437, 2313, 11290, 316, 404, 73, 2643, 273, 2130, 9449, 28, 3437, 2313, 11290, 3784, 225, 389, 2761, 395, 4727, 2173, 1768, 20196, 4398, 1534, 3286, 1365, 434, 14410, 61, 300, 290, 3085, 12, 21, 15, 20, 18, 6260, 16, 2696, 951, 6450, 2173, 5593, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 202, 915, 26770, 72, 1294, 93, 12, 11890, 10392, 389, 2761, 395, 4727, 2173, 1768, 13, 1071, 288, 203, 202, 202, 67, 3700, 23999, 5621, 203, 202, 202, 67, 542, 2203, 61, 24899, 2761, 395, 4727, 2173, 1768, 1769, 203, 202, 202, 6528, 12, 203, 1082, 202, 10477, 1105, 92, 1105, 18, 16411, 89, 12, 203, 9506, 202, 10477, 1105, 92, 1105, 18, 23509, 12, 2761, 395, 4727, 2173, 1768, 60, 1105, 16, 7922, 6450, 2173, 5593, 3631, 203, 9506, 202, 21, 73, 24, 203, 1082, 202, 13, 411, 2593, 3784, 203, 202, 202, 1769, 203, 203, 202, 202, 18356, 14410, 61, 694, 24899, 2761, 395, 4727, 2173, 1768, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-07-20 */ // File @openzeppelin/contracts/utils/introspection/[email protected] // 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); } // File @openzeppelin/contracts/token/ERC721/[email protected] 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/[email protected] 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/token/ERC721/extensions/[email protected] 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/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/utils/[email protected] 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; } } // File @openzeppelin/contracts/utils/[email protected] 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/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File @openzeppelin/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @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(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File @openzeppelin/contracts/access/[email protected] 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() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @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]; } } } // File contracts/MerkleProof.sol pragma solidity ^0.8.4; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ contract MerkleProof { bytes32 public root; constructor(bytes32 _root) { root = _root; } function verifyURI(string memory tokenURI, bytes32[] memory proof) public view returns (bool) { bytes32 leaf = keccak256(abi.encodePacked(tokenURI)); return verify(leaf, proof); } /** * @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 leaf, bytes32[] memory proof) public view returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256( abi.encodePacked(computedHash, proofElement) ); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256( abi.encodePacked(proofElement, computedHash) ); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // File contracts/NFTPoke.sol pragma solidity ^0.8.4; contract NFTPoke is Ownable, ERC721URIStorage, MerkleProof { using Counters for Counters.Counter; Counters.Counter private _tokenIds; string public baseURI = "https://ipfs.io/ipfs/"; // marks the token as being minted mapping(bytes32 => bool) public mintedTokens; // find tokenId by tokenURI mapping(bytes32 => uint256) public uriToTokenId; // find all tokens of an address mapping(address => uint256[]) public tokensByAddress; // the starting price to mint an NFT uint256 public currentPrice; // the price increase after each NFT is minted uint256 public priceIncrease; // the number of tokens that will not get price increases uint256 public numberOfTokensAtSamePrice = 200; // maximum number of hard minted tokens uint256 public maxHardMinted = 242; // the current number of hard minted tokens uint256 public hardMinted; // maximum number of tokens that can be minted uint256 public maxMinted = 13000 + maxHardMinted; event SetBaseUri(address indexed _owner, string initialBaseURI, string finalBaseURI); event MintedOwner(string tokenURI, uint256 tokenId); event Minted(address indexed _owner, uint256 price, string tokenURI, uint256 tokenId); event MintedMultiple(address indexed _owner, uint256 price, uint256 tokenLength); event TransferToken(address indexed from, address indexed to, uint256 tokenId); constructor(string memory nftName, string memory nftSymbol, bytes32 root, uint256 _currentPrice, uint256 _priceIncrease) ERC721(nftName, nftSymbol) MerkleProof(root) { currentPrice = _currentPrice; priceIncrease = _priceIncrease; } /** * @dev See {IERC721-safeTransferFrom}. * @param from address from which to transfer the token * @param to address to which to transfer the token * @param tokenId to transfer */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { require(ownerOf(tokenId) == msg.sender, "The owner is not the sender"); uint256 length = tokensByAddress[from].length; for (uint i = 0; i < length; i++) { if (tokensByAddress[from][i] == tokenId) { tokensByAddress[from][i] = tokensByAddress[from][length - 1]; tokensByAddress[from].pop(); tokensByAddress[to].push(tokenId); super.safeTransferFrom(from, to, tokenId); emit TransferToken(from, to, tokenId); return; } } revert("There was not found any token"); } /** * @dev Return the value of the current price to mint a NFT * @return value of 'number' */ function getCurrentPrice() public view returns (uint256) { return currentPrice; } /** * @dev Return the list of tokenIds assigned for a specific address * @param owner address for which we return the token list * @return list value of 'number' */ function getTokensOf(address owner) public view returns (uint256[]memory) { return tokensByAddress[owner]; } /** * @dev Return if a specific token URI was already minted * @param tokenURI string to be verified * @return bool value */ function isMinted(string memory tokenURI) public view returns (bool) { return mintedTokens[hashed(tokenURI)]; } /** * @dev Return the hash of the given tokenURI * @param tokenURI string for which to calculate the hash * @return bytes32 hash value */ function hashed(string memory tokenURI) internal pure returns (bytes32) { return keccak256(abi.encodePacked(tokenURI)); } /** * @dev Mint by owner a given list of hashes * @param hashes string list to mint */ function mintByOwner(string[] memory hashes) public onlyOwner { require(hardMinted + hashes.length <= maxHardMinted, "There are too many hard minted tokens"); for (uint i = 0; i < hashes.length; i++) { mintItemWithoutProof(hashes[i]); hardMinted++; } } /** * @dev Set the baseURI to a given tokenURI * @param uri string to save */ function setBaseURI(string memory uri) public onlyOwner { baseURI = uri; emit SetBaseUri(msg.sender, baseURI, uri); } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overwritten * in child contracts. */ function _baseURI() internal view override returns (string memory) { return baseURI; } /** * @dev Get the current number of minted NFTs * @return uint256 value */ function getCurrentNumberOfNFTs() public view returns (uint256) { return _tokenIds.current(); } /** * @dev Return a tokenId given a string tokenURI * @param tokenURI string to be verified * @return uint256 value */ function getTokenIdByTokenURI(string memory tokenURI) public view returns (uint256) { return uriToTokenId[hashed(tokenURI)]; } /** * @dev Verify that the current tokenURI is part of the root merkleTree * @param tokenURI string to be verified */ modifier validURI(string memory tokenURI, bytes32[] memory proof) { require(verifyURI(tokenURI, proof), "Not valid tokenURI"); _; } /** * @dev Mint a list of NFTs as owner * @param tokenURI string */ function mintItemWithoutProof(string memory tokenURI) internal { bytes32 uriHash = hashed(tokenURI); // increment the number of tokens minted _tokenIds.increment(); // get a new token id uint256 id = _tokenIds.current(); // mint the new id to the sender _mint(msg.sender, id); // set the tokenURI for the minted token _setTokenURI(id, tokenURI); // link the tokenURI with the token id uriToTokenId[uriHash] = id; // mark the tokenURI token as minted mintedTokens[uriHash] = true; tokensByAddress[msg.sender].push(id); emit MintedOwner(tokenURI, id); } /** * @dev It is possible that funds were sent to this address before the contract was deployed. * We can flush those funds to the destination address. */ function flush() public onlyOwner { address payable ownerAddress = payable(owner()); ownerAddress.transfer(address(this).balance); } /** * @dev Mint a list of tokenURIs * @param tokenURIs string list of * @param proofs bytes32 list */ function mintItems(string[] memory tokenURIs, bytes32[][]memory proofs) public payable returns (uint256[]memory) { require(tokenURIs.length == proofs.length, "The input number of token URIs length is not the same as the number of proofs"); require(msg.value >= currentPrice * tokenURIs.length, "value is smaller than current price"); require(_tokenIds.current() < maxMinted, "No more tokens can be minted"); require(_tokenIds.current() + tokenURIs.length <= maxMinted, "The number of tokens to mint is greater than maximum allowed"); uint256[] memory rez = new uint256[](tokenURIs.length); uint256 oldId = _tokenIds.current(); for (uint i = 0; i < tokenURIs.length; i++) { require(verifyURI(tokenURIs[i], proofs[i]), "Not valid tokenURI"); bytes32 uriHash = hashed(tokenURIs[i]); //make sure they are only minting something that is not already minted require(!mintedTokens[uriHash], "Token already minted"); // get a new token id uint256 id = _tokenIds.current() + 1; // mint the new id to the sender _mint(msg.sender, id); // set the tokenURI for the minted token _setTokenURI(id, tokenURIs[i]); // link the tokenURI with the token id uriToTokenId[uriHash] = id; // mark the tokenURI token as minted mintedTokens[uriHash] = true; // increment the number of tokens minted _tokenIds.increment(); tokensByAddress[msg.sender].push(id); rez[i] = id; } uint256 maxStableId = numberOfTokensAtSamePrice + hardMinted; if (_tokenIds.current() >= maxStableId) { if (oldId < maxStableId) { uint256 mintedTokensWithPriceIncrease = tokenURIs.length - (maxStableId - oldId); // increase price of the next token to be minted currentPrice = currentPrice + priceIncrease * mintedTokensWithPriceIncrease; } else { // increase price of the next token to be minted currentPrice = currentPrice + priceIncrease * tokenURIs.length; } } address payable ownerAddress = payable(owner()); ownerAddress.transfer(msg.value); emit MintedMultiple(msg.sender, currentPrice, tokenURIs.length); return rez; } /** * @dev Mint a NFT based on the tokenURI * @param tokenURI string * @param proof bytes32 list */ function mintItem(string memory tokenURI, bytes32[] memory proof) public payable validURI(tokenURI, proof) returns (uint256) { require(msg.value >= currentPrice, "value is smaller than current price"); require(_tokenIds.current() < maxMinted, "No more tokens can be minted"); bytes32 uriHash = hashed(tokenURI); //make sure they are only minting something that is not already minted require(!mintedTokens[uriHash], "Token already minted"); // get a new token id uint256 id = _tokenIds.current() + 1; // mint the new id to the sender _mint(msg.sender, id); // set the tokenURI for the minted token _setTokenURI(id, tokenURI); // link the tokenURI with the token id uriToTokenId[uriHash] = id; // mark the tokenURI token as minted mintedTokens[uriHash] = true; // increment the number of tokens minted _tokenIds.increment(); tokensByAddress[msg.sender].push(id); if (id >= numberOfTokensAtSamePrice + hardMinted) { // increase price of the next token to be minted currentPrice = currentPrice + priceIncrease; } address payable ownerAddress = payable(owner()); ownerAddress.transfer(msg.value); emit Minted(msg.sender, currentPrice, tokenURI, id); // returns the current minted token id return id; } }
* @dev Mint a NFT based on the tokenURI @param tokenURI string @param proof bytes32 list/make sure they are only minting something that is not already minted get a new token id mint the new id to the sender set the tokenURI for the minted token link the tokenURI with the token id mark the tokenURI token as minted increment the number of tokens minted increase price of the next token to be minted
function mintItem(string memory tokenURI, bytes32[] memory proof) public payable validURI(tokenURI, proof) returns (uint256) { require(msg.value >= currentPrice, "value is smaller than current price"); require(_tokenIds.current() < maxMinted, "No more tokens can be minted"); bytes32 uriHash = hashed(tokenURI); require(!mintedTokens[uriHash], "Token already minted"); uint256 id = _tokenIds.current() + 1; _mint(msg.sender, id); _setTokenURI(id, tokenURI); uriToTokenId[uriHash] = id; mintedTokens[uriHash] = true; _tokenIds.increment(); tokensByAddress[msg.sender].push(id); if (id >= numberOfTokensAtSamePrice + hardMinted) { currentPrice = currentPrice + priceIncrease; } address payable ownerAddress = payable(owner()); ownerAddress.transfer(msg.value); emit Minted(msg.sender, currentPrice, tokenURI, id); }
2,178,284
[ 1, 49, 474, 279, 423, 4464, 2511, 603, 326, 1147, 3098, 225, 1147, 3098, 533, 225, 14601, 1731, 1578, 666, 19, 6540, 3071, 2898, 854, 1338, 312, 474, 310, 5943, 716, 353, 486, 1818, 312, 474, 329, 225, 336, 279, 394, 1147, 612, 225, 312, 474, 326, 394, 612, 358, 326, 5793, 225, 444, 326, 1147, 3098, 364, 326, 312, 474, 329, 1147, 225, 1692, 326, 1147, 3098, 598, 326, 1147, 612, 225, 2267, 326, 1147, 3098, 1147, 487, 312, 474, 329, 225, 5504, 326, 1300, 434, 2430, 312, 474, 329, 225, 10929, 6205, 434, 326, 1024, 1147, 358, 506, 312, 474, 329, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 312, 474, 1180, 12, 1080, 3778, 1147, 3098, 16, 1731, 1578, 8526, 3778, 14601, 13, 203, 565, 1071, 8843, 429, 203, 565, 923, 3098, 12, 2316, 3098, 16, 14601, 13, 203, 565, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 783, 5147, 16, 315, 1132, 353, 10648, 2353, 783, 6205, 8863, 203, 3639, 2583, 24899, 2316, 2673, 18, 2972, 1435, 411, 943, 49, 474, 329, 16, 315, 2279, 1898, 2430, 848, 506, 312, 474, 329, 8863, 203, 203, 3639, 1731, 1578, 2003, 2310, 273, 14242, 12, 2316, 3098, 1769, 203, 203, 3639, 2583, 12, 5, 81, 474, 329, 5157, 63, 1650, 2310, 6487, 315, 1345, 1818, 312, 474, 329, 8863, 203, 203, 3639, 2254, 5034, 612, 273, 389, 2316, 2673, 18, 2972, 1435, 397, 404, 31, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 612, 1769, 203, 3639, 389, 542, 1345, 3098, 12, 350, 16, 1147, 3098, 1769, 203, 3639, 2003, 774, 1345, 548, 63, 1650, 2310, 65, 273, 612, 31, 203, 3639, 312, 474, 329, 5157, 63, 1650, 2310, 65, 273, 638, 31, 203, 3639, 389, 2316, 2673, 18, 15016, 5621, 203, 203, 3639, 2430, 858, 1887, 63, 3576, 18, 15330, 8009, 6206, 12, 350, 1769, 203, 203, 3639, 309, 261, 350, 1545, 7922, 5157, 861, 8650, 5147, 397, 7877, 49, 474, 329, 13, 288, 203, 5411, 783, 5147, 273, 783, 5147, 397, 6205, 382, 11908, 31, 203, 3639, 289, 203, 203, 3639, 1758, 8843, 429, 3410, 1887, 273, 8843, 429, 2 ]
pragma solidity 0.4.24; // produced by the Solididy File Flattener (c) David Appleton 2018 // contact : [email protected] // released under Apache 2.0 licence /* // produced by the Solididy File Flattener (c) David Appleton 2018 // contact : [email protected] // released under Apache 2.0 licence */ // produced by the Solididy File Flattener (c) David Appleton 2018 // contact : [email protected] // released under Apache 2.0 licence 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. */ 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 newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Token { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant public returns (uint256 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, uint256 _value) public 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, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public 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) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { function transfer(address _to, uint256 _value) public returns (bool success) { //Default assumes totalSupply can't be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. //Replace the if with this one instead. //require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]); require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { //same as above. Replace this line with the following if you want to protect against wrapping uints. //require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]); require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } contract MintAndBurnToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = 'H0.1'; //human 0.1 standard. Just an arbitrary versioning scheme. constructor( string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { name = _tokenName; // Set the name for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = SafeMath.add(_amount, totalSupply); balances[_to] = SafeMath.add(_amount,balances[_to]); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } // ----------------------------------- // BURN FUNCTIONS BELOW // https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC20/BurnableToken.sol // ----------------------------------- event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) onlyOwner public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = SafeMath.sub(balances[_who],_value); totalSupply = SafeMath.sub(totalSupply,_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } contract HumanStandardToken is StandardToken { /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = 'H0.1'; //human 0.1 standard. Just an arbitrary versioning scheme. constructor( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { balances[msg.sender] = _initialAmount; // Give the creator all initial tokens totalSupply = _initialAmount; // Update total supply name = _tokenName; // Set the name for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. require(_spender.call(bytes4(bytes32(keccak256("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)); return true; } } 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; } } contract SpankBank { using BytesLib for bytes; using SafeMath for uint256; event SpankBankCreated( uint256 periodLength, uint256 maxPeriods, address spankAddress, uint256 initialBootySupply, string bootyTokenName, uint8 bootyDecimalUnits, string bootySymbol ); event StakeEvent( address staker, uint256 period, uint256 spankPoints, uint256 spankAmount, uint256 stakePeriods, address delegateKey, address bootyBase ); event SendFeesEvent ( address sender, uint256 bootyAmount ); event MintBootyEvent ( uint256 targetBootySupply, uint256 totalBootySupply ); event CheckInEvent ( address staker, uint256 period, uint256 spankPoints, uint256 stakerEndingPeriod ); event ClaimBootyEvent ( address staker, uint256 period, uint256 bootyOwed ); event WithdrawStakeEvent ( address staker, uint256 totalSpankToWithdraw ); event SplitStakeEvent ( address staker, address newAddress, address newDelegateKey, address newBootyBase, uint256 spankAmount ); event VoteToCloseEvent ( address staker, uint256 period ); event UpdateDelegateKeyEvent ( address staker, address newDelegateKey ); event UpdateBootyBaseEvent ( address staker, address newBootyBase ); event ReceiveApprovalEvent ( address from, address tokenContract ); /*********************************** VARIABLES SET AT CONTRACT DEPLOYMENT ************************************/ // GLOBAL CONSTANT VARIABLES uint256 public periodLength; // time length of each period in seconds uint256 public maxPeriods; // the maximum # of periods a staker can stake for uint256 public totalSpankStaked; // the total SPANK staked across all stakers bool public isClosed; // true if voteToClose has passed, allows early withdrawals // ERC-20 BASED TOKEN WITH SOME ADDED PROPERTIES FOR HUMAN READABILITY // https://github.com/ConsenSys/Tokens/blob/master/contracts/HumanStandardToken.sol HumanStandardToken public spankToken; MintAndBurnToken public bootyToken; // LOOKUP TABLE FOR SPANKPOINTS BY PERIOD // 1 -> 45% // 2 -> 50% // ... // 12 -> 100% mapping(uint256 => uint256) public pointsTable; /************************************* INTERAL ACCOUNTING **************************************/ uint256 public currentPeriod = 0; struct Staker { uint256 spankStaked; // the amount of spank staked uint256 startingPeriod; // the period this staker started staking uint256 endingPeriod; // the period after which this stake expires mapping(uint256 => uint256) spankPoints; // the spankPoints per period mapping(uint256 => bool) didClaimBooty; // true if staker claimed BOOTY for that period mapping(uint256 => bool) votedToClose; // true if staker voted to close for that period address delegateKey; // address used to call checkIn and claimBooty address bootyBase; // destination address to receive BOOTY } mapping(address => Staker) public stakers; struct Period { uint256 bootyFees; // the amount of BOOTY collected in fees uint256 totalSpankPoints; // the total spankPoints of all stakers uint256 bootyMinted; // the amount of BOOTY minted bool mintingComplete; // true if BOOTY has already been minted for this period uint256 startTime; // the starting unix timestamp in seconds uint256 endTime; // the ending unix timestamp in seconds uint256 closingVotes; // the total votes to close this period } mapping(uint256 => Period) public periods; mapping(address => address) public stakerByDelegateKey; modifier SpankBankIsOpen() { require(isClosed == false); _; } constructor ( uint256 _periodLength, uint256 _maxPeriods, address spankAddress, uint256 initialBootySupply, string bootyTokenName, uint8 bootyDecimalUnits, string bootySymbol ) public { periodLength = _periodLength; maxPeriods = _maxPeriods; spankToken = HumanStandardToken(spankAddress); bootyToken = new MintAndBurnToken(bootyTokenName, bootyDecimalUnits, bootySymbol); bootyToken.mint(this, initialBootySupply); uint256 startTime = now; periods[currentPeriod].startTime = startTime; periods[currentPeriod].endTime = SafeMath.add(startTime, periodLength); bootyToken.transfer(msg.sender, initialBootySupply); // initialize points table pointsTable[0] = 0; pointsTable[1] = 45; pointsTable[2] = 50; pointsTable[3] = 55; pointsTable[4] = 60; pointsTable[5] = 65; pointsTable[6] = 70; pointsTable[7] = 75; pointsTable[8] = 80; pointsTable[9] = 85; pointsTable[10] = 90; pointsTable[11] = 95; pointsTable[12] = 100; emit SpankBankCreated(_periodLength, _maxPeriods, spankAddress, initialBootySupply, bootyTokenName, bootyDecimalUnits, bootySymbol); } // Used to create a new staking position - verifies that the caller is not staking function stake(uint256 spankAmount, uint256 stakePeriods, address delegateKey, address bootyBase) SpankBankIsOpen public { doStake(msg.sender, spankAmount, stakePeriods, delegateKey, bootyBase); } function doStake(address stakerAddress, uint256 spankAmount, uint256 stakePeriods, address delegateKey, address bootyBase) internal { updatePeriod(); require(stakePeriods > 0 && stakePeriods <= maxPeriods, "stake not between zero and maxPeriods"); // stake 1-12 (max) periods require(spankAmount > 0, "stake is 0"); // stake must be greater than 0 // the staker must not have an active staking position require(stakers[stakerAddress].startingPeriod == 0, "staker already exists"); // transfer SPANK to this contract - assumes sender has already "allowed" the spankAmount require(spankToken.transferFrom(stakerAddress, this, spankAmount)); stakers[stakerAddress] = Staker(spankAmount, currentPeriod + 1, currentPeriod + stakePeriods, delegateKey, bootyBase); _updateNextPeriodPoints(stakerAddress, stakePeriods); totalSpankStaked = SafeMath.add(totalSpankStaked, spankAmount); require(delegateKey != address(0), "delegateKey does not exist"); require(bootyBase != address(0), "bootyBase does not exist"); require(stakerByDelegateKey[delegateKey] == address(0), "delegateKey already used"); stakerByDelegateKey[delegateKey] = stakerAddress; emit StakeEvent( stakerAddress, currentPeriod + 1, stakers[stakerAddress].spankPoints[currentPeriod + 1], spankAmount, stakePeriods, delegateKey, bootyBase ); } // Called during stake and checkIn, assumes those functions prevent duplicate calls // for the same staker. function _updateNextPeriodPoints(address stakerAddress, uint256 stakingPeriods) internal { Staker storage staker = stakers[stakerAddress]; uint256 stakerPoints = SafeMath.div(SafeMath.mul(staker.spankStaked, pointsTable[stakingPeriods]), 100); // add staker spankpoints to total spankpoints for the next period uint256 totalPoints = periods[currentPeriod + 1].totalSpankPoints; totalPoints = SafeMath.add(totalPoints, stakerPoints); periods[currentPeriod + 1].totalSpankPoints = totalPoints; staker.spankPoints[currentPeriod + 1] = stakerPoints; } function receiveApproval(address from, uint256 amount, address tokenContract, bytes extraData) SpankBankIsOpen public returns (bool success) { address delegateKeyFromBytes = extraData.toAddress(12); address bootyBaseFromBytes = extraData.toAddress(44); uint256 periodFromBytes = extraData.toUint(64); emit ReceiveApprovalEvent(from, tokenContract); doStake(from, amount, periodFromBytes, delegateKeyFromBytes, bootyBaseFromBytes); return true; } function sendFees(uint256 bootyAmount) SpankBankIsOpen public { updatePeriod(); require(bootyAmount > 0, "fee is zero"); // fees must be greater than 0 require(bootyToken.transferFrom(msg.sender, this, bootyAmount)); bootyToken.burn(bootyAmount); uint256 currentBootyFees = periods[currentPeriod].bootyFees; currentBootyFees = SafeMath.add(bootyAmount, currentBootyFees); periods[currentPeriod].bootyFees = currentBootyFees; emit SendFeesEvent(msg.sender, bootyAmount); } function mintBooty() SpankBankIsOpen public { updatePeriod(); // can't mint BOOTY during period 0 - would result in integer underflow require(currentPeriod > 0, "current period is zero"); Period storage period = periods[currentPeriod - 1]; require(!period.mintingComplete, "minting already complete"); // cant mint BOOTY twice period.mintingComplete = true; uint256 targetBootySupply = SafeMath.mul(period.bootyFees, 20); uint256 totalBootySupply = bootyToken.totalSupply(); if (targetBootySupply > totalBootySupply) { uint256 bootyMinted = targetBootySupply - totalBootySupply; bootyToken.mint(this, bootyMinted); period.bootyMinted = bootyMinted; emit MintBootyEvent(targetBootySupply, totalBootySupply); } } // This will check the current time and update the current period accordingly // - called from all write functions to ensure the period is always up to date before any writes // - can also be called externally, but there isn't a good reason for why you would want to // - the while loop protects against the edge case where we miss a period function updatePeriod() public { while (now >= periods[currentPeriod].endTime) { Period memory prevPeriod = periods[currentPeriod]; currentPeriod += 1; periods[currentPeriod].startTime = prevPeriod.endTime; periods[currentPeriod].endTime = SafeMath.add(prevPeriod.endTime, periodLength); } } // In order to receive Booty, each staker will have to check-in every period. // This check-in will compute the spankPoints locally and globally for each staker. function checkIn(uint256 updatedEndingPeriod) SpankBankIsOpen public { updatePeriod(); address stakerAddress = stakerByDelegateKey[msg.sender]; Staker storage staker = stakers[stakerAddress]; require(staker.spankStaked > 0, "staker stake is zero"); require(currentPeriod < staker.endingPeriod, "staker expired"); require(staker.spankPoints[currentPeriod+1] == 0, "staker has points for next period"); // If updatedEndingPeriod is 0, don't update the ending period if (updatedEndingPeriod > 0) { require(updatedEndingPeriod > staker.endingPeriod, "updatedEndingPeriod less than or equal to staker endingPeriod"); require(updatedEndingPeriod <= currentPeriod + maxPeriods, "updatedEndingPeriod greater than currentPeriod and maxPeriods"); staker.endingPeriod = updatedEndingPeriod; } uint256 stakePeriods = staker.endingPeriod - currentPeriod; _updateNextPeriodPoints(stakerAddress, stakePeriods); emit CheckInEvent(stakerAddress, currentPeriod + 1, staker.spankPoints[currentPeriod + 1], staker.endingPeriod); } function claimBooty(uint256 claimPeriod) public { updatePeriod(); Period memory period = periods[claimPeriod]; require(period.mintingComplete, "booty not minted"); address stakerAddress = stakerByDelegateKey[msg.sender]; Staker storage staker = stakers[stakerAddress]; require(!staker.didClaimBooty[claimPeriod], "staker already claimed"); // can only claim booty once uint256 stakerSpankPoints = staker.spankPoints[claimPeriod]; require(stakerSpankPoints > 0, "staker has no points"); // only stakers can claim staker.didClaimBooty[claimPeriod] = true; uint256 bootyMinted = period.bootyMinted; uint256 totalSpankPoints = period.totalSpankPoints; uint256 bootyOwed = SafeMath.div(SafeMath.mul(stakerSpankPoints, bootyMinted), totalSpankPoints); require(bootyToken.transfer(staker.bootyBase, bootyOwed)); emit ClaimBootyEvent(stakerAddress, claimPeriod, bootyOwed); } function withdrawStake() public { updatePeriod(); Staker storage staker = stakers[msg.sender]; require(staker.spankStaked > 0, "staker has no stake"); require(isClosed || currentPeriod > staker.endingPeriod, "currentPeriod less than endingPeriod or spankbank closed"); uint256 spankToWithdraw = staker.spankStaked; totalSpankStaked = SafeMath.sub(totalSpankStaked, staker.spankStaked); staker.spankStaked = 0; spankToken.transfer(msg.sender, spankToWithdraw); emit WithdrawStakeEvent(msg.sender, spankToWithdraw); } function splitStake(address newAddress, address newDelegateKey, address newBootyBase, uint256 spankAmount) public { updatePeriod(); require(newAddress != address(0), "newAddress is zero"); require(newDelegateKey != address(0), "delegateKey is zero"); require(newBootyBase != address(0), "bootyBase is zero"); require(stakerByDelegateKey[newDelegateKey] == address(0), "delegateKey in use"); require(spankAmount > 0, "spankAmount is zero"); Staker storage staker = stakers[msg.sender]; require(currentPeriod < staker.endingPeriod, "staker expired"); require(spankAmount <= staker.spankStaked, "spankAmount greater than stake"); require(staker.spankPoints[currentPeriod+1] == 0, "staker has points for next period"); staker.spankStaked = SafeMath.sub(staker.spankStaked, spankAmount); stakers[newAddress] = Staker(spankAmount, staker.startingPeriod, staker.endingPeriod, newDelegateKey, newBootyBase); stakerByDelegateKey[newDelegateKey] = newAddress; emit SplitStakeEvent(msg.sender, newAddress, newDelegateKey, newBootyBase, spankAmount); } function voteToClose() public { updatePeriod(); Staker storage staker = stakers[msg.sender]; require(staker.spankStaked > 0, "stake is zero"); require(currentPeriod < staker.endingPeriod , "staker expired"); require(staker.votedToClose[currentPeriod] == false, "stake already voted"); require(isClosed == false, "SpankBank already closed"); uint256 closingVotes = periods[currentPeriod].closingVotes; closingVotes = SafeMath.add(closingVotes, staker.spankStaked); periods[currentPeriod].closingVotes = closingVotes; staker.votedToClose[currentPeriod] = true; uint256 closingTrigger = SafeMath.div(totalSpankStaked, 2); if (closingVotes > closingTrigger) { isClosed = true; } emit VoteToCloseEvent(msg.sender, currentPeriod); } function updateDelegateKey(address newDelegateKey) public { require(newDelegateKey != address(0), "delegateKey is zero"); require(stakerByDelegateKey[newDelegateKey] == address(0), "delegateKey already exists"); Staker storage staker = stakers[msg.sender]; require(staker.startingPeriod > 0, "staker starting period is zero"); stakerByDelegateKey[staker.delegateKey] = address(0); staker.delegateKey = newDelegateKey; stakerByDelegateKey[newDelegateKey] = msg.sender; emit UpdateDelegateKeyEvent(msg.sender, newDelegateKey); } function updateBootyBase(address newBootyBase) public { Staker storage staker = stakers[msg.sender]; require(staker.startingPeriod > 0, "staker starting period is zero"); staker.bootyBase = newBootyBase; emit UpdateBootyBaseEvent(msg.sender, newBootyBase); } function getSpankPoints(address stakerAddress, uint256 period) public view returns (uint256) { return stakers[stakerAddress].spankPoints[period]; } function getDidClaimBooty(address stakerAddress, uint256 period) public view returns (bool) { return stakers[stakerAddress].didClaimBooty[period]; } function getVote(address stakerAddress, uint period) public view returns (bool) { return stakers[stakerAddress].votedToClose[period]; } function getStakerFromDelegateKey(address delegateAddress) public view returns (address) { return stakerByDelegateKey[delegateAddress]; } }
the maximum # of periods a staker can stake for
uint256 public maxPeriods;
2,556,576
[ 1, 5787, 4207, 225, 434, 12777, 279, 384, 6388, 848, 384, 911, 364, 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, 2254, 5034, 1071, 943, 30807, 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 ]
pragma experimental ABIEncoderV2; pragma solidity 0.5.13; import "./Authorization.sol"; contract Specification { Authorization internal auth; address internal contractRegistry; string public deviceName; address public deviceAgent; address public owner; constructor (address payable _authAddress) public { auth = Authorization(_authAddress); contractRegistry = msg.sender; } //generic version blueprint for file stored on DHT struct Version { uint timestamp; address author; bytes32 hash; } struct Document { string name; string description; Version[] versions; } struct Sensor { string name; bytes32 hash; } struct ExternalSource { string URI; string description; address owner; } struct ProgramCall { uint timestamp; address author; string call; } Version[] public AML; ExternalSource[] public sources; //map hash of component to its documents mapping(bytes32 => Document[]) public documents; //map hash of component to its sensors mapping(bytes32 => Sensor[]) public sensors; //program calls for specific component mapping(bytes32 => ProgramCall[]) public programCallQueue; //array index of the most recently run program mapping(bytes32 => uint) public programCounter; function getTwin() external view returns (string memory, address, address){ return (deviceName, deviceAgent, owner); } function updateTwin(string calldata _deviceName, address _deviceAgent, address _owner) external { require(msg.sender == contractRegistry || auth.hasPermission(msg.sender, Authorization.PERMISSION.TWIN_UPDATE, address(this))); deviceName = _deviceName; deviceAgent = _deviceAgent; owner = _owner; } //******* AML *******// //overload function with msg.sender variant, since Solidity does not support optional parameters function _addNewAMLVersion(bytes32 _newAMLVersion, address sender) external { // AML can be inserted by each role except unauthorized accounts require(!(auth.getRole(sender, address(this)) == 404), "Your account has no privileges"); AML.push(Version(now, sender, _newAMLVersion)); } function addNewAMLVersion(bytes32 _newAMLVersion) external { // AML can be inserted by each role except unauthorized accounts require(!(auth.getRole(msg.sender, address(this)) == 404), "Your account has no privileges"); AML.push(Version(now, msg.sender, _newAMLVersion)); } function getAML(uint id) external view returns (Version memory){ return AML[id]; } function getAMLCount() external view returns (uint){ return AML.length; } function getAMLHistory() external view returns (Version[] memory){ return AML; } //******* DOCUMENTS *******// //register a new document (always appends to the end) function addDocument(string calldata componentId, string calldata name, string calldata description, bytes32 docHash) external { bytes32 id = keccak256(bytes(componentId)); require(auth.hasPermissionAndAttribute(msg.sender, Authorization.PERMISSION.DOC_CREATE, id, address(this))); documents[id].length++; Document storage doc = documents[id][documents[id].length - 1]; doc.name = name; doc.description = description; doc.versions.push(Version(now, msg.sender, docHash)); documents[id].push(doc); documents[id].length--; } //update Document storage metadata function updateDocument(string calldata componentId, uint documentId, string calldata name, string calldata description) external { bytes32 id = keccak256(bytes(componentId)); require(auth.hasPermissionAndAttribute(msg.sender, Authorization.PERMISSION.DOC_UPDATE, id, address(this))); documents[id][documentId].name = name; documents[id][documentId].description = description; } //add new document version function addDocumentVersion(string calldata componentId, uint documentId, bytes32 docHash) external { bytes32 id = keccak256(bytes(componentId)); require(auth.hasPermissionAndAttribute(msg.sender, Authorization.PERMISSION.DOC_UPDATE, id, address(this))); Version memory updated = Version(now, msg.sender, docHash); documents[id][documentId].versions.push(updated); } function getDocument(string calldata componentId, uint index) external view returns (Document memory){ bytes32 id = keccak256(bytes(componentId)); return documents[id][index]; } function getDocumentCount(string calldata componentId) external view returns (uint){ bytes32 id = keccak256(bytes(componentId)); return documents[id].length; } function removeDocument(string calldata componentId, uint index) external { bytes32 id = keccak256(bytes(componentId)); require(auth.hasPermissionAndAttribute(msg.sender, Authorization.PERMISSION.DOC_DELETE, id, address(this))); require(index < documents[id].length); documents[id][index] = documents[id][documents[id].length-1]; delete documents[id][documents[id].length-1]; documents[id].pop(); } //******* SENSORS *******// function addSensor(string calldata componentId, string calldata name, bytes32 hash) external { bytes32 id = keccak256(bytes(componentId)); require(auth.hasPermissionAndAttribute(msg.sender, Authorization.PERMISSION.SENSOR_CREATE, id, address(this))); sensors[id].push(Sensor(name, hash)); } function getSensor(string calldata componentId, uint index) external view returns (Sensor memory){ bytes32 id = keccak256(bytes(componentId)); return sensors[id][index]; } function getSensorCount(string calldata componentId) external view returns (uint){ bytes32 id = keccak256(bytes(componentId)); return sensors[id].length; } function removeSensor(string calldata componentId, uint index) external { bytes32 id = keccak256(bytes(componentId)); require(auth.hasPermissionAndAttribute(msg.sender, Authorization.PERMISSION.SENSOR_DELETE, id, address(this))); require(index < sensors[id].length); sensors[id][index] = sensors[id][sensors[id].length-1]; delete sensors[id][sensors[id].length-1]; sensors[id].pop(); } //******* EXTERNAL SOURCES *******// function addExternalSource(string calldata URI, string calldata description) external { sources.push(ExternalSource(URI, description, msg.sender)); } function getExternalSource(uint index) external view returns (ExternalSource memory){ return sources[index]; } function getExternalSourceHistory() external view returns (ExternalSource[] memory){ return sources; } function removeExternalSource(uint index) external { //todo permission check require(index < sources.length); sources[index] = sources[sources.length-1]; delete sources[sources.length-1]; sources.pop(); } //******* PROGRAM CALLS *******// function addProgramCall(string calldata componentId, string calldata call) external { bytes32 id = keccak256(bytes(componentId)); //todo permission check programCallQueue[id].push(ProgramCall(now, msg.sender, call)); } function getProgramCallQueue(string calldata componentId) external view returns (ProgramCall[] memory){ bytes32 id = keccak256(bytes(componentId)); return programCallQueue[id]; } function getProgramCounter(string calldata componentId) external view returns (uint){ bytes32 id = keccak256(bytes(componentId)); return programCounter[id]; } function updateProgramCounter(string calldata componentId, uint counter) external { bytes32 id = keccak256(bytes(componentId)); //todo permission check programCounter[id] = counter; } }
todo permission check
function removeExternalSource(uint index) external { require(index < sources.length); sources[index] = sources[sources.length-1]; delete sources[sources.length-1]; sources.pop(); }
12,997,274
[ 1, 9012, 4132, 866, 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, 1206, 6841, 1830, 12, 11890, 770, 13, 3903, 288, 203, 3639, 2583, 12, 1615, 411, 5550, 18, 2469, 1769, 203, 3639, 5550, 63, 1615, 65, 273, 5550, 63, 10141, 18, 2469, 17, 21, 15533, 203, 3639, 1430, 5550, 63, 10141, 18, 2469, 17, 21, 15533, 203, 3639, 5550, 18, 5120, 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 ]
./full_match/80001/0x65d35F25C6D2A723e73db6092D26ab1b500DCeB3/sources/contracts/SplitDetech.sol
* @dev Release owed amount of the `token` to all of the payees./
function distribute(IERC20Upgradeable token) public virtual { uint256 count = payeeCount(); for (uint256 i = 0; i < count; i++) { _release(token, payee(i)); } }
879,285
[ 1, 7391, 2523, 329, 3844, 434, 326, 1375, 2316, 68, 358, 777, 434, 326, 8843, 25521, 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 ]
[ 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, 25722, 12, 45, 654, 39, 3462, 10784, 429, 1147, 13, 1071, 5024, 288, 203, 3639, 2254, 5034, 1056, 273, 8843, 1340, 1380, 5621, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 1056, 31, 277, 27245, 288, 203, 5411, 389, 9340, 12, 2316, 16, 8843, 1340, 12, 77, 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 ]
/* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { ISynth } from "../../interfaces/external/ISynth.sol"; import { ISynthetixExchanger } from "../../interfaces/external/ISynthetixExchanger.sol"; /** * @title SynthetixTradeAdapter * @author Set Protocol * * Exchange adapter for Synthetix that returns data for trades */ contract SynthetixExchangeAdapter { /* ============ Structs ============ */ /** * Struct containing information for trade function */ struct SynthetixTradeInfo { bytes32 sourceCurrencyKey; // Currency key of the token to send bytes32 destinationCurrencyKey; // Currency key the token to receive } /* ============ State Variables ============ */ // Address of Synthetix's Exchanger contract address public immutable synthetixExchangerAddress; /* ============ Constructor ============ */ /** * Set state variables * * @param _synthetixExchangerAddress Address of Synthetix's Exchanger contract */ constructor(address _synthetixExchangerAddress) public { synthetixExchangerAddress = _synthetixExchangerAddress; } /* ============ External Getter Functions ============ */ /** * Calculate Synthetix trade encoded calldata. To be invoked on the SetToken. * * @param _sourceToken Address of source token to be sold * @param _destinationToken Address of destination token to buy * @param _destinationAddress Address to receive traded tokens * @param _sourceQuantity Amount of source token to sell * * @return address Target address * @return uint256 Call value * @return bytes Trade calldata */ function getTradeCalldata( address _sourceToken, address _destinationToken, address _destinationAddress, uint256 _sourceQuantity, uint256 /* _minDestinationQuantity */, bytes calldata /* _data */ ) external view returns (address, uint256, bytes memory) { SynthetixTradeInfo memory synthetixTradeInfo; require( _sourceToken != _destinationToken, "Source token cannot be same as destination token" ); synthetixTradeInfo.sourceCurrencyKey = _getCurrencyKey(_sourceToken); synthetixTradeInfo.destinationCurrencyKey = _getCurrencyKey(_destinationToken); // Encode method data for SetToken to invoke bytes memory methodData = abi.encodeWithSignature( "exchange(address,bytes32,uint256,bytes32,address)", _destinationAddress, synthetixTradeInfo.sourceCurrencyKey, _sourceQuantity, synthetixTradeInfo.destinationCurrencyKey, _destinationAddress ); return (synthetixExchangerAddress, 0, methodData); } /** * Returns the Synthetix contract address. * There is no need to approve to SNX as its a proxy * * @return address */ function getSpender() external view returns (address) { return synthetixExchangerAddress; } /** * Returns the amount of destination token received for exchanging a quantity of * source token, less fees. * * @param _sourceToken Address of source token to be sold * @param _destinationToken Address of destination token to buy * @param _sourceQuantity Amount of source token to sell * * @return amountReceived Amount of source token received for exchange */ function getAmountReceivedForExchange( address _sourceToken, address _destinationToken, uint256 _sourceQuantity ) external view returns (uint256 amountReceived) { SynthetixTradeInfo memory synthetixTradeInfo; synthetixTradeInfo.sourceCurrencyKey = _getCurrencyKey(_sourceToken); synthetixTradeInfo.destinationCurrencyKey = _getCurrencyKey(_destinationToken); (amountReceived,,) = ISynthetixExchanger(synthetixExchangerAddress).getAmountsForExchange( _sourceQuantity, synthetixTradeInfo.sourceCurrencyKey, synthetixTradeInfo.destinationCurrencyKey ); } /* ============ Internal Functions ============ */ /** * Gets the Synthetix currency key for _token * * @param _token Address of token to get currency key for */ function _getCurrencyKey(address _token) internal view returns (bytes32) { try ISynth(_token).currencyKey() returns (bytes32 key){ return key; } catch (bytes memory /* data */) { revert("Invalid Synth token address"); } } } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; // https://docs.synthetix.io/contracts/source/interfaces/isynth interface ISynth { function currencyKey() external view returns (bytes32); } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; // https://docs.synthetix.io/contracts/source/interfaces/iExchanger interface ISynthetixExchanger { function getAmountsForExchange( uint sourceAmount, bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey ) external view returns ( uint amountReceived, uint fee, uint exchangeFeeRate ); function exchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external returns (uint amountReceived); }
============ Structs ============ */* Struct containing information for trade function/
struct SynthetixTradeInfo { }
11,814,007
[ 1, 14468, 7362, 87, 422, 1432, 631, 342, 7362, 4191, 1779, 364, 18542, 445, 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 ]
[ 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, 1958, 16091, 451, 278, 697, 22583, 966, 288, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xBA5A76a60AD29f8C1f06174a520E5e5DB9A9705B/sources/HOasis.sol
Fixed Input - Token to ETH if amount == uint256(-1) return balance of Proxy
function sellAllAmountBuyEth( address payToken, uint256 payAmt, address wethToken, uint256 minBuyAmt ) external payable returns (uint256 wethAmt) { IOasisDirectProxy oasis = IOasisDirectProxy(OASIS_DIRECT_PROXY); payAmt = _getBalance(payToken, payAmt); IERC20(payToken).safeApprove(address(oasis), payAmt); try oasis.sellAllAmountBuyEth( MAKER_OTC, payToken, payAmt, wethToken, minBuyAmt ) returns (uint256 ret) { wethAmt = ret; _revertMsg("sellAllAmountBuyEth", reason); _revertMsg("sellAllAmountBuyEth"); } IERC20(payToken).safeApprove(address(oasis), 0); }
15,473,422
[ 1, 7505, 2741, 300, 3155, 358, 512, 2455, 309, 3844, 422, 2254, 5034, 19236, 21, 13, 327, 11013, 434, 7659, 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, 357, 80, 1595, 6275, 38, 9835, 41, 451, 12, 203, 3639, 1758, 8843, 1345, 16, 203, 3639, 2254, 5034, 8843, 31787, 16, 203, 3639, 1758, 341, 546, 1345, 16, 203, 3639, 2254, 5034, 1131, 38, 9835, 31787, 203, 565, 262, 3903, 8843, 429, 1135, 261, 11890, 5034, 341, 546, 31787, 13, 288, 203, 3639, 1665, 17247, 5368, 3886, 320, 17247, 273, 1665, 17247, 5368, 3886, 12, 28202, 15664, 67, 17541, 67, 16085, 1769, 203, 3639, 8843, 31787, 273, 389, 588, 13937, 12, 10239, 1345, 16, 8843, 31787, 1769, 203, 3639, 467, 654, 39, 3462, 12, 10239, 1345, 2934, 4626, 12053, 537, 12, 2867, 12, 26501, 3631, 8843, 31787, 1769, 203, 3639, 775, 203, 5411, 320, 17247, 18, 87, 1165, 1595, 6275, 38, 9835, 41, 451, 12, 203, 7734, 490, 14607, 654, 67, 1974, 39, 16, 203, 7734, 8843, 1345, 16, 203, 7734, 8843, 31787, 16, 203, 7734, 341, 546, 1345, 16, 203, 7734, 1131, 38, 9835, 31787, 203, 5411, 262, 203, 3639, 1135, 261, 11890, 5034, 325, 13, 288, 203, 5411, 341, 546, 31787, 273, 325, 31, 203, 5411, 389, 266, 1097, 3332, 2932, 87, 1165, 1595, 6275, 38, 9835, 41, 451, 3113, 3971, 1769, 203, 5411, 389, 266, 1097, 3332, 2932, 87, 1165, 1595, 6275, 38, 9835, 41, 451, 8863, 203, 3639, 289, 203, 3639, 467, 654, 39, 3462, 12, 10239, 1345, 2934, 4626, 12053, 537, 12, 2867, 12, 26501, 3631, 374, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts/utils/cryptography/ECDSA.sol pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // File: VaultCoreInterface.sol pragma solidity 0.8.9; abstract contract VaultCoreInterface { function getVersion() public pure virtual returns (uint); function typeOfContract() public pure virtual returns (bytes32); function approveToken( uint256 _tokenId, address _tokenContractAddress) external virtual; } // File: RoyaltyRegistryInterface.sol pragma solidity 0.8.9; /** * Interface to the RoyaltyRegistry responsible for looking payout addresses */ abstract contract RoyaltyRegistryInterface { function getAddress(address custodial) external view virtual returns (address); function getMediaCustomPercentage(uint256 mediaId, address tokenAddress) external view virtual returns(uint16); function getExternalTokenPercentage(uint256 tokenId, address tokenAddress) external view virtual returns(uint16, uint16); function typeOfContract() virtual public pure returns (string calldata); function VERSION() virtual public pure returns (uint8); } // File: ApprovedCreatorRegistryInterface.sol pragma solidity 0.8.9; /** * Interface to the digital media store external contract that is * responsible for storing the common digital media and collection data. * This allows for new token contracts to be deployed and continue to reference * the digital media and collection data. */ abstract contract ApprovedCreatorRegistryInterface { function getVersion() virtual public pure returns (uint); function typeOfContract() virtual public pure returns (string calldata); function isOperatorApprovedForCustodialAccount( address _operator, address _custodialAddress) virtual public view returns (bool); } // File: utils/Collaborator.sol pragma solidity 0.8.9; library Collaborator { bytes32 public constant TYPE_HASH = keccak256("Share(address account,uint48 value,uint48 royalty)"); struct Share { address payable account; uint48 value; uint48 royalty; } function hash(Share memory part) internal pure returns (bytes32) { return keccak256(abi.encode(TYPE_HASH, part.account, part.value, part.royalty)); } } // 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/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; } } // 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() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: OBOControl.sol pragma solidity 0.8.9; contract OBOControl is Ownable { address public oboAdmin; uint256 constant public newAddressWaitPeriod = 1 days; bool public isInitialOBOAdded = false; // List of approved on behalf of users. mapping (address => uint256) public approvedOBOs; event NewOBOAddressEvent( address OBOAddress, bool action); event NewOBOAdminAddressEvent( address oboAdminAddress); modifier onlyOBOAdmin() { require(owner() == _msgSender() || oboAdmin == _msgSender(), "not oboAdmin"); _; } function setOBOAdmin(address _oboAdmin) external onlyOwner { oboAdmin = _oboAdmin; emit NewOBOAdminAddressEvent(_oboAdmin); } /** * Add a new approvedOBO address. The address can be used after wait period. */ function addApprovedOBO(address _oboAddress) external onlyOBOAdmin { require(_oboAddress != address(0), "cant set to 0x"); require(approvedOBOs[_oboAddress] == 0, "already added"); approvedOBOs[_oboAddress] = block.timestamp; emit NewOBOAddressEvent(_oboAddress, true); } /** * Removes an approvedOBO immediately. */ function removeApprovedOBO(address _oboAddress) external onlyOBOAdmin { delete approvedOBOs[_oboAddress]; emit NewOBOAddressEvent(_oboAddress, false); } /* * Add OBOAddress for immediate use. This is an internal only Fn that is called * only when the contract is deployed. */ function addApprovedOBOImmediately(address _oboAddress) internal onlyOwner { require(_oboAddress != address(0), "addr(0)"); // set the date to one in past so that address is active immediately. approvedOBOs[_oboAddress] = block.timestamp - newAddressWaitPeriod - 1; emit NewOBOAddressEvent(_oboAddress, true); } function addApprovedOBOAfterDeploy(address _oboAddress) external onlyOBOAdmin { require(isInitialOBOAdded == false, "OBO already added"); addApprovedOBOImmediately(_oboAddress); isInitialOBOAdded = true; } /* * Helper function to verify is a given address is a valid approvedOBO address. */ function isValidApprovedOBO(address _oboAddress) public view returns (bool) { uint256 createdAt = approvedOBOs[_oboAddress]; if (createdAt == 0) { return false; } return block.timestamp - createdAt > newAddressWaitPeriod; } /** * @dev Modifier to make the obo calls only callable by approved addressess */ modifier isApprovedOBO() { require(isValidApprovedOBO(msg.sender), "unauthorized OBO user"); _; } } // File: @openzeppelin/contracts/security/Pausable.sol pragma solidity ^0.8.0; /** * @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()); } } // 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; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @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/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/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/extensions/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/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: DigitalMediaToken.sol pragma solidity 0.8.9; contract DigitalMediaToken is ERC721, OBOControl, Pausable { uint256 public currentSupply = 0; // creator address has to be set during deploy via constructor only. address public singleCreatorAddress; address public signerAddress; bool public enableExternalMinting; bool public canRoyaltyRegistryChange = true; struct DigitalMedia { uint32 totalSupply; // The total supply of collectibles available uint32 printIndex; // The current print index address creator; // The creator of the collectible uint16 royalty; bool immutableMedia; Collaborator.Share[] collaborators; string metadataPath; // Hash of the media content, with the actual data stored on a secondary // data store (ideally decentralized) } struct DigitalMediaRelease { uint32 printEdition; // The unique edition number of this digital media release uint256 digitalMediaId; // Reference ID to the digital media metadata } ApprovedCreatorRegistryInterface public creatorRegistryStore; RoyaltyRegistryInterface public royaltyStore; VaultCoreInterface public vaultStore; // Event fired when a new digital media is created. No point in returning printIndex // since its always zero when created. event DigitalMediaCreateEvent( uint256 id, address creator, uint32 totalSupply, uint32 royalty, bool immutableMedia, string metadataPath); event DigitalMediaReleaseCreateEvent( uint256 id, address owner, uint32 printEdition, string tokenURI, uint256 digitalMediaId); // Event fired when a creator assigns a new creator address. event ChangedCreator( address creator, address newCreator); // Event fired when a digital media is burned event DigitalMediaBurnEvent( uint256 id, address caller); // Event fired when burning a token event DigitalMediaReleaseBurnEvent( uint256 tokenId, address owner); event NewSignerEvent( address signer); event NewRoyaltyEvent( uint16 value); // ID to Digital Media object mapping (uint256 => DigitalMedia) public idToDigitalMedia; // Maps internal ERC721 token ID to digital media release object. mapping (uint256 => DigitalMediaRelease) public tokenIdToDigitalMediaRelease; // Maps a creator address to a new creator address. Useful if a creator // changes their address or the previous address gets compromised. mapping (address => address) public changedCreators; constructor(string memory _tokenName, string memory _tokenSymbol) ERC721(_tokenName, _tokenSymbol) {} // Set the creator registry address upon construction. Immutable. function setCreatorRegistryStore(address _crsAddress) internal { ApprovedCreatorRegistryInterface candidateCreatorRegistryStore = ApprovedCreatorRegistryInterface(_crsAddress); // require(candidateCreatorRegistryStore.getVersion() == 1, "registry store is not version 1"); // Simple check to make sure we are adding the registry contract indeed // https://fravoll.github.io/solidity-patterns/string_equality_comparison.html bytes32 contractType = keccak256(abi.encodePacked(candidateCreatorRegistryStore.typeOfContract())); // keccak256(abi.encodePacked("approvedCreatorRegistry")) = 0x74cb6de1099c3d993f336da7af5394f68038a23980424e1ae5723d4110522be4 // keccak256(abi.encodePacked("approvedCreatorRegistryReadOnly")) = 0x9732b26dfb8751e6f1f71e8f21b28a237cfe383953dce7db3dfa1777abdb2791 require( contractType == 0x74cb6de1099c3d993f336da7af5394f68038a23980424e1ae5723d4110522be4 || contractType == 0x9732b26dfb8751e6f1f71e8f21b28a237cfe383953dce7db3dfa1777abdb2791, "not crtrRegistry"); creatorRegistryStore = candidateCreatorRegistryStore; } function setRoyaltyRegistryStore(address _royaltyStore) external whenNotPaused onlyOBOAdmin { require(canRoyaltyRegistryChange == true, "no"); RoyaltyRegistryInterface candidateRoyaltyStore = RoyaltyRegistryInterface(_royaltyStore); require(candidateRoyaltyStore.VERSION() == 1, "roylty v!= 1"); bytes32 contractType = keccak256(abi.encodePacked(candidateRoyaltyStore.typeOfContract())); // keccak256(abi.encodePacked("royaltyRegistry")) = 0xb590ff355bf2d720a7e957392d3b76fd1adda1832940640bf5d5a7c387fed323 require(contractType == 0xb590ff355bf2d720a7e957392d3b76fd1adda1832940640bf5d5a7c387fed323, "not royalty"); royaltyStore = candidateRoyaltyStore; } function setRoyaltyRegistryForever() external whenNotPaused onlyOwner { canRoyaltyRegistryChange = false; } function setVaultStore(address _vaultStore) external whenNotPaused onlyOwner { VaultCoreInterface candidateVaultStore = VaultCoreInterface(_vaultStore); bytes32 contractType = candidateVaultStore.typeOfContract(); require(contractType == 0x6d707661756c7400000000000000000000000000000000000000000000000000, "invalid mpvault"); vaultStore = candidateVaultStore; } /* * Set signer address on the token contract. Setting signer means we are opening * the token contract for external accounts to create tokens. Call this to change * the signer immediately. */ function setSignerAddress(address _signerAddress, bool _enableExternalMinting) external whenNotPaused isApprovedOBO { require(_signerAddress != address(0), "cant be zero"); signerAddress = _signerAddress; enableExternalMinting = _enableExternalMinting; emit NewSignerEvent(signerAddress); } /** * Validates that the Registered store is initialized. */ modifier registryInitialized() { require(address(creatorRegistryStore) != address(0), "registry = 0x0"); _; } /** * Validates that the Vault store is initialized. */ modifier vaultInitialized() { require(address(vaultStore) != address(0), "vault = 0x0"); _; } function _setCollaboratorsOnDigitalMedia(DigitalMedia storage _digitalMedia, Collaborator.Share[] memory _collaborators) internal { uint total = 0; uint totalRoyalty = 0; for (uint i = 0; i < _collaborators.length; i++) { require(_collaborators[i].account != address(0x0) || _collaborators[i].account != _digitalMedia.creator, "collab 0x0/creator"); require(_collaborators[i].value != 0 || _collaborators[i].royalty != 0, "share/royalty = 0"); _digitalMedia.collaborators.push(_collaborators[i]); total = total + _collaborators[i].value; totalRoyalty = totalRoyalty + _collaborators[i].royalty; } require(total <= 10000, "total <=10000"); require(totalRoyalty <= 10000, "totalRoyalty <=10000"); } /** * Creates a new digital media object. * @param _creator address the creator of this digital media * @param _totalSupply uint32 the total supply a creation could have * @param _metadataPath string the path to the ipfs metadata * @return uint the new digital media id */ function _createDigitalMedia( address _creator, uint256 _onchainId, uint32 _totalSupply, string memory _metadataPath, Collaborator.Share[] memory _collaborators, uint16 _royalty, bool _immutableMedia, uint256 contractSupply) internal returns (uint) { // If this is a single creator contract make sure _owner matches single creator if (singleCreatorAddress != address(0)) { require(singleCreatorAddress == _creator, "Creator must match single creator address"); } // If token contract's max supply is reached error out. if (contractSupply > 0) { require(currentSupply < contractSupply, "total supply reached"); } // Verify this media does not exist already DigitalMedia storage _digitalMedia = idToDigitalMedia[_onchainId]; require(_digitalMedia.creator == address(0), "media already exists"); // TODO: Dannie check this require throughly. require((_totalSupply > 0) && address(_creator) != address(0) && _royalty <= 10000, "invalid params"); _digitalMedia.printIndex = 0; _digitalMedia.totalSupply = _totalSupply; _digitalMedia.creator = _creator; _digitalMedia.metadataPath = _metadataPath; _digitalMedia.immutableMedia = _immutableMedia; _digitalMedia.royalty = _royalty; _setCollaboratorsOnDigitalMedia(_digitalMedia, _collaborators); currentSupply = currentSupply + 1; emit DigitalMediaCreateEvent( _onchainId, _creator, _totalSupply, _royalty, _immutableMedia, _metadataPath); return _onchainId; } /** * Creates _count number of new digital media releases (i.e a token). * Bumps up the print index by _count. * @param _owner address the owner of the digital media object * @param _digitalMediaId uint256 the digital media id */ function _createDigitalMediaReleases( address _owner, uint256 _digitalMediaId, uint256[] memory _releaseIds) internal { require(_releaseIds.length > 0 && _releaseIds.length < 10000, "0 < count <= 10000"); DigitalMedia storage _digitalMedia = idToDigitalMedia[_digitalMediaId]; require(_digitalMedia.creator != address(0), "media does not exist"); uint32 currentPrintIndex = _digitalMedia.printIndex; require(_checkApprovedCreator(_digitalMedia.creator, _owner), "Creator not approved"); require(_releaseIds.length + currentPrintIndex <= _digitalMedia.totalSupply, "Total supply exceeded."); for (uint32 i=0; i < _releaseIds.length; i++) { uint256 newDigitalMediaReleaseId = _releaseIds[i]; DigitalMediaRelease storage release = tokenIdToDigitalMediaRelease[newDigitalMediaReleaseId]; require(release.printEdition == 0, "tokenId already used"); uint32 newPrintEdition = currentPrintIndex + 1 + i; release.printEdition = newPrintEdition; release.digitalMediaId = _digitalMediaId; emit DigitalMediaReleaseCreateEvent( newDigitalMediaReleaseId, _owner, newPrintEdition, _digitalMedia.metadataPath, _digitalMediaId ); // This will assign ownership and also emit the Transfer event as per ERC721 _mint(_owner, newDigitalMediaReleaseId); } _digitalMedia.printIndex = _digitalMedia.printIndex + uint32(_releaseIds.length); } /** * Checks that a given caller is an approved creator and is allowed to mint or burn * tokens. If the creator was changed it will check against the updated creator. * @param _caller the calling address * @return bool allowed or not */ function _checkApprovedCreator(address _creator, address _caller) internal view returns (bool) { address approvedCreator = changedCreators[_creator]; if (approvedCreator != address(0)) { return approvedCreator == _caller; } else { return _creator == _caller; } } /** * Burns a token for a given tokenId and caller. * @param _tokenId the id of the token to burn. * @param _caller the address of the caller. */ function _burnToken(uint256 _tokenId, address _caller) internal { address owner = ownerOf(_tokenId); require(_isApprovedOrOwner(_caller, _tokenId), "ERC721: burn caller is not owner nor approved"); _burn(_tokenId); delete tokenIdToDigitalMediaRelease[_tokenId]; emit DigitalMediaReleaseBurnEvent(_tokenId, owner); } /** * Burns a digital media. Once this function succeeds, this digital media * will no longer be able to mint any more tokens. Existing tokens need to be * burned individually though. * @param _digitalMediaId the id of the digital media to burn * @param _caller the address of the caller. */ function _burnDigitalMedia(uint256 _digitalMediaId, address _caller) internal { DigitalMedia storage _digitalMedia = idToDigitalMedia[_digitalMediaId]; require(_digitalMedia.creator != address(0), "media does not exist"); require(_checkApprovedCreator(_digitalMedia.creator, _caller) || isApprovedForAll(_digitalMedia.creator, _caller), "Failed digital media burn. Caller not approved."); _digitalMedia.printIndex = _digitalMedia.totalSupply; emit DigitalMediaBurnEvent(_digitalMediaId, _caller); } /** * @dev Returns an URI for a given token ID * @dev Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); DigitalMediaRelease storage digitalMediaRelease = tokenIdToDigitalMediaRelease[_tokenId]; uint256 _digitalMediaId = digitalMediaRelease.digitalMediaId; DigitalMedia storage _digitalMedia = idToDigitalMedia[_digitalMediaId]; string memory prefix = "ipfs://"; return string(abi.encodePacked(prefix, string(_digitalMedia.metadataPath))); } /* * Look up a royalty payout address if royaltyStore is set otherwise we returns * the same argument. */ function _getRoyaltyAddress(address custodial) internal view returns(address) { return address(royaltyStore) == address(0) ? custodial : royaltyStore.getAddress(custodial); } } // File: DigitalMediaCore.sol pragma solidity 0.8.9; contract DigitalMediaCore is DigitalMediaToken { using ECDSA for bytes32; uint8 constant public VERSION = 3; // if the contract can have a total of only 10,000 tokens set the totalMediaSupply // during the contract deployment. I could nt define a immutable variable in DigitalMediaToken // So creating the variable here and instantiating it in constructor and passing // it down to the internal functions. uint256 public immutable totalMediaSupply; struct DigitalMediaCreateRequest { uint256 onchainId; // onchain id for this media uint32 totalSupply; // The total supply of collectibles available address creator; // The creator of the collectible uint16 royalty; bool immutableMedia; Collaborator.Share[] collaborators; string metadataPath; // Hash of the media content uint256[] releaseIds; // number of releases to mint } struct DigitalMediaUpdateRequest { uint256 onchainId; // onchain id for this media uint256 metadataId; uint32 totalSupply; // The total supply of collectibles available address creator; // The creator of the collectible uint16 royalty; Collaborator.Share[] collaborators; string metadataPath; // Hash of the media content } struct DigitalMediaReleaseCreateRequest { uint256 digitalMediaId; uint256[] releaseIds; // number of releases to mint address owner; } struct TokenDestinationRequest { uint256 tokenId; address destinationAddress; } struct ChainSignatureRequest { uint256 onchainId; address owner; } struct PayoutInfo { address user; uint256 amount; } event DigitalMediaUpdateEvent( uint256 id, uint32 totalSupply, uint16 royalty, string metadataPath, uint256 metadataId); event MediasImmutableEvent( uint256[] mediaIds); event MediaImmutableEvent( uint256 mediaId); constructor(string memory _tokenName, string memory _tokenSymbol, address _crsAddress, uint256 _totalSupply) DigitalMediaToken(_tokenName, _tokenSymbol) { setCreatorRegistryStore(_crsAddress); totalMediaSupply = _totalSupply; } /** * Retrieves a Digital Media object. */ function getDigitalMedia(uint256 _id) external view returns (DigitalMedia memory) { DigitalMedia memory _digitalMedia = idToDigitalMedia[_id]; require(_digitalMedia.creator != address(0), "DigitalMedia not found."); return _digitalMedia; } /** * Ok I am not proud of this function but sale conract needs to getDigitalMedia * while I tried to write a interface file DigitalMediaBurnInterfaceV3.sol I could * not include the DigitalMedia struct in that abstract contract. So I am writing * another endpoint to return just the bare minimum data required for the sale contract. */ function getDigitalMediaForSale(uint256 _id) external view returns( address, bool, uint16) { DigitalMedia storage _digitalMedia = idToDigitalMedia[_id]; require(_digitalMedia.creator != address(0), "DigitalMedia not found."); return (_digitalMedia.creator, _digitalMedia.collaborators.length > 0, _digitalMedia.royalty); } /** * Retrieves a Digital Media Release (i.e a token) */ function getDigitalMediaRelease(uint256 _id) external view returns (DigitalMediaRelease memory) { require(_exists(_id), "release does not exist"); DigitalMediaRelease storage digitalMediaRelease = tokenIdToDigitalMediaRelease[_id]; return digitalMediaRelease; } /** * Creates a new digital media object and mints it's first digital media release token. * The onchainid and creator has to be signed by signerAddress in order to create. * No creations of any kind are allowed when the contract is paused. */ function createDigitalMediaAndReleases( DigitalMediaCreateRequest memory request, bytes calldata signature) external whenNotPaused { require(request.creator == msg.sender, "msgSender != creator"); ChainSignatureRequest memory signatureRequest = ChainSignatureRequest(request.onchainId, request.creator); _verifyReleaseRequestSignature(signatureRequest, signature); uint256 digitalMediaId = _createDigitalMedia(msg.sender, request.onchainId, request.totalSupply, request.metadataPath, request.collaborators, request.royalty, request.immutableMedia, totalMediaSupply); _createDigitalMediaReleases(msg.sender, digitalMediaId, request.releaseIds); } /** * Creates a new digital media release (token) for a given digital media id. * This request needs to be signed by the authorized signerAccount to prevent * from user stealing media & release ids on chain and frontrunning. * No creations of any kind are allowed when the contract is paused. */ function createDigitalMediaReleases( DigitalMediaReleaseCreateRequest memory request) external whenNotPaused { // require(request.owner == msg.sender, "owner != msg.sender"); require(signerAddress != address(0), "signer not set"); _createDigitalMediaReleases(msg.sender, request.digitalMediaId, request.releaseIds); } /** * Creates a new digital media object and mints it's digital media release tokens. * Called on behalf of the _owner. Pass count to mint `n` number of tokens. * * Only approved creators are allowed to create Obo. * * No creations of any kind are allowed when the contract is paused. */ function oboCreateDigitalMediaAndReleases( DigitalMediaCreateRequest memory request) external whenNotPaused isApprovedOBO { uint256 digitalMediaId = _createDigitalMedia(request.creator, request.onchainId, request.totalSupply, request.metadataPath, request.collaborators, request.royalty, request.immutableMedia, totalMediaSupply); _createDigitalMediaReleases(request.creator, digitalMediaId, request.releaseIds); } /** * Create many digital medias in one call. */ function oboCreateManyDigitalMedias( DigitalMediaCreateRequest[] memory requests) external whenNotPaused isApprovedOBO { for (uint32 i=0; i < requests.length; i++) { DigitalMediaCreateRequest memory request = requests[i]; _createDigitalMedia(request.creator, request.onchainId, request.totalSupply, request.metadataPath, request.collaborators, request.royalty, request.immutableMedia, totalMediaSupply); } } /** * Creates multiple digital media releases (tokens) for a given digital media id. * Called on behalf of the _owner. * * Only approved creators are allowed to create Obo. * * No creations of any kind are allowed when the contract is paused. */ function oboCreateDigitalMediaReleases( DigitalMediaReleaseCreateRequest memory request) external whenNotPaused isApprovedOBO { _createDigitalMediaReleases(request.owner, request.digitalMediaId, request.releaseIds); } /* * Create multiple digital medias and associated releases (tokens). Called on behalf * of the _owner. Each media should mint atleast 1 token. * No creations of any kind are allowed when the contract is paused. */ function oboCreateManyDigitalMediasAndReleases( DigitalMediaCreateRequest[] memory requests) external whenNotPaused isApprovedOBO { for (uint32 i=0; i < requests.length; i++) { DigitalMediaCreateRequest memory request = requests[i]; uint256 digitalMediaId = _createDigitalMedia(request.creator, request.onchainId, request.totalSupply, request.metadataPath, request.collaborators, request.royalty, request.immutableMedia, totalMediaSupply); _createDigitalMediaReleases(request.creator, digitalMediaId, request.releaseIds); } } /* * Create multiple releases (tokens) associated with existing medias. Called on behalf * of the _owner. * No creations of any kind are allowed when the contract is paused. */ function oboCreateManyReleases( DigitalMediaReleaseCreateRequest[] memory requests) external whenNotPaused isApprovedOBO { for (uint32 i=0; i < requests.length; i++) { DigitalMediaReleaseCreateRequest memory request = requests[i]; DigitalMedia storage _digitalMedia = idToDigitalMedia[request.digitalMediaId]; require(_digitalMedia.creator != address(0), "DigitalMedia not found."); _createDigitalMediaReleases(request.owner, request.digitalMediaId, request.releaseIds); } } /** * Override the isApprovalForAll to check for a special oboApproval list. Reason for this * is that we can can easily remove obo operators if they every become compromised. */ function isApprovedForAll(address _owner, address _operator) public view override registryInitialized returns (bool) { if (creatorRegistryStore.isOperatorApprovedForCustodialAccount(_operator, _owner) == true) { return true; } else { return super.isApprovedForAll(_owner, _operator); } } /** * Changes the creator for the current sender, in the event we * need to be able to mint new tokens from an existing digital media * print production. When changing creator, the old creator will * no longer be able to mint tokens. * * A creator may need to be changed: * 1. If we want to allow a creator to take control over their token minting (i.e go decentralized) * 2. If we want to re-issue private keys due to a compromise. For this reason, we can call this function * when the contract is paused. * @param _creator the creator address * @param _newCreator the new creator address */ function changeCreator(address _creator, address _newCreator) external { address approvedCreator = changedCreators[_creator]; require(msg.sender != address(0) && _creator != address(0), "Creator must be valid non 0x0 address."); require(msg.sender == _creator || msg.sender == approvedCreator, "Unauthorized caller."); if (approvedCreator == address(0)) { changedCreators[msg.sender] = _newCreator; } else { require(msg.sender == approvedCreator, "Unauthorized caller."); changedCreators[_creator] = _newCreator; } emit ChangedCreator(_creator, _newCreator); } // standard ERC721 burn interface function burn(uint256 _tokenId) external { _burnToken(_tokenId, msg.sender); } /** * Ends the production run of a digital media. Afterwards no more tokens * will be allowed to be printed for each digital media. Used when a creator * makes a mistake and wishes to burn and recreate their digital media. * * When a contract is paused we do not allow new tokens to be created, * so stopping the production of a token doesn't have much purpose. */ function burnDigitalMedia(uint256 _digitalMediaId) external whenNotPaused { _burnDigitalMedia(_digitalMediaId, msg.sender); } /* * Batch transfer multiple tokens from their sources to destination * Owner / ApproveAll user can call this endpoint. */ function safeTransferMany(TokenDestinationRequest[] memory requests) external whenNotPaused { for (uint32 i=0; i < requests.length; i++) { TokenDestinationRequest memory request = requests[i]; safeTransferFrom(ownerOf(request.tokenId), request.destinationAddress, request.tokenId); } } function _updateDigitalMedia(DigitalMediaUpdateRequest memory request, DigitalMedia storage _digitalMedia) internal { require(_digitalMedia.immutableMedia == false, "immutable"); require(_digitalMedia.printIndex <= request.totalSupply, "< currentPrintIndex"); _digitalMedia.totalSupply = request.totalSupply; _digitalMedia.metadataPath = request.metadataPath; _digitalMedia.royalty = request.royalty; delete _digitalMedia.collaborators; _setCollaboratorsOnDigitalMedia(_digitalMedia, request.collaborators); emit DigitalMediaUpdateEvent(request.onchainId, request.totalSupply, request.royalty, request.metadataPath, request.metadataId); } function updateMedia(DigitalMediaUpdateRequest memory request) external whenNotPaused { require(request.creator == msg.sender, "msgSender != creator"); DigitalMedia storage _digitalMedia = idToDigitalMedia[request.onchainId]; require(_digitalMedia.creator != address(0) && _digitalMedia.creator == msg.sender, "DM creator issue"); _updateDigitalMedia(request, _digitalMedia); } /* * Update existing digitalMedia's metadata, totalSupply, collaborated, royalty * and immutable attribute. Once a media is immutable you cannot call this function */ function updateManyMedias(DigitalMediaUpdateRequest[] memory requests) external whenNotPaused isApprovedOBO vaultInitialized { for (uint32 i=0; i < requests.length; i++) { DigitalMediaUpdateRequest memory request = requests[i]; DigitalMedia storage _digitalMedia = idToDigitalMedia[request.onchainId]; // Call creator registry to check if the creator gave approveAll to vault require(_digitalMedia.creator != address(0) && _digitalMedia.creator == request.creator, "DM creator"); require(isApprovedForAll(_digitalMedia.creator, address(vaultStore)) == true, "approveall missing"); _updateDigitalMedia(request, _digitalMedia); } } function makeMediaImmutable(uint256 mediaId) external whenNotPaused { DigitalMedia storage _digitalMedia = idToDigitalMedia[mediaId]; require(_digitalMedia.creator != address(0) && _digitalMedia.creator == msg.sender, "DM creator"); require(_digitalMedia.immutableMedia == false, "DM immutable"); _digitalMedia.immutableMedia = true; emit MediaImmutableEvent(mediaId); } /* * Once we update media and feel satisfied with the changes, we can render it immutable now. */ function makeMediasImmutable(uint256[] memory mediaIds) external whenNotPaused isApprovedOBO vaultInitialized { for (uint32 i=0; i < mediaIds.length; i++) { uint256 mediaId = mediaIds[i]; DigitalMedia storage _digitalMedia = idToDigitalMedia[mediaId]; require(_digitalMedia.creator != address(0), "DM not found."); require(_digitalMedia.immutableMedia == false, "DM immutable"); require(isApprovedForAll(_digitalMedia.creator, address(vaultStore)) == true, "approveall missing"); _digitalMedia.immutableMedia = true; } emit MediasImmutableEvent(mediaIds); } function _lookUpTokenAndReturnEntries(uint256 _tokenId, uint256 _salePrice, bool _isRoyalty) internal view returns(PayoutInfo[] memory entries) { require(_exists(_tokenId), "no token"); DigitalMediaRelease memory digitalMediaRelease = tokenIdToDigitalMediaRelease[_tokenId]; DigitalMedia memory _digitalMedia = idToDigitalMedia[digitalMediaRelease.digitalMediaId]; uint256 size = _digitalMedia.collaborators.length + 1; entries = new PayoutInfo[](size); uint totalRoyaltyPercentage = 0; for (uint256 index = 0; index < _digitalMedia.collaborators.length; index++) { address payoutAddress = _getRoyaltyAddress(_digitalMedia.collaborators[index].account); if (_isRoyalty == true) { entries[index] = PayoutInfo(payoutAddress, _digitalMedia.collaborators[index].royalty * _digitalMedia.royalty * _salePrice / (10000 * 10000)); totalRoyaltyPercentage = totalRoyaltyPercentage + _digitalMedia.collaborators[index].royalty; } else { entries[index] = PayoutInfo(payoutAddress, _digitalMedia.collaborators[index].value * _salePrice / 10000); totalRoyaltyPercentage = totalRoyaltyPercentage + _digitalMedia.collaborators[index].value; } } address creatorPayoutAddress = _getRoyaltyAddress(_digitalMedia.creator); if (_isRoyalty == true) { entries[size-1]= PayoutInfo(creatorPayoutAddress, _salePrice * (10000 - totalRoyaltyPercentage) * _digitalMedia.royalty / (10000 * 10000)); } else { entries[size-1]= PayoutInfo(creatorPayoutAddress, _salePrice * (10000 - totalRoyaltyPercentage) / 10000); } return entries; } /* * Return royalty for a given Token. Returns an array of PayoutInfo which consists * of address to pay to and amount. * Thank you for posting this gist. Helped me to figure out how to return an array of structs. * https://gist.github.com/minhth1905/4b6208372fc5e7343b5ce1fb6d42c942 */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns ( PayoutInfo[] memory) { return _lookUpTokenAndReturnEntries(_tokenId, _salePrice, true); } /* * Given salePrice break down the amount between the creator and collabarators * according to their percentages. */ function saleInfo(uint256 _tokenId, uint256 _totalPayout) external view returns ( PayoutInfo[] memory) { return _lookUpTokenAndReturnEntries(_tokenId, _totalPayout, false); } function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } /* * helper to verify signature signed by non-custodial creator. */ function _verifyReleaseRequestSignature( ChainSignatureRequest memory request, bytes calldata signature) internal view { require(enableExternalMinting == true, "ext minting disabled"); bytes32 encodedRequest = keccak256(abi.encode(request)); address addressWhoSigned = encodedRequest.recover(signature); require(addressWhoSigned == signerAddress, "sig error"); } }
* Burns a digital media. Once this function succeeds, this digital media will no longer be able to mint any more tokens. Existing tokens need to be burned individually though. @param _digitalMediaId the id of the digital media to burn @param _caller the address of the caller./
function _burnDigitalMedia(uint256 _digitalMediaId, address _caller) internal { DigitalMedia storage _digitalMedia = idToDigitalMedia[_digitalMediaId]; require(_digitalMedia.creator != address(0), "media does not exist"); require(_checkApprovedCreator(_digitalMedia.creator, _caller) || isApprovedForAll(_digitalMedia.creator, _caller), "Failed digital media burn. Caller not approved."); _digitalMedia.printIndex = _digitalMedia.totalSupply; emit DigitalMediaBurnEvent(_digitalMediaId, _caller); }
640,488
[ 1, 38, 321, 87, 279, 25615, 3539, 18, 225, 12419, 333, 445, 21933, 16, 333, 25615, 3539, 903, 1158, 7144, 506, 7752, 358, 312, 474, 1281, 1898, 2430, 18, 225, 28257, 2430, 1608, 358, 506, 18305, 329, 28558, 11376, 18, 282, 389, 28095, 5419, 548, 326, 612, 434, 326, 25615, 3539, 358, 18305, 282, 389, 16140, 326, 1758, 434, 326, 4894, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 70, 321, 4907, 7053, 5419, 12, 11890, 5034, 389, 28095, 5419, 548, 16, 1758, 389, 16140, 13, 2713, 288, 203, 3639, 11678, 7053, 5419, 2502, 389, 28095, 5419, 273, 612, 774, 4907, 7053, 5419, 63, 67, 28095, 5419, 548, 15533, 203, 3639, 2583, 24899, 28095, 5419, 18, 20394, 480, 1758, 12, 20, 3631, 315, 5829, 1552, 486, 1005, 8863, 203, 3639, 2583, 24899, 1893, 31639, 10636, 24899, 28095, 5419, 18, 20394, 16, 389, 16140, 13, 747, 203, 7734, 353, 31639, 1290, 1595, 24899, 28095, 5419, 18, 20394, 16, 389, 16140, 3631, 203, 7734, 315, 2925, 25615, 3539, 18305, 18, 225, 20646, 486, 20412, 1199, 1769, 203, 203, 3639, 389, 28095, 5419, 18, 1188, 1016, 273, 389, 28095, 5419, 18, 4963, 3088, 1283, 31, 203, 3639, 3626, 11678, 7053, 5419, 38, 321, 1133, 24899, 28095, 5419, 548, 16, 389, 16140, 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 ]
pragma solidity 0.5.16; 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 IBoostedVaultWithLockup { /** * @dev Stakes a given amount of the StakingToken for the sender * @param _amount Units of StakingToken */ function stake(uint256 _amount) external; /** * @dev Stakes a given amount of the StakingToken for a given beneficiary * @param _beneficiary Staked tokens are credited to this address * @param _amount Units of StakingToken */ function stake(address _beneficiary, uint256 _amount) external; /** * @dev Withdraws stake from pool and claims any unlocked rewards. * Note, this function is costly - the args for _claimRewards * should be determined off chain and then passed to other fn */ function exit() external; /** * @dev Withdraws stake from pool and claims any unlocked rewards. * @param _first Index of the first array element to claim * @param _last Index of the last array element to claim */ function exit(uint256 _first, uint256 _last) external; /** * @dev Withdraws given stake amount from the pool * @param _amount Units of the staked token to withdraw */ function withdraw(uint256 _amount) external; /** * @dev Claims only the tokens that have been immediately unlocked, not including * those that are in the lockers. */ function claimReward() external; /** * @dev Claims all unlocked rewards for sender. * Note, this function is costly - the args for _claimRewards * should be determined off chain and then passed to other fn */ function claimRewards() external; /** * @dev Claims all unlocked rewards for sender. Both immediately unlocked * rewards and also locked rewards past their time lock. * @param _first Index of the first array element to claim * @param _last Index of the last array element to claim */ function claimRewards(uint256 _first, uint256 _last) external; /** * @dev Pokes a given account to reset the boost */ function pokeBoost(address _account) external; /** * @dev Gets the RewardsToken */ function getRewardToken() external view returns (IERC20); /** * @dev Gets the last applicable timestamp for this reward period */ function lastTimeRewardApplicable() external view returns (uint256); /** * @dev Calculates the amount of unclaimed rewards per token since last update, * and sums with stored to give the new cumulative reward per token * @return 'Reward' per staked token */ function rewardPerToken() external view returns (uint256); /** * @dev Returned the units of IMMEDIATELY claimable rewards a user has to receive. Note - this * does NOT include the majority of rewards which will be locked up. * @param _account User address * @return Total reward amount earned */ function earned(address _account) external view returns (uint256); /** * @dev Calculates all unclaimed reward data, finding both immediately unlocked rewards * and those that have passed their time lock. * @param _account User address * @return amount Total units of unclaimed rewards * @return first Index of the first userReward that has unlocked * @return last Index of the last userReward that has unlocked */ function unclaimedRewards(address _account) external view returns ( uint256 amount, uint256 first, uint256 last ); } contract ModuleKeys { // Governance // =========== // keccak256("Governance"); bytes32 internal constant KEY_GOVERNANCE = 0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d; //keccak256("Staking"); bytes32 internal constant KEY_STAKING = 0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034; //keccak256("ProxyAdmin"); bytes32 internal constant KEY_PROXY_ADMIN = 0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1; // mStable // ======= // keccak256("OracleHub"); bytes32 internal constant KEY_ORACLE_HUB = 0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040; // keccak256("Manager"); bytes32 internal constant KEY_MANAGER = 0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f; //keccak256("Recollateraliser"); bytes32 internal constant KEY_RECOLLATERALISER = 0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f; //keccak256("MetaToken"); bytes32 internal constant KEY_META_TOKEN = 0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2; // keccak256("SavingsManager"); bytes32 internal constant KEY_SAVINGS_MANAGER = 0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1; // keccak256("Liquidator"); bytes32 internal constant KEY_LIQUIDATOR = 0x1e9cb14d7560734a61fa5ff9273953e971ff3cd9283c03d8346e3264617933d4; } interface INexus { function governor() external view returns (address); function getModule(bytes32 key) external view returns (address); function proposeModule(bytes32 _key, address _addr) external; function cancelProposedModule(bytes32 _key) external; function acceptProposedModule(bytes32 _key) external; function acceptProposedModules(bytes32[] calldata _keys) external; function requestLockModule(bytes32 _key) external; function cancelLockModule(bytes32 _key) external; function lockModule(bytes32 _key) external; } contract InitializableModule2 is ModuleKeys { INexus public constant nexus = INexus(0xAFcE80b19A8cE13DEc0739a1aaB7A028d6845Eb3); /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyGovernor() { require(msg.sender == _governor(), "Only governor can execute"); _; } /** * @dev Modifier to allow function calls only from the Governance. * Governance is either Governor address or Governance address. */ modifier onlyGovernance() { require( msg.sender == _governor() || msg.sender == _governance(), "Only governance can execute" ); _; } /** * @dev Modifier to allow function calls only from the ProxyAdmin. */ modifier onlyProxyAdmin() { require(msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute"); _; } /** * @dev Modifier to allow function calls only from the Manager. */ modifier onlyManager() { require(msg.sender == _manager(), "Only manager can execute"); _; } /** * @dev Returns Governor address from the Nexus * @return Address of Governor Contract */ function _governor() internal view returns (address) { return nexus.governor(); } /** * @dev Returns Governance Module address from the Nexus * @return Address of the Governance (Phase 2) */ function _governance() internal view returns (address) { return nexus.getModule(KEY_GOVERNANCE); } /** * @dev Return Staking Module address from the Nexus * @return Address of the Staking Module contract */ function _staking() internal view returns (address) { return nexus.getModule(KEY_STAKING); } /** * @dev Return ProxyAdmin Module address from the Nexus * @return Address of the ProxyAdmin Module contract */ function _proxyAdmin() internal view returns (address) { return nexus.getModule(KEY_PROXY_ADMIN); } /** * @dev Return MetaToken Module address from the Nexus * @return Address of the MetaToken Module contract */ function _metaToken() internal view returns (address) { return nexus.getModule(KEY_META_TOKEN); } /** * @dev Return OracleHub Module address from the Nexus * @return Address of the OracleHub Module contract */ function _oracleHub() internal view returns (address) { return nexus.getModule(KEY_ORACLE_HUB); } /** * @dev Return Manager Module address from the Nexus * @return Address of the Manager Module contract */ function _manager() internal view returns (address) { return nexus.getModule(KEY_MANAGER); } /** * @dev Return SavingsManager Module address from the Nexus * @return Address of the SavingsManager Module contract */ function _savingsManager() internal view returns (address) { return nexus.getModule(KEY_SAVINGS_MANAGER); } /** * @dev Return Recollateraliser Module address from the Nexus * @return Address of the Recollateraliser Module contract (Phase 2) */ function _recollateraliser() internal view returns (address) { return nexus.getModule(KEY_RECOLLATERALISER); } } interface IRewardsDistributionRecipient { function notifyRewardAmount(uint256 reward) external; function getRewardToken() external view returns (IERC20); } contract InitializableRewardsDistributionRecipient is IRewardsDistributionRecipient, InitializableModule2 { // @abstract function notifyRewardAmount(uint256 reward) external; function getRewardToken() external view returns (IERC20); // This address has the ability to distribute the rewards address public rewardsDistributor; /** @dev Recipient is a module, governed by mStable governance */ function _initialize(address _rewardsDistributor) internal { rewardsDistributor = _rewardsDistributor; } /** * @dev Only the rewards distributor can notify about rewards */ modifier onlyRewardsDistributor() { require(msg.sender == rewardsDistributor, "Caller is not reward distributor"); _; } /** * @dev Change the rewardsDistributor - only called by mStable governor * @param _rewardsDistributor Address of the new distributor */ function setRewardsDistribution(address _rewardsDistributor) external onlyGovernor { rewardsDistributor = _rewardsDistributor; } } contract IERC20WithCheckpointing { function balanceOf(address _owner) public view returns (uint256); function balanceOfAt(address _owner, uint256 _blockNumber) public view returns (uint256); function totalSupply() public view returns (uint256); function totalSupplyAt(uint256 _blockNumber) public view returns (uint256); } contract IIncentivisedVotingLockup is IERC20WithCheckpointing { function getLastUserPoint(address _addr) external view returns ( int128 bias, int128 slope, uint256 ts ); function createLock(uint256 _value, uint256 _unlockTime) external; function withdraw() external; function increaseLockAmount(uint256 _value) external; function increaseLockLength(uint256 _unlockTime) external; function eject(address _user) external; function expireContract() external; function claimReward() public; function earned(address _account) public view returns (uint256); } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ /** * @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; } } /** * @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"); } } 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"); } } } contract InitializableReentrancyGuard { bool private _notEntered; function _initialize() internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } library StableMath { using SafeMath for uint256; /** * @dev Scaling unit for use in specific calculations, * where 1 * 10**18, or 1e18 represents a unit '1' */ uint256 private constant FULL_SCALE = 1e18; /** * @notice Token Ratios are used when converting between units of bAsset, mAsset and MTA * Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold) * @dev bAsset ratio unit for use in exact calculations, * where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit */ uint256 private constant RATIO_SCALE = 1e8; /** * @dev Provides an interface to the scaling unit * @return Scaling unit (1e18 or 1 * 10**18) */ function getFullScale() internal pure returns (uint256) { return FULL_SCALE; } /** * @dev Provides an interface to the ratio unit * @return Ratio scale unit (1e8 or 1 * 10**8) */ function getRatioScale() internal pure returns (uint256) { return RATIO_SCALE; } /** * @dev Scales a given integer to the power of the full scale. * @param x Simple uint256 to scale * @return Scaled value a to an exact number */ function scaleInteger(uint256 x) internal pure returns (uint256) { return x.mul(FULL_SCALE); } /*************************************** PRECISE ARITHMETIC ****************************************/ /** * @dev Multiplies two precise units, and then truncates by the full scale * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) { return mulTruncateScale(x, y, FULL_SCALE); } /** * @dev Multiplies two precise units, and then truncates by the given scale. For example, * when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18 * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @param scale Scale unit * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncateScale( uint256 x, uint256 y, uint256 scale ) internal pure returns (uint256) { // e.g. assume scale = fullScale // z = 10e18 * 9e17 = 9e36 uint256 z = x.mul(y); // return 9e38 / 1e18 = 9e18 return z.div(scale); } /** * @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit, rounded up to the closest base unit. */ function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e17 * 17268172638 = 138145381104e17 uint256 scaled = x.mul(y); // e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17 uint256 ceil = scaled.add(FULL_SCALE.sub(1)); // e.g. 13814538111.399...e18 / 1e18 = 13814538111 return ceil.div(FULL_SCALE); } /** * @dev Precisely divides two units, by first scaling the left hand operand. Useful * for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17) * @param x Left hand input to division * @param y Right hand input to division * @return Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e18 * 1e18 = 8e36 uint256 z = x.mul(FULL_SCALE); // e.g. 8e36 / 10e18 = 8e17 return z.div(y); } /*************************************** RATIO FUNCS ****************************************/ /** * @dev Multiplies and truncates a token ratio, essentially flooring the result * i.e. How much mAsset is this bAsset worth? * @param x Left hand operand to multiplication (i.e Exact quantity) * @param ratio bAsset ratio * @return Result after multiplying the two inputs and then dividing by the ratio scale */ function mulRatioTruncate(uint256 x, uint256 ratio) internal pure returns (uint256 c) { return mulTruncateScale(x, ratio, RATIO_SCALE); } /** * @dev Multiplies and truncates a token ratio, rounding up the result * i.e. How much mAsset is this bAsset worth? * @param x Left hand input to multiplication (i.e Exact quantity) * @param ratio bAsset ratio * @return Result after multiplying the two inputs and then dividing by the shared * ratio scale, rounded up to the closest base unit. */ function mulRatioTruncateCeil(uint256 x, uint256 ratio) internal pure returns (uint256) { // e.g. How much mAsset should I burn for this bAsset (x)? // 1e18 * 1e8 = 1e26 uint256 scaled = x.mul(ratio); // 1e26 + 9.99e7 = 100..00.999e8 uint256 ceil = scaled.add(RATIO_SCALE.sub(1)); // return 100..00.999e8 / 1e8 = 1e18 return ceil.div(RATIO_SCALE); } /** * @dev Precisely divides two ratioed units, by first scaling the left hand operand * i.e. How much bAsset is this mAsset worth? * @param x Left hand operand in division * @param ratio bAsset ratio * @return Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) { // e.g. 1e14 * 1e8 = 1e22 uint256 y = x.mul(RATIO_SCALE); // return 1e22 / 1e12 = 1e10 return y.div(ratio); } /*************************************** HELPERS ****************************************/ /** * @dev Calculates minimum of two numbers * @param x Left hand input * @param y Right hand input * @return Minimum of the two inputs */ function min(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? y : x; } /** * @dev Calculated maximum of two numbers * @param x Left hand input * @param y Right hand input * @return Maximum of the two inputs */ function max(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? x : y; } /** * @dev Clamps a value to an upper bound * @param x Left hand input * @param upperBound Maximum possible value to return * @return Input x clamped to a maximum value, upperBound */ function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) { return x > upperBound ? upperBound : x; } } library Root { using SafeMath for uint256; /** * @dev Returns the square root of a given number * @param x Input * @return y Square root of Input */ function sqrt(uint256 x) internal pure returns (uint256 y) { 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.add(x).div(r)) >> 1; r = (r.add(x).div(r)) >> 1; r = (r.add(x).div(r)) >> 1; r = (r.add(x).div(r)) >> 1; r = (r.add(x).div(r)) >> 1; r = (r.add(x).div(r)) >> 1; r = (r.add(x).div(r)) >> 1; // Seven iterations should be enough uint256 r1 = x.div(r); return uint256(r < r1 ? r : r1); } } } interface IBoostDirector { function getBalance(address _user) external returns (uint256); function setDirection( address _old, address _new, bool _pokeNew ) external; function whitelistVaults(address[] calldata _vaults) external; } contract BoostedTokenWrapper is InitializableReentrancyGuard { using SafeMath for uint256; using StableMath for uint256; using SafeERC20 for IERC20; IERC20 public constant stakingToken = IERC20(0x30647a72Dc82d7Fbb1123EA74716aB8A317Eac19); // mStable MTA Staking contract via the BoostDirectorV2 IBoostDirector public constant boostDirector = IBoostDirector(0xBa05FD2f20AE15B0D3f20DDc6870FeCa6ACd3592); uint256 private _totalBoostedSupply; mapping(address => uint256) private _boostedBalances; mapping(address => uint256) private _rawBalances; // Vars for use in the boost calculations uint256 private constant MIN_DEPOSIT = 1e18; uint256 private constant MAX_VMTA = 600000e18; uint256 private constant MAX_BOOST = 3e18; uint256 private constant MIN_BOOST = 1e18; uint256 private constant FLOOR = 98e16; uint256 public constant boostCoeff = 9; uint256 public constant priceCoeff = 1e17; /** * @dev TokenWrapper constructor **/ function _initialize() internal { InitializableReentrancyGuard._initialize(); } /** * @dev Get the total boosted amount * @return uint256 total supply */ function totalSupply() public view returns (uint256) { return _totalBoostedSupply; } /** * @dev Get the boosted balance of a given account * @param _account User for which to retrieve balance */ function balanceOf(address _account) public view returns (uint256) { return _boostedBalances[_account]; } /** * @dev Get the RAW balance of a given account * @param _account User for which to retrieve balance */ function rawBalanceOf(address _account) public view returns (uint256) { return _rawBalances[_account]; } /** * @dev Read the boost for the given address * @param _account User for which to return the boost * @return boost where 1x == 1e18 */ function getBoost(address _account) public view returns (uint256) { return balanceOf(_account).divPrecisely(rawBalanceOf(_account)); } /** * @dev Deposits a given amount of StakingToken from sender * @param _amount Units of StakingToken */ function _stakeRaw(address _beneficiary, uint256 _amount) internal nonReentrant { _rawBalances[_beneficiary] = _rawBalances[_beneficiary].add(_amount); stakingToken.safeTransferFrom(msg.sender, address(this), _amount); } /** * @dev Withdraws a given stake from sender * @param _amount Units of StakingToken */ function _withdrawRaw(uint256 _amount) internal nonReentrant { _rawBalances[msg.sender] = _rawBalances[msg.sender].sub(_amount); stakingToken.safeTransfer(msg.sender, _amount); } /** * @dev Updates the boost for the given address according to the formula * boost = min(0.5 + c * vMTA_balance / imUSD_locked^(7/8), 1.5) * If rawBalance <= MIN_DEPOSIT, boost is 0 * @param _account User for which to update the boost */ function _setBoost(address _account) internal { uint256 rawBalance = _rawBalances[_account]; uint256 boostedBalance = _boostedBalances[_account]; uint256 boost = MIN_BOOST; // Check whether balance is sufficient // is_boosted is used to minimize gas usage uint256 scaledBalance = (rawBalance * priceCoeff) / 1e18; if (rawBalance >= MIN_DEPOSIT) { uint256 votingWeight = boostDirector.getBalance(_account); boost = _computeBoost(scaledBalance, votingWeight); } uint256 newBoostedBalance = rawBalance.mulTruncate(boost); if (newBoostedBalance != boostedBalance) { _totalBoostedSupply = _totalBoostedSupply.sub(boostedBalance).add(newBoostedBalance); _boostedBalances[_account] = newBoostedBalance; } } /** * @dev Computes the boost for * boost = min(m, max(1, 0.95 + c * min(voting_weight, f) / deposit^(3/4))) * @param _scaledDeposit deposit amount in terms of USD */ function _computeBoost(uint256 _scaledDeposit, uint256 _votingWeight) private view returns (uint256 boost) { if (_votingWeight == 0) return MIN_BOOST; // Compute balance to the power 3/4 uint256 sqrt1 = Root.sqrt(_scaledDeposit * 1e6); uint256 sqrt2 = Root.sqrt(sqrt1); uint256 denominator = sqrt1 * sqrt2; boost = (((StableMath.min(_votingWeight, MAX_VMTA) * boostCoeff) / 10) * 1e18) / denominator; boost = StableMath.min(MAX_BOOST, StableMath.max(MIN_BOOST, FLOOR + boost)); } } 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; } 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); } } // Internal // Libs /** * @title BoostedSavingsVault * @author Stability Labs Pty. Ltd. * @notice Accrues rewards second by second, based on a users boosted balance * @dev Forked from rewards/staking/StakingRewards.sol * Changes: * - Lockup implemented in `updateReward` hook (20% unlock immediately, 80% locked for 6 months) * - `updateBoost` hook called after every external action to reset a users boost * - Struct packing of common data * - Searching for and claiming of unlocked rewards */ contract BoostedSavingsVault is IBoostedVaultWithLockup, Initializable, InitializableRewardsDistributionRecipient, BoostedTokenWrapper { using StableMath for uint256; using SafeCast for uint256; event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount, address payer); event Withdrawn(address indexed user, uint256 amount); event Poked(address indexed user); event RewardPaid(address indexed user, uint256 reward); IERC20 public constant rewardsToken = IERC20(0xa3BeD4E1c75D00fa6f4E5E6922DB7261B5E9AcD2); uint64 public constant DURATION = 7 days; // Length of token lockup, after rewards are earned uint256 public constant LOCKUP = 26 weeks; // Percentage of earned tokens unlocked immediately uint64 public constant UNLOCK = 2e17; // Timestamp for current period finish uint256 public periodFinish; // RewardRate for the rest of the PERIOD uint256 public rewardRate; // Last time any user took action uint256 public lastUpdateTime; // Ever increasing rewardPerToken rate, based on % of total supply uint256 public rewardPerTokenStored; mapping(address => UserData) public userData; // Locked reward tracking mapping(address => Reward[]) public userRewards; mapping(address => uint64) public userClaim; struct UserData { uint128 rewardPerTokenPaid; uint128 rewards; uint64 lastAction; uint64 rewardCount; } struct Reward { uint64 start; uint64 finish; uint128 rate; } /** * @dev StakingRewards is a TokenWrapper and RewardRecipient * Constants added to bytecode at deployTime to reduce SLOAD cost */ function initialize(address _rewardsDistributor) external initializer { InitializableRewardsDistributionRecipient._initialize(_rewardsDistributor); BoostedTokenWrapper._initialize(); } /** * @dev Updates the reward for a given address, before executing function. * Locks 80% of new rewards up for 6 months, vesting linearly from (time of last action + 6 months) to * (now + 6 months). This allows rewards to be distributed close to how they were accrued, as opposed * to locking up for a flat 6 months from the time of this fn call (allowing more passive accrual). */ modifier updateReward(address _account) { _updateReward(_account); _; } function _updateReward(address _account) internal { uint256 currentTime = block.timestamp; uint64 currentTime64 = SafeCast.toUint64(currentTime); // Setting of global vars (uint256 newRewardPerToken, uint256 lastApplicableTime) = _rewardPerToken(); // If statement protects against loss in initialisation case if (newRewardPerToken > 0) { rewardPerTokenStored = newRewardPerToken; lastUpdateTime = lastApplicableTime; // Setting of personal vars based on new globals if (_account != address(0)) { UserData memory data = userData[_account]; uint256 earned = _earned(_account, data.rewardPerTokenPaid, newRewardPerToken); // If earned == 0, then it must either be the initial stake, or an action in the // same block, since new rewards unlock after each block. if (earned > 0) { uint256 unlocked = earned.mulTruncate(UNLOCK); uint256 locked = earned.sub(unlocked); userRewards[_account].push( Reward({ start: SafeCast.toUint64(LOCKUP.add(data.lastAction)), finish: SafeCast.toUint64(LOCKUP.add(currentTime)), rate: SafeCast.toUint128(locked.div(currentTime.sub(data.lastAction))) }) ); userData[_account] = UserData({ rewardPerTokenPaid: SafeCast.toUint128(newRewardPerToken), rewards: SafeCast.toUint128(unlocked.add(data.rewards)), lastAction: currentTime64, rewardCount: data.rewardCount + 1 }); } else { userData[_account] = UserData({ rewardPerTokenPaid: SafeCast.toUint128(newRewardPerToken), rewards: data.rewards, lastAction: currentTime64, rewardCount: data.rewardCount }); } } } else if (_account != address(0)) { // This should only be hit once, for first staker in initialisation case userData[_account].lastAction = currentTime64; } } /** @dev Updates the boost for a given address, after the rest of the function has executed */ modifier updateBoost(address _account) { _; _setBoost(_account); } /*************************************** ACTIONS - EXTERNAL ****************************************/ /** * @dev Stakes a given amount of the StakingToken for the sender * @param _amount Units of StakingToken */ function stake(uint256 _amount) external updateReward(msg.sender) updateBoost(msg.sender) { _stake(msg.sender, _amount); } /** * @dev Stakes a given amount of the StakingToken for a given beneficiary * @param _beneficiary Staked tokens are credited to this address * @param _amount Units of StakingToken */ function stake(address _beneficiary, uint256 _amount) external updateReward(_beneficiary) updateBoost(_beneficiary) { _stake(_beneficiary, _amount); } /** * @dev Withdraws stake from pool and claims any unlocked rewards. * Note, this function is costly - the args for _claimRewards * should be determined off chain and then passed to other fn */ function exit() external updateReward(msg.sender) updateBoost(msg.sender) { _withdraw(rawBalanceOf(msg.sender)); (uint256 first, uint256 last) = _unclaimedEpochs(msg.sender); _claimRewards(first, last); } /** * @dev Withdraws stake from pool and claims any unlocked rewards. * @param _first Index of the first array element to claim * @param _last Index of the last array element to claim */ function exit(uint256 _first, uint256 _last) external updateReward(msg.sender) updateBoost(msg.sender) { _withdraw(rawBalanceOf(msg.sender)); _claimRewards(_first, _last); } /** * @dev Withdraws given stake amount from the pool * @param _amount Units of the staked token to withdraw */ function withdraw(uint256 _amount) external updateReward(msg.sender) updateBoost(msg.sender) { _withdraw(_amount); } /** * @dev Claims only the tokens that have been immediately unlocked, not including * those that are in the lockers. */ function claimReward() external updateReward(msg.sender) updateBoost(msg.sender) { uint256 unlocked = userData[msg.sender].rewards; userData[msg.sender].rewards = 0; if (unlocked > 0) { rewardsToken.safeTransfer(msg.sender, unlocked); emit RewardPaid(msg.sender, unlocked); } } /** * @dev Claims all unlocked rewards for sender. * Note, this function is costly - the args for _claimRewards * should be determined off chain and then passed to other fn */ function claimRewards() external updateReward(msg.sender) updateBoost(msg.sender) { (uint256 first, uint256 last) = _unclaimedEpochs(msg.sender); _claimRewards(first, last); } /** * @dev Claims all unlocked rewards for sender. Both immediately unlocked * rewards and also locked rewards past their time lock. * @param _first Index of the first array element to claim * @param _last Index of the last array element to claim */ function claimRewards(uint256 _first, uint256 _last) external updateReward(msg.sender) updateBoost(msg.sender) { _claimRewards(_first, _last); } /** * @dev Pokes a given account to reset the boost */ function pokeBoost(address _account) external updateReward(_account) updateBoost(_account) { emit Poked(_account); } /*************************************** ACTIONS - INTERNAL ****************************************/ /** * @dev Claims all unlocked rewards for sender. Both immediately unlocked * rewards and also locked rewards past their time lock. * @param _first Index of the first array element to claim * @param _last Index of the last array element to claim */ function _claimRewards(uint256 _first, uint256 _last) internal { (uint256 unclaimed, uint256 lastTimestamp) = _unclaimedRewards(msg.sender, _first, _last); userClaim[msg.sender] = uint64(lastTimestamp); uint256 unlocked = userData[msg.sender].rewards; userData[msg.sender].rewards = 0; uint256 total = unclaimed.add(unlocked); if (total > 0) { rewardsToken.safeTransfer(msg.sender, total); emit RewardPaid(msg.sender, total); } } /** * @dev Internally stakes an amount by depositing from sender, * and crediting to the specified beneficiary * @param _beneficiary Staked tokens are credited to this address * @param _amount Units of StakingToken */ function _stake(address _beneficiary, uint256 _amount) internal { require(_amount > 0, "Cannot stake 0"); require(_beneficiary != address(0), "Invalid beneficiary address"); _stakeRaw(_beneficiary, _amount); emit Staked(_beneficiary, _amount, msg.sender); } /** * @dev Withdraws raw units from the sender * @param _amount Units of StakingToken */ function _withdraw(uint256 _amount) internal { require(_amount > 0, "Cannot withdraw 0"); _withdrawRaw(_amount); emit Withdrawn(msg.sender, _amount); } /*************************************** GETTERS ****************************************/ /** * @dev Gets the RewardsToken */ function getRewardToken() external view returns (IERC20) { return rewardsToken; } /** * @dev Gets the last applicable timestamp for this reward period */ function lastTimeRewardApplicable() public view returns (uint256) { return StableMath.min(block.timestamp, periodFinish); } /** * @dev Calculates the amount of unclaimed rewards per token since last update, * and sums with stored to give the new cumulative reward per token * @return 'Reward' per staked token */ function rewardPerToken() public view returns (uint256) { (uint256 rewardPerToken_, ) = _rewardPerToken(); return rewardPerToken_; } function _rewardPerToken() internal view returns (uint256 rewardPerToken_, uint256 lastTimeRewardApplicable_) { uint256 lastApplicableTime = lastTimeRewardApplicable(); // + 1 SLOAD uint256 timeDelta = lastApplicableTime.sub(lastUpdateTime); // + 1 SLOAD // If this has been called twice in the same block, shortcircuit to reduce gas if (timeDelta == 0) { return (rewardPerTokenStored, lastApplicableTime); } // new reward units to distribute = rewardRate * timeSinceLastUpdate uint256 rewardUnitsToDistribute = rewardRate.mul(timeDelta); // + 1 SLOAD uint256 supply = totalSupply(); // + 1 SLOAD // If there is no StakingToken liquidity, avoid div(0) // If there is nothing to distribute, short circuit if (supply == 0 || rewardUnitsToDistribute == 0) { return (rewardPerTokenStored, lastApplicableTime); } // new reward units per token = (rewardUnitsToDistribute * 1e18) / totalTokens uint256 unitsToDistributePerToken = rewardUnitsToDistribute.divPrecisely(supply); // return summed rate return (rewardPerTokenStored.add(unitsToDistributePerToken), lastApplicableTime); // + 1 SLOAD } /** * @dev Returned the units of IMMEDIATELY claimable rewards a user has to receive. Note - this * does NOT include the majority of rewards which will be locked up. * @param _account User address * @return Total reward amount earned */ function earned(address _account) public view returns (uint256) { uint256 newEarned = _earned( _account, userData[_account].rewardPerTokenPaid, rewardPerToken() ); uint256 immediatelyUnlocked = newEarned.mulTruncate(UNLOCK); return immediatelyUnlocked.add(userData[_account].rewards); } /** * @dev Calculates all unclaimed reward data, finding both immediately unlocked rewards * and those that have passed their time lock. * @param _account User address * @return amount Total units of unclaimed rewards * @return first Index of the first userReward that has unlocked * @return last Index of the last userReward that has unlocked */ function unclaimedRewards(address _account) external view returns ( uint256 amount, uint256 first, uint256 last ) { (first, last) = _unclaimedEpochs(_account); (uint256 unlocked, ) = _unclaimedRewards(_account, first, last); amount = unlocked.add(earned(_account)); } /** @dev Returns only the most recently earned rewards */ function _earned( address _account, uint256 _userRewardPerTokenPaid, uint256 _currentRewardPerToken ) internal view returns (uint256) { // current rate per token - rate user previously received uint256 userRewardDelta = _currentRewardPerToken.sub(_userRewardPerTokenPaid); // + 1 SLOAD // Short circuit if there is nothing new to distribute if (userRewardDelta == 0) { return 0; } // new reward = staked tokens * difference in rate uint256 userNewReward = balanceOf(_account).mulTruncate(userRewardDelta); // + 1 SLOAD // add to previous rewards return userNewReward; } /** * @dev Gets the first and last indexes of array elements containing unclaimed rewards */ function _unclaimedEpochs(address _account) internal view returns (uint256 first, uint256 last) { uint64 lastClaim = userClaim[_account]; uint256 firstUnclaimed = _findFirstUnclaimed(lastClaim, _account); uint256 lastUnclaimed = _findLastUnclaimed(_account); return (firstUnclaimed, lastUnclaimed); } /** * @dev Sums the cumulative rewards from a valid range */ function _unclaimedRewards( address _account, uint256 _first, uint256 _last ) internal view returns (uint256 amount, uint256 latestTimestamp) { uint256 currentTime = block.timestamp; uint64 lastClaim = userClaim[_account]; // Check for no rewards unlocked uint256 totalLen = userRewards[_account].length; if (_first == 0 && _last == 0) { if (totalLen == 0 || currentTime <= userRewards[_account][0].start) { return (0, currentTime); } } // If there are previous unlocks, check for claims that would leave them untouchable if (_first > 0) { require( lastClaim >= userRewards[_account][_first.sub(1)].finish, "Invalid _first arg: Must claim earlier entries" ); } uint256 count = _last.sub(_first).add(1); for (uint256 i = 0; i < count; i++) { uint256 id = _first.add(i); Reward memory rwd = userRewards[_account][id]; require(currentTime >= rwd.start && lastClaim <= rwd.finish, "Invalid epoch"); uint256 endTime = StableMath.min(rwd.finish, currentTime); uint256 startTime = StableMath.max(rwd.start, lastClaim); uint256 unclaimed = endTime.sub(startTime).mul(rwd.rate); amount = amount.add(unclaimed); } // Calculate last relevant timestamp here to allow users to avoid issue of OOG errors // by claiming rewards in batches. latestTimestamp = StableMath.min(currentTime, userRewards[_account][_last].finish); } /** * @dev Uses binarysearch to find the unclaimed lockups for a given account */ function _findFirstUnclaimed(uint64 _lastClaim, address _account) internal view returns (uint256 first) { uint256 len = userRewards[_account].length; if (len == 0) return 0; // Binary search uint256 min = 0; uint256 max = len - 1; // Will be always enough for 128-bit numbers for (uint256 i = 0; i < 128; i++) { if (min >= max) break; uint256 mid = (min.add(max).add(1)).div(2); if (_lastClaim > userRewards[_account][mid].start) { min = mid; } else { max = mid.sub(1); } } return min; } /** * @dev Uses binarysearch to find the unclaimed lockups for a given account */ function _findLastUnclaimed(address _account) internal view returns (uint256 first) { uint256 len = userRewards[_account].length; if (len == 0) return 0; // Binary search uint256 min = 0; uint256 max = len - 1; // Will be always enough for 128-bit numbers for (uint256 i = 0; i < 128; i++) { if (min >= max) break; uint256 mid = (min.add(max).add(1)).div(2); if (now > userRewards[_account][mid].start) { min = mid; } else { max = mid.sub(1); } } return min; } /*************************************** ADMIN ****************************************/ /** * @dev Notifies the contract that new rewards have been added. * Calculates an updated rewardRate based on the rewards in period. * @param _reward Units of RewardToken that have been added to the pool */ function notifyRewardAmount(uint256 _reward) external onlyRewardsDistributor updateReward(address(0)) { require(_reward < 1e24, "Cannot notify with more than a million units"); uint256 currentTime = block.timestamp; // If previous period over, reset rewardRate if (currentTime >= periodFinish) { rewardRate = _reward.div(DURATION); } // If additional reward to existing period, calc sum else { uint256 remaining = periodFinish.sub(currentTime); uint256 leftover = remaining.mul(rewardRate); rewardRate = _reward.add(leftover).div(DURATION); } lastUpdateTime = currentTime; periodFinish = currentTime.add(DURATION); emit RewardAdded(_reward); } }
mStable MTA Staking contract via the BoostDirectorV2 Vars for use in the boost calculations
contract BoostedTokenWrapper is InitializableReentrancyGuard { using SafeMath for uint256; using StableMath for uint256; using SafeERC20 for IERC20; IERC20 public constant stakingToken = IERC20(0x30647a72Dc82d7Fbb1123EA74716aB8A317Eac19); IBoostDirector public constant boostDirector = IBoostDirector(0xBa05FD2f20AE15B0D3f20DDc6870FeCa6ACd3592); uint256 private _totalBoostedSupply; mapping(address => uint256) private _boostedBalances; mapping(address => uint256) private _rawBalances; uint256 private constant MIN_DEPOSIT = 1e18; uint256 private constant MAX_VMTA = 600000e18; uint256 private constant MAX_BOOST = 3e18; uint256 private constant MIN_BOOST = 1e18; uint256 private constant FLOOR = 98e16; uint256 public constant boostCoeff = 9; uint256 public constant priceCoeff = 1e17; function _initialize() internal { InitializableReentrancyGuard._initialize(); } function totalSupply() public view returns (uint256) { return _totalBoostedSupply; } function balanceOf(address _account) public view returns (uint256) { return _boostedBalances[_account]; } function rawBalanceOf(address _account) public view returns (uint256) { return _rawBalances[_account]; } function getBoost(address _account) public view returns (uint256) { return balanceOf(_account).divPrecisely(rawBalanceOf(_account)); } function _stakeRaw(address _beneficiary, uint256 _amount) internal nonReentrant { _rawBalances[_beneficiary] = _rawBalances[_beneficiary].add(_amount); stakingToken.safeTransferFrom(msg.sender, address(this), _amount); } function _withdrawRaw(uint256 _amount) internal nonReentrant { _rawBalances[msg.sender] = _rawBalances[msg.sender].sub(_amount); stakingToken.safeTransfer(msg.sender, _amount); } function _setBoost(address _account) internal { uint256 rawBalance = _rawBalances[_account]; uint256 boostedBalance = _boostedBalances[_account]; uint256 boost = MIN_BOOST; uint256 scaledBalance = (rawBalance * priceCoeff) / 1e18; if (rawBalance >= MIN_DEPOSIT) { uint256 votingWeight = boostDirector.getBalance(_account); boost = _computeBoost(scaledBalance, votingWeight); } uint256 newBoostedBalance = rawBalance.mulTruncate(boost); if (newBoostedBalance != boostedBalance) { _totalBoostedSupply = _totalBoostedSupply.sub(boostedBalance).add(newBoostedBalance); _boostedBalances[_account] = newBoostedBalance; } } function _setBoost(address _account) internal { uint256 rawBalance = _rawBalances[_account]; uint256 boostedBalance = _boostedBalances[_account]; uint256 boost = MIN_BOOST; uint256 scaledBalance = (rawBalance * priceCoeff) / 1e18; if (rawBalance >= MIN_DEPOSIT) { uint256 votingWeight = boostDirector.getBalance(_account); boost = _computeBoost(scaledBalance, votingWeight); } uint256 newBoostedBalance = rawBalance.mulTruncate(boost); if (newBoostedBalance != boostedBalance) { _totalBoostedSupply = _totalBoostedSupply.sub(boostedBalance).add(newBoostedBalance); _boostedBalances[_account] = newBoostedBalance; } } function _setBoost(address _account) internal { uint256 rawBalance = _rawBalances[_account]; uint256 boostedBalance = _boostedBalances[_account]; uint256 boost = MIN_BOOST; uint256 scaledBalance = (rawBalance * priceCoeff) / 1e18; if (rawBalance >= MIN_DEPOSIT) { uint256 votingWeight = boostDirector.getBalance(_account); boost = _computeBoost(scaledBalance, votingWeight); } uint256 newBoostedBalance = rawBalance.mulTruncate(boost); if (newBoostedBalance != boostedBalance) { _totalBoostedSupply = _totalBoostedSupply.sub(boostedBalance).add(newBoostedBalance); _boostedBalances[_account] = newBoostedBalance; } } function _computeBoost(uint256 _scaledDeposit, uint256 _votingWeight) private view returns (uint256 boost) { if (_votingWeight == 0) return MIN_BOOST; uint256 sqrt1 = Root.sqrt(_scaledDeposit * 1e6); uint256 sqrt2 = Root.sqrt(sqrt1); uint256 denominator = sqrt1 * sqrt2; boost = (((StableMath.min(_votingWeight, MAX_VMTA) * boostCoeff) / 10) * 1e18) / denominator; boost = StableMath.min(MAX_BOOST, StableMath.max(MIN_BOOST, FLOOR + boost)); } }
5,881,866
[ 1, 81, 30915, 490, 9833, 934, 6159, 6835, 3970, 326, 17980, 669, 28280, 58, 22, 27289, 364, 999, 316, 326, 14994, 20882, 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, 16351, 17980, 669, 329, 1345, 3611, 353, 10188, 6934, 426, 8230, 12514, 16709, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 934, 429, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 467, 654, 39, 3462, 1071, 5381, 384, 6159, 1345, 273, 467, 654, 39, 3462, 12, 20, 92, 5082, 30792, 69, 9060, 40, 71, 11149, 72, 27, 42, 9897, 22642, 41, 37, 5608, 27, 2313, 69, 38, 28, 37, 23, 4033, 41, 1077, 3657, 1769, 203, 565, 467, 26653, 28280, 1071, 5381, 14994, 28280, 273, 467, 26653, 28280, 12, 20, 20029, 69, 6260, 16894, 22, 74, 3462, 16985, 3600, 38, 20, 40, 23, 74, 3462, 5698, 71, 9470, 7301, 2954, 23508, 26, 2226, 72, 4763, 9975, 1769, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 26653, 329, 3088, 1283, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 25018, 329, 38, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 1899, 38, 26488, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 6989, 67, 1639, 28284, 273, 404, 73, 2643, 31, 203, 565, 2254, 5034, 3238, 5381, 4552, 67, 58, 6152, 37, 273, 1666, 11706, 73, 2643, 31, 203, 565, 2254, 5034, 3238, 5381, 4552, 67, 5315, 4005, 273, 890, 73, 2643, 31, 203, 565, 2254, 5034, 3238, 5381, 6989, 67, 5315, 4005, 273, 404, 73, 2643, 31, 203, 565, 2254, 5034, 3238, 5381, 478, 1502, 916, 273, 24645, 73, 2 ]
./full_match/1/0xF527c0F73d96F853A48D1B53Bcf3aCb4983CE702/sources/contracts/Campaign.sol
campaign_id task_id -> reward level task_id -> campaign_id task_id, user address -> claimed task_id -> isMultipleClaimed address -> boolean
{ using SafeERC20Upgradeable for IERC20Upgradeable; mapping(uint80 => CampaignInfo) private campaignInfos; mapping(uint80 => uint256) private taskToAmountReward; mapping(uint80 => uint80) private taskToCampaignId; mapping(uint80 => mapping(address => uint8)) private claimedTasks; mapping(uint80 => uint8) private multipleClaim; mapping(address => uint8) private isOperator; AggregatorV3Interface internal dataFeed; address private chappyToken; address private cookieToken; address private cutReceiver; address[] private admins; uint80 private newCampaignId; uint80 private newTaskId; uint72 private nonce; error InvalidSignature(); error InsufficentChappy(uint80); error InsufficentChappyNFT(uint80); error UnavailableCampaign(uint80); error TaskNotInCampaign(uint80, uint80); error ClaimedTask(uint80); error InsufficentFund(uint80); error Unauthorized(); error InvalidTime(); error InvalidAddress(); error InvalidNumber(); error SentZeroNative(); error SentNativeFailed(); error NativeNotAllowed(); error InvalidCampaign(uint80); error InvalidEligibility(uint80); error InvalidInput(); error Underflow(); error InvalidValue(); error InvalidFee(); error InvalidTip(); error InvalidReward(uint80); error AlreadyOperators(address); error NotOperators(address); error InvalidPriceFeed(); error InvalidPoint(); event ChangeAdmin(address[]); event ChangeToken(address); event AddOperator(address); event RemoveOperator(address); event CreateCampaign(uint80, uint80[]); event AddTasks(uint80, uint80[]); event ChangeCutReceiver(address); event ChangeTreasury(address); event ChangeSharePercent(uint16); event FundCampaign(uint80, uint256); event WithdrawFundCampaign(uint80, uint256); event ClaimReward(uint80[][]); struct CampaignInfo { address rewardToken; address collection; address owner; uint256 amount; uint256 minimumBalance; uint32 startAt; uint32 endAt; uint8 checkNFT; } struct CampaignInput { address rewardToken; address collection; uint256 minimumBalance; uint256 amount; uint32 startAt; uint32 endAt; uint8 checkNFT; } struct ClaimInput { uint80[][] taskIds; uint80[][] pointForMultiple; bytes signature; uint8[] isValidUser; } modifier onlyAdmins() { address[] memory memAdmins = admins; bool checked = false; for (uint256 idx = 0; idx < memAdmins.length; ++idx) { if (memAdmins[idx] == msg.sender) { checked = true; break; } } if (checked == false) { revert Unauthorized(); } _; } modifier onlyAdmins() { address[] memory memAdmins = admins; bool checked = false; for (uint256 idx = 0; idx < memAdmins.length; ++idx) { if (memAdmins[idx] == msg.sender) { checked = true; break; } } if (checked == false) { revert Unauthorized(); } _; } modifier onlyAdmins() { address[] memory memAdmins = admins; bool checked = false; for (uint256 idx = 0; idx < memAdmins.length; ++idx) { if (memAdmins[idx] == msg.sender) { checked = true; break; } } if (checked == false) { revert Unauthorized(); } _; } modifier onlyAdmins() { address[] memory memAdmins = admins; bool checked = false; for (uint256 idx = 0; idx < memAdmins.length; ++idx) { if (memAdmins[idx] == msg.sender) { checked = true; break; } } if (checked == false) { revert Unauthorized(); } _; } modifier byOperator() { bool checked = false; if (isOperator[msg.sender] == 1 || msg.sender == owner()) { checked = true; } if (checked == false) { revert Unauthorized(); } _; } modifier byOperator() { bool checked = false; if (isOperator[msg.sender] == 1 || msg.sender == owner()) { checked = true; } if (checked == false) { revert Unauthorized(); } _; } modifier byOperator() { bool checked = false; if (isOperator[msg.sender] == 1 || msg.sender == owner()) { checked = true; } if (checked == false) { revert Unauthorized(); } _; } function initialize( address operatorAddress, address chappyTokenAddress, address cookieTokenAddress, address cutReceiverAddress, address[] memory newAdmins, uint16 newSharePercent, address chainlinkPriceFeedNativeCoin ) external initializer { __Ownable_init_unchained(); __ReentrancyGuard_init_unchained(); if (newSharePercent > 10000) { revert InvalidNumber(); } dataFeed = AggregatorV3Interface( chainlinkPriceFeedNativeCoin ); isOperator[operatorAddress] = 1; admins = newAdmins; chappyToken = chappyTokenAddress; cookieToken = cookieTokenAddress; sharePercent = newSharePercent; cutReceiver = cutReceiverAddress; } function initialize( address operatorAddress, address chappyTokenAddress, address cookieTokenAddress, address cutReceiverAddress, address[] memory newAdmins, uint16 newSharePercent, address chainlinkPriceFeedNativeCoin ) external initializer { __Ownable_init_unchained(); __ReentrancyGuard_init_unchained(); if (newSharePercent > 10000) { revert InvalidNumber(); } dataFeed = AggregatorV3Interface( chainlinkPriceFeedNativeCoin ); isOperator[operatorAddress] = 1; admins = newAdmins; chappyToken = chappyTokenAddress; cookieToken = cookieTokenAddress; sharePercent = newSharePercent; cutReceiver = cutReceiverAddress; } function addOperator(address operatorAddress) external onlyOwner { if (isOperator[operatorAddress] == 1) { revert AlreadyOperators(operatorAddress); } isOperator[operatorAddress] = 1; emit AddOperator(operatorAddress); } function addOperator(address operatorAddress) external onlyOwner { if (isOperator[operatorAddress] == 1) { revert AlreadyOperators(operatorAddress); } isOperator[operatorAddress] = 1; emit AddOperator(operatorAddress); } function removeOperator(address operatorAddress) external onlyOwner { if (isOperator[operatorAddress] == 0) { revert NotOperators(operatorAddress); } isOperator[operatorAddress] = 0; emit RemoveOperator(operatorAddress); } function removeOperator(address operatorAddress) external onlyOwner { if (isOperator[operatorAddress] == 0) { revert NotOperators(operatorAddress); } isOperator[operatorAddress] = 0; emit RemoveOperator(operatorAddress); } function changeAdmins(address[] calldata newAdmins) external byOperator { admins = newAdmins; emit ChangeAdmin(newAdmins); } function changeTokenPlatform(address newToken) external byOperator { chappyToken = newToken; emit ChangeToken(newToken); } function createCampaign( CampaignInput calldata campaign, uint256[] calldata rewardEachTask, uint8[] calldata isMultipleClaim ) external payable onlyAdmins nonReentrant { if (rewardEachTask.length != isMultipleClaim.length) { revert InvalidInput(); } if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) { revert InvalidTime(); } if (campaign.collection == address(0)) { if (campaign.checkNFT == 1 || campaign.checkNFT == 2) { revert InvalidAddress(); } } if (campaign.checkNFT > 2) { revert InvalidValue(); } if ( campaign.rewardToken == address(0) && msg.value != campaign.amount ) { revert InvalidValue(); } if (campaign.rewardToken != address(0) && msg.value != 0) { revert InvalidValue(); } address clonedRewardToken = campaign.rewardToken; uint256 cutAmount = 0; uint256 actualAmount = 0; if (campaign.rewardToken != address(0)) { cutAmount = mulDiv(campaign.amount, sharePercent, 10000); actualAmount = campaign.amount - cutAmount; cutAmount = mulDiv(msg.value, sharePercent, 10000); actualAmount = msg.value - cutAmount; } CampaignInfo memory campaignInfo = CampaignInfo( clonedRewardToken, campaign.collection, msg.sender, actualAmount, campaign.minimumBalance, campaign.startAt, campaign.endAt, campaign.checkNFT ); uint80 taskId = newTaskId; uint80 campaignId = newCampaignId; campaignInfos[campaignId] = campaignInfo; uint80[] memory taskIds = new uint80[](rewardEachTask.length); for (uint80 idx; idx < rewardEachTask.length; ++idx) { if (rewardEachTask[idx] >= campaign.amount) { revert InvalidNumber(); } if (isMultipleClaim[idx] == 1) { multipleClaim[taskId] = 1; } taskToAmountReward[taskId] = rewardEachTask[idx]; taskToCampaignId[taskId] = campaignId; taskIds[idx] = taskId; ++taskId; } newTaskId = taskId; ++newCampaignId; if (clonedRewardToken == address(0)) { if (msg.value != campaign.amount) { revert InvalidInput(); } (bool sent_cut, bytes memory data2) = payable(cutReceiver).call{ value: cutAmount }(""); if (sent_cut == false) { revert SentNativeFailed(); } if (msg.value != 0 ether) { revert NativeNotAllowed(); } IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), address(this), actualAmount ); IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), cutReceiver, cutAmount ); } emit CreateCampaign(campaignId, taskIds); } function createCampaign( CampaignInput calldata campaign, uint256[] calldata rewardEachTask, uint8[] calldata isMultipleClaim ) external payable onlyAdmins nonReentrant { if (rewardEachTask.length != isMultipleClaim.length) { revert InvalidInput(); } if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) { revert InvalidTime(); } if (campaign.collection == address(0)) { if (campaign.checkNFT == 1 || campaign.checkNFT == 2) { revert InvalidAddress(); } } if (campaign.checkNFT > 2) { revert InvalidValue(); } if ( campaign.rewardToken == address(0) && msg.value != campaign.amount ) { revert InvalidValue(); } if (campaign.rewardToken != address(0) && msg.value != 0) { revert InvalidValue(); } address clonedRewardToken = campaign.rewardToken; uint256 cutAmount = 0; uint256 actualAmount = 0; if (campaign.rewardToken != address(0)) { cutAmount = mulDiv(campaign.amount, sharePercent, 10000); actualAmount = campaign.amount - cutAmount; cutAmount = mulDiv(msg.value, sharePercent, 10000); actualAmount = msg.value - cutAmount; } CampaignInfo memory campaignInfo = CampaignInfo( clonedRewardToken, campaign.collection, msg.sender, actualAmount, campaign.minimumBalance, campaign.startAt, campaign.endAt, campaign.checkNFT ); uint80 taskId = newTaskId; uint80 campaignId = newCampaignId; campaignInfos[campaignId] = campaignInfo; uint80[] memory taskIds = new uint80[](rewardEachTask.length); for (uint80 idx; idx < rewardEachTask.length; ++idx) { if (rewardEachTask[idx] >= campaign.amount) { revert InvalidNumber(); } if (isMultipleClaim[idx] == 1) { multipleClaim[taskId] = 1; } taskToAmountReward[taskId] = rewardEachTask[idx]; taskToCampaignId[taskId] = campaignId; taskIds[idx] = taskId; ++taskId; } newTaskId = taskId; ++newCampaignId; if (clonedRewardToken == address(0)) { if (msg.value != campaign.amount) { revert InvalidInput(); } (bool sent_cut, bytes memory data2) = payable(cutReceiver).call{ value: cutAmount }(""); if (sent_cut == false) { revert SentNativeFailed(); } if (msg.value != 0 ether) { revert NativeNotAllowed(); } IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), address(this), actualAmount ); IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), cutReceiver, cutAmount ); } emit CreateCampaign(campaignId, taskIds); } function createCampaign( CampaignInput calldata campaign, uint256[] calldata rewardEachTask, uint8[] calldata isMultipleClaim ) external payable onlyAdmins nonReentrant { if (rewardEachTask.length != isMultipleClaim.length) { revert InvalidInput(); } if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) { revert InvalidTime(); } if (campaign.collection == address(0)) { if (campaign.checkNFT == 1 || campaign.checkNFT == 2) { revert InvalidAddress(); } } if (campaign.checkNFT > 2) { revert InvalidValue(); } if ( campaign.rewardToken == address(0) && msg.value != campaign.amount ) { revert InvalidValue(); } if (campaign.rewardToken != address(0) && msg.value != 0) { revert InvalidValue(); } address clonedRewardToken = campaign.rewardToken; uint256 cutAmount = 0; uint256 actualAmount = 0; if (campaign.rewardToken != address(0)) { cutAmount = mulDiv(campaign.amount, sharePercent, 10000); actualAmount = campaign.amount - cutAmount; cutAmount = mulDiv(msg.value, sharePercent, 10000); actualAmount = msg.value - cutAmount; } CampaignInfo memory campaignInfo = CampaignInfo( clonedRewardToken, campaign.collection, msg.sender, actualAmount, campaign.minimumBalance, campaign.startAt, campaign.endAt, campaign.checkNFT ); uint80 taskId = newTaskId; uint80 campaignId = newCampaignId; campaignInfos[campaignId] = campaignInfo; uint80[] memory taskIds = new uint80[](rewardEachTask.length); for (uint80 idx; idx < rewardEachTask.length; ++idx) { if (rewardEachTask[idx] >= campaign.amount) { revert InvalidNumber(); } if (isMultipleClaim[idx] == 1) { multipleClaim[taskId] = 1; } taskToAmountReward[taskId] = rewardEachTask[idx]; taskToCampaignId[taskId] = campaignId; taskIds[idx] = taskId; ++taskId; } newTaskId = taskId; ++newCampaignId; if (clonedRewardToken == address(0)) { if (msg.value != campaign.amount) { revert InvalidInput(); } (bool sent_cut, bytes memory data2) = payable(cutReceiver).call{ value: cutAmount }(""); if (sent_cut == false) { revert SentNativeFailed(); } if (msg.value != 0 ether) { revert NativeNotAllowed(); } IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), address(this), actualAmount ); IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), cutReceiver, cutAmount ); } emit CreateCampaign(campaignId, taskIds); } function createCampaign( CampaignInput calldata campaign, uint256[] calldata rewardEachTask, uint8[] calldata isMultipleClaim ) external payable onlyAdmins nonReentrant { if (rewardEachTask.length != isMultipleClaim.length) { revert InvalidInput(); } if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) { revert InvalidTime(); } if (campaign.collection == address(0)) { if (campaign.checkNFT == 1 || campaign.checkNFT == 2) { revert InvalidAddress(); } } if (campaign.checkNFT > 2) { revert InvalidValue(); } if ( campaign.rewardToken == address(0) && msg.value != campaign.amount ) { revert InvalidValue(); } if (campaign.rewardToken != address(0) && msg.value != 0) { revert InvalidValue(); } address clonedRewardToken = campaign.rewardToken; uint256 cutAmount = 0; uint256 actualAmount = 0; if (campaign.rewardToken != address(0)) { cutAmount = mulDiv(campaign.amount, sharePercent, 10000); actualAmount = campaign.amount - cutAmount; cutAmount = mulDiv(msg.value, sharePercent, 10000); actualAmount = msg.value - cutAmount; } CampaignInfo memory campaignInfo = CampaignInfo( clonedRewardToken, campaign.collection, msg.sender, actualAmount, campaign.minimumBalance, campaign.startAt, campaign.endAt, campaign.checkNFT ); uint80 taskId = newTaskId; uint80 campaignId = newCampaignId; campaignInfos[campaignId] = campaignInfo; uint80[] memory taskIds = new uint80[](rewardEachTask.length); for (uint80 idx; idx < rewardEachTask.length; ++idx) { if (rewardEachTask[idx] >= campaign.amount) { revert InvalidNumber(); } if (isMultipleClaim[idx] == 1) { multipleClaim[taskId] = 1; } taskToAmountReward[taskId] = rewardEachTask[idx]; taskToCampaignId[taskId] = campaignId; taskIds[idx] = taskId; ++taskId; } newTaskId = taskId; ++newCampaignId; if (clonedRewardToken == address(0)) { if (msg.value != campaign.amount) { revert InvalidInput(); } (bool sent_cut, bytes memory data2) = payable(cutReceiver).call{ value: cutAmount }(""); if (sent_cut == false) { revert SentNativeFailed(); } if (msg.value != 0 ether) { revert NativeNotAllowed(); } IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), address(this), actualAmount ); IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), cutReceiver, cutAmount ); } emit CreateCampaign(campaignId, taskIds); } function createCampaign( CampaignInput calldata campaign, uint256[] calldata rewardEachTask, uint8[] calldata isMultipleClaim ) external payable onlyAdmins nonReentrant { if (rewardEachTask.length != isMultipleClaim.length) { revert InvalidInput(); } if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) { revert InvalidTime(); } if (campaign.collection == address(0)) { if (campaign.checkNFT == 1 || campaign.checkNFT == 2) { revert InvalidAddress(); } } if (campaign.checkNFT > 2) { revert InvalidValue(); } if ( campaign.rewardToken == address(0) && msg.value != campaign.amount ) { revert InvalidValue(); } if (campaign.rewardToken != address(0) && msg.value != 0) { revert InvalidValue(); } address clonedRewardToken = campaign.rewardToken; uint256 cutAmount = 0; uint256 actualAmount = 0; if (campaign.rewardToken != address(0)) { cutAmount = mulDiv(campaign.amount, sharePercent, 10000); actualAmount = campaign.amount - cutAmount; cutAmount = mulDiv(msg.value, sharePercent, 10000); actualAmount = msg.value - cutAmount; } CampaignInfo memory campaignInfo = CampaignInfo( clonedRewardToken, campaign.collection, msg.sender, actualAmount, campaign.minimumBalance, campaign.startAt, campaign.endAt, campaign.checkNFT ); uint80 taskId = newTaskId; uint80 campaignId = newCampaignId; campaignInfos[campaignId] = campaignInfo; uint80[] memory taskIds = new uint80[](rewardEachTask.length); for (uint80 idx; idx < rewardEachTask.length; ++idx) { if (rewardEachTask[idx] >= campaign.amount) { revert InvalidNumber(); } if (isMultipleClaim[idx] == 1) { multipleClaim[taskId] = 1; } taskToAmountReward[taskId] = rewardEachTask[idx]; taskToCampaignId[taskId] = campaignId; taskIds[idx] = taskId; ++taskId; } newTaskId = taskId; ++newCampaignId; if (clonedRewardToken == address(0)) { if (msg.value != campaign.amount) { revert InvalidInput(); } (bool sent_cut, bytes memory data2) = payable(cutReceiver).call{ value: cutAmount }(""); if (sent_cut == false) { revert SentNativeFailed(); } if (msg.value != 0 ether) { revert NativeNotAllowed(); } IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), address(this), actualAmount ); IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), cutReceiver, cutAmount ); } emit CreateCampaign(campaignId, taskIds); } function createCampaign( CampaignInput calldata campaign, uint256[] calldata rewardEachTask, uint8[] calldata isMultipleClaim ) external payable onlyAdmins nonReentrant { if (rewardEachTask.length != isMultipleClaim.length) { revert InvalidInput(); } if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) { revert InvalidTime(); } if (campaign.collection == address(0)) { if (campaign.checkNFT == 1 || campaign.checkNFT == 2) { revert InvalidAddress(); } } if (campaign.checkNFT > 2) { revert InvalidValue(); } if ( campaign.rewardToken == address(0) && msg.value != campaign.amount ) { revert InvalidValue(); } if (campaign.rewardToken != address(0) && msg.value != 0) { revert InvalidValue(); } address clonedRewardToken = campaign.rewardToken; uint256 cutAmount = 0; uint256 actualAmount = 0; if (campaign.rewardToken != address(0)) { cutAmount = mulDiv(campaign.amount, sharePercent, 10000); actualAmount = campaign.amount - cutAmount; cutAmount = mulDiv(msg.value, sharePercent, 10000); actualAmount = msg.value - cutAmount; } CampaignInfo memory campaignInfo = CampaignInfo( clonedRewardToken, campaign.collection, msg.sender, actualAmount, campaign.minimumBalance, campaign.startAt, campaign.endAt, campaign.checkNFT ); uint80 taskId = newTaskId; uint80 campaignId = newCampaignId; campaignInfos[campaignId] = campaignInfo; uint80[] memory taskIds = new uint80[](rewardEachTask.length); for (uint80 idx; idx < rewardEachTask.length; ++idx) { if (rewardEachTask[idx] >= campaign.amount) { revert InvalidNumber(); } if (isMultipleClaim[idx] == 1) { multipleClaim[taskId] = 1; } taskToAmountReward[taskId] = rewardEachTask[idx]; taskToCampaignId[taskId] = campaignId; taskIds[idx] = taskId; ++taskId; } newTaskId = taskId; ++newCampaignId; if (clonedRewardToken == address(0)) { if (msg.value != campaign.amount) { revert InvalidInput(); } (bool sent_cut, bytes memory data2) = payable(cutReceiver).call{ value: cutAmount }(""); if (sent_cut == false) { revert SentNativeFailed(); } if (msg.value != 0 ether) { revert NativeNotAllowed(); } IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), address(this), actualAmount ); IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), cutReceiver, cutAmount ); } emit CreateCampaign(campaignId, taskIds); } function createCampaign( CampaignInput calldata campaign, uint256[] calldata rewardEachTask, uint8[] calldata isMultipleClaim ) external payable onlyAdmins nonReentrant { if (rewardEachTask.length != isMultipleClaim.length) { revert InvalidInput(); } if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) { revert InvalidTime(); } if (campaign.collection == address(0)) { if (campaign.checkNFT == 1 || campaign.checkNFT == 2) { revert InvalidAddress(); } } if (campaign.checkNFT > 2) { revert InvalidValue(); } if ( campaign.rewardToken == address(0) && msg.value != campaign.amount ) { revert InvalidValue(); } if (campaign.rewardToken != address(0) && msg.value != 0) { revert InvalidValue(); } address clonedRewardToken = campaign.rewardToken; uint256 cutAmount = 0; uint256 actualAmount = 0; if (campaign.rewardToken != address(0)) { cutAmount = mulDiv(campaign.amount, sharePercent, 10000); actualAmount = campaign.amount - cutAmount; cutAmount = mulDiv(msg.value, sharePercent, 10000); actualAmount = msg.value - cutAmount; } CampaignInfo memory campaignInfo = CampaignInfo( clonedRewardToken, campaign.collection, msg.sender, actualAmount, campaign.minimumBalance, campaign.startAt, campaign.endAt, campaign.checkNFT ); uint80 taskId = newTaskId; uint80 campaignId = newCampaignId; campaignInfos[campaignId] = campaignInfo; uint80[] memory taskIds = new uint80[](rewardEachTask.length); for (uint80 idx; idx < rewardEachTask.length; ++idx) { if (rewardEachTask[idx] >= campaign.amount) { revert InvalidNumber(); } if (isMultipleClaim[idx] == 1) { multipleClaim[taskId] = 1; } taskToAmountReward[taskId] = rewardEachTask[idx]; taskToCampaignId[taskId] = campaignId; taskIds[idx] = taskId; ++taskId; } newTaskId = taskId; ++newCampaignId; if (clonedRewardToken == address(0)) { if (msg.value != campaign.amount) { revert InvalidInput(); } (bool sent_cut, bytes memory data2) = payable(cutReceiver).call{ value: cutAmount }(""); if (sent_cut == false) { revert SentNativeFailed(); } if (msg.value != 0 ether) { revert NativeNotAllowed(); } IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), address(this), actualAmount ); IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), cutReceiver, cutAmount ); } emit CreateCampaign(campaignId, taskIds); } function createCampaign( CampaignInput calldata campaign, uint256[] calldata rewardEachTask, uint8[] calldata isMultipleClaim ) external payable onlyAdmins nonReentrant { if (rewardEachTask.length != isMultipleClaim.length) { revert InvalidInput(); } if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) { revert InvalidTime(); } if (campaign.collection == address(0)) { if (campaign.checkNFT == 1 || campaign.checkNFT == 2) { revert InvalidAddress(); } } if (campaign.checkNFT > 2) { revert InvalidValue(); } if ( campaign.rewardToken == address(0) && msg.value != campaign.amount ) { revert InvalidValue(); } if (campaign.rewardToken != address(0) && msg.value != 0) { revert InvalidValue(); } address clonedRewardToken = campaign.rewardToken; uint256 cutAmount = 0; uint256 actualAmount = 0; if (campaign.rewardToken != address(0)) { cutAmount = mulDiv(campaign.amount, sharePercent, 10000); actualAmount = campaign.amount - cutAmount; cutAmount = mulDiv(msg.value, sharePercent, 10000); actualAmount = msg.value - cutAmount; } CampaignInfo memory campaignInfo = CampaignInfo( clonedRewardToken, campaign.collection, msg.sender, actualAmount, campaign.minimumBalance, campaign.startAt, campaign.endAt, campaign.checkNFT ); uint80 taskId = newTaskId; uint80 campaignId = newCampaignId; campaignInfos[campaignId] = campaignInfo; uint80[] memory taskIds = new uint80[](rewardEachTask.length); for (uint80 idx; idx < rewardEachTask.length; ++idx) { if (rewardEachTask[idx] >= campaign.amount) { revert InvalidNumber(); } if (isMultipleClaim[idx] == 1) { multipleClaim[taskId] = 1; } taskToAmountReward[taskId] = rewardEachTask[idx]; taskToCampaignId[taskId] = campaignId; taskIds[idx] = taskId; ++taskId; } newTaskId = taskId; ++newCampaignId; if (clonedRewardToken == address(0)) { if (msg.value != campaign.amount) { revert InvalidInput(); } (bool sent_cut, bytes memory data2) = payable(cutReceiver).call{ value: cutAmount }(""); if (sent_cut == false) { revert SentNativeFailed(); } if (msg.value != 0 ether) { revert NativeNotAllowed(); } IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), address(this), actualAmount ); IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), cutReceiver, cutAmount ); } emit CreateCampaign(campaignId, taskIds); } function createCampaign( CampaignInput calldata campaign, uint256[] calldata rewardEachTask, uint8[] calldata isMultipleClaim ) external payable onlyAdmins nonReentrant { if (rewardEachTask.length != isMultipleClaim.length) { revert InvalidInput(); } if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) { revert InvalidTime(); } if (campaign.collection == address(0)) { if (campaign.checkNFT == 1 || campaign.checkNFT == 2) { revert InvalidAddress(); } } if (campaign.checkNFT > 2) { revert InvalidValue(); } if ( campaign.rewardToken == address(0) && msg.value != campaign.amount ) { revert InvalidValue(); } if (campaign.rewardToken != address(0) && msg.value != 0) { revert InvalidValue(); } address clonedRewardToken = campaign.rewardToken; uint256 cutAmount = 0; uint256 actualAmount = 0; if (campaign.rewardToken != address(0)) { cutAmount = mulDiv(campaign.amount, sharePercent, 10000); actualAmount = campaign.amount - cutAmount; cutAmount = mulDiv(msg.value, sharePercent, 10000); actualAmount = msg.value - cutAmount; } CampaignInfo memory campaignInfo = CampaignInfo( clonedRewardToken, campaign.collection, msg.sender, actualAmount, campaign.minimumBalance, campaign.startAt, campaign.endAt, campaign.checkNFT ); uint80 taskId = newTaskId; uint80 campaignId = newCampaignId; campaignInfos[campaignId] = campaignInfo; uint80[] memory taskIds = new uint80[](rewardEachTask.length); for (uint80 idx; idx < rewardEachTask.length; ++idx) { if (rewardEachTask[idx] >= campaign.amount) { revert InvalidNumber(); } if (isMultipleClaim[idx] == 1) { multipleClaim[taskId] = 1; } taskToAmountReward[taskId] = rewardEachTask[idx]; taskToCampaignId[taskId] = campaignId; taskIds[idx] = taskId; ++taskId; } newTaskId = taskId; ++newCampaignId; if (clonedRewardToken == address(0)) { if (msg.value != campaign.amount) { revert InvalidInput(); } (bool sent_cut, bytes memory data2) = payable(cutReceiver).call{ value: cutAmount }(""); if (sent_cut == false) { revert SentNativeFailed(); } if (msg.value != 0 ether) { revert NativeNotAllowed(); } IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), address(this), actualAmount ); IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), cutReceiver, cutAmount ); } emit CreateCampaign(campaignId, taskIds); } } else { function createCampaign( CampaignInput calldata campaign, uint256[] calldata rewardEachTask, uint8[] calldata isMultipleClaim ) external payable onlyAdmins nonReentrant { if (rewardEachTask.length != isMultipleClaim.length) { revert InvalidInput(); } if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) { revert InvalidTime(); } if (campaign.collection == address(0)) { if (campaign.checkNFT == 1 || campaign.checkNFT == 2) { revert InvalidAddress(); } } if (campaign.checkNFT > 2) { revert InvalidValue(); } if ( campaign.rewardToken == address(0) && msg.value != campaign.amount ) { revert InvalidValue(); } if (campaign.rewardToken != address(0) && msg.value != 0) { revert InvalidValue(); } address clonedRewardToken = campaign.rewardToken; uint256 cutAmount = 0; uint256 actualAmount = 0; if (campaign.rewardToken != address(0)) { cutAmount = mulDiv(campaign.amount, sharePercent, 10000); actualAmount = campaign.amount - cutAmount; cutAmount = mulDiv(msg.value, sharePercent, 10000); actualAmount = msg.value - cutAmount; } CampaignInfo memory campaignInfo = CampaignInfo( clonedRewardToken, campaign.collection, msg.sender, actualAmount, campaign.minimumBalance, campaign.startAt, campaign.endAt, campaign.checkNFT ); uint80 taskId = newTaskId; uint80 campaignId = newCampaignId; campaignInfos[campaignId] = campaignInfo; uint80[] memory taskIds = new uint80[](rewardEachTask.length); for (uint80 idx; idx < rewardEachTask.length; ++idx) { if (rewardEachTask[idx] >= campaign.amount) { revert InvalidNumber(); } if (isMultipleClaim[idx] == 1) { multipleClaim[taskId] = 1; } taskToAmountReward[taskId] = rewardEachTask[idx]; taskToCampaignId[taskId] = campaignId; taskIds[idx] = taskId; ++taskId; } newTaskId = taskId; ++newCampaignId; if (clonedRewardToken == address(0)) { if (msg.value != campaign.amount) { revert InvalidInput(); } (bool sent_cut, bytes memory data2) = payable(cutReceiver).call{ value: cutAmount }(""); if (sent_cut == false) { revert SentNativeFailed(); } if (msg.value != 0 ether) { revert NativeNotAllowed(); } IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), address(this), actualAmount ); IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), cutReceiver, cutAmount ); } emit CreateCampaign(campaignId, taskIds); } function createCampaign( CampaignInput calldata campaign, uint256[] calldata rewardEachTask, uint8[] calldata isMultipleClaim ) external payable onlyAdmins nonReentrant { if (rewardEachTask.length != isMultipleClaim.length) { revert InvalidInput(); } if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) { revert InvalidTime(); } if (campaign.collection == address(0)) { if (campaign.checkNFT == 1 || campaign.checkNFT == 2) { revert InvalidAddress(); } } if (campaign.checkNFT > 2) { revert InvalidValue(); } if ( campaign.rewardToken == address(0) && msg.value != campaign.amount ) { revert InvalidValue(); } if (campaign.rewardToken != address(0) && msg.value != 0) { revert InvalidValue(); } address clonedRewardToken = campaign.rewardToken; uint256 cutAmount = 0; uint256 actualAmount = 0; if (campaign.rewardToken != address(0)) { cutAmount = mulDiv(campaign.amount, sharePercent, 10000); actualAmount = campaign.amount - cutAmount; cutAmount = mulDiv(msg.value, sharePercent, 10000); actualAmount = msg.value - cutAmount; } CampaignInfo memory campaignInfo = CampaignInfo( clonedRewardToken, campaign.collection, msg.sender, actualAmount, campaign.minimumBalance, campaign.startAt, campaign.endAt, campaign.checkNFT ); uint80 taskId = newTaskId; uint80 campaignId = newCampaignId; campaignInfos[campaignId] = campaignInfo; uint80[] memory taskIds = new uint80[](rewardEachTask.length); for (uint80 idx; idx < rewardEachTask.length; ++idx) { if (rewardEachTask[idx] >= campaign.amount) { revert InvalidNumber(); } if (isMultipleClaim[idx] == 1) { multipleClaim[taskId] = 1; } taskToAmountReward[taskId] = rewardEachTask[idx]; taskToCampaignId[taskId] = campaignId; taskIds[idx] = taskId; ++taskId; } newTaskId = taskId; ++newCampaignId; if (clonedRewardToken == address(0)) { if (msg.value != campaign.amount) { revert InvalidInput(); } (bool sent_cut, bytes memory data2) = payable(cutReceiver).call{ value: cutAmount }(""); if (sent_cut == false) { revert SentNativeFailed(); } if (msg.value != 0 ether) { revert NativeNotAllowed(); } IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), address(this), actualAmount ); IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), cutReceiver, cutAmount ); } emit CreateCampaign(campaignId, taskIds); } function createCampaign( CampaignInput calldata campaign, uint256[] calldata rewardEachTask, uint8[] calldata isMultipleClaim ) external payable onlyAdmins nonReentrant { if (rewardEachTask.length != isMultipleClaim.length) { revert InvalidInput(); } if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) { revert InvalidTime(); } if (campaign.collection == address(0)) { if (campaign.checkNFT == 1 || campaign.checkNFT == 2) { revert InvalidAddress(); } } if (campaign.checkNFT > 2) { revert InvalidValue(); } if ( campaign.rewardToken == address(0) && msg.value != campaign.amount ) { revert InvalidValue(); } if (campaign.rewardToken != address(0) && msg.value != 0) { revert InvalidValue(); } address clonedRewardToken = campaign.rewardToken; uint256 cutAmount = 0; uint256 actualAmount = 0; if (campaign.rewardToken != address(0)) { cutAmount = mulDiv(campaign.amount, sharePercent, 10000); actualAmount = campaign.amount - cutAmount; cutAmount = mulDiv(msg.value, sharePercent, 10000); actualAmount = msg.value - cutAmount; } CampaignInfo memory campaignInfo = CampaignInfo( clonedRewardToken, campaign.collection, msg.sender, actualAmount, campaign.minimumBalance, campaign.startAt, campaign.endAt, campaign.checkNFT ); uint80 taskId = newTaskId; uint80 campaignId = newCampaignId; campaignInfos[campaignId] = campaignInfo; uint80[] memory taskIds = new uint80[](rewardEachTask.length); for (uint80 idx; idx < rewardEachTask.length; ++idx) { if (rewardEachTask[idx] >= campaign.amount) { revert InvalidNumber(); } if (isMultipleClaim[idx] == 1) { multipleClaim[taskId] = 1; } taskToAmountReward[taskId] = rewardEachTask[idx]; taskToCampaignId[taskId] = campaignId; taskIds[idx] = taskId; ++taskId; } newTaskId = taskId; ++newCampaignId; if (clonedRewardToken == address(0)) { if (msg.value != campaign.amount) { revert InvalidInput(); } (bool sent_cut, bytes memory data2) = payable(cutReceiver).call{ value: cutAmount }(""); if (sent_cut == false) { revert SentNativeFailed(); } if (msg.value != 0 ether) { revert NativeNotAllowed(); } IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), address(this), actualAmount ); IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), cutReceiver, cutAmount ); } emit CreateCampaign(campaignId, taskIds); } function createCampaign( CampaignInput calldata campaign, uint256[] calldata rewardEachTask, uint8[] calldata isMultipleClaim ) external payable onlyAdmins nonReentrant { if (rewardEachTask.length != isMultipleClaim.length) { revert InvalidInput(); } if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) { revert InvalidTime(); } if (campaign.collection == address(0)) { if (campaign.checkNFT == 1 || campaign.checkNFT == 2) { revert InvalidAddress(); } } if (campaign.checkNFT > 2) { revert InvalidValue(); } if ( campaign.rewardToken == address(0) && msg.value != campaign.amount ) { revert InvalidValue(); } if (campaign.rewardToken != address(0) && msg.value != 0) { revert InvalidValue(); } address clonedRewardToken = campaign.rewardToken; uint256 cutAmount = 0; uint256 actualAmount = 0; if (campaign.rewardToken != address(0)) { cutAmount = mulDiv(campaign.amount, sharePercent, 10000); actualAmount = campaign.amount - cutAmount; cutAmount = mulDiv(msg.value, sharePercent, 10000); actualAmount = msg.value - cutAmount; } CampaignInfo memory campaignInfo = CampaignInfo( clonedRewardToken, campaign.collection, msg.sender, actualAmount, campaign.minimumBalance, campaign.startAt, campaign.endAt, campaign.checkNFT ); uint80 taskId = newTaskId; uint80 campaignId = newCampaignId; campaignInfos[campaignId] = campaignInfo; uint80[] memory taskIds = new uint80[](rewardEachTask.length); for (uint80 idx; idx < rewardEachTask.length; ++idx) { if (rewardEachTask[idx] >= campaign.amount) { revert InvalidNumber(); } if (isMultipleClaim[idx] == 1) { multipleClaim[taskId] = 1; } taskToAmountReward[taskId] = rewardEachTask[idx]; taskToCampaignId[taskId] = campaignId; taskIds[idx] = taskId; ++taskId; } newTaskId = taskId; ++newCampaignId; if (clonedRewardToken == address(0)) { if (msg.value != campaign.amount) { revert InvalidInput(); } (bool sent_cut, bytes memory data2) = payable(cutReceiver).call{ value: cutAmount }(""); if (sent_cut == false) { revert SentNativeFailed(); } if (msg.value != 0 ether) { revert NativeNotAllowed(); } IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), address(this), actualAmount ); IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), cutReceiver, cutAmount ); } emit CreateCampaign(campaignId, taskIds); } function createCampaign( CampaignInput calldata campaign, uint256[] calldata rewardEachTask, uint8[] calldata isMultipleClaim ) external payable onlyAdmins nonReentrant { if (rewardEachTask.length != isMultipleClaim.length) { revert InvalidInput(); } if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) { revert InvalidTime(); } if (campaign.collection == address(0)) { if (campaign.checkNFT == 1 || campaign.checkNFT == 2) { revert InvalidAddress(); } } if (campaign.checkNFT > 2) { revert InvalidValue(); } if ( campaign.rewardToken == address(0) && msg.value != campaign.amount ) { revert InvalidValue(); } if (campaign.rewardToken != address(0) && msg.value != 0) { revert InvalidValue(); } address clonedRewardToken = campaign.rewardToken; uint256 cutAmount = 0; uint256 actualAmount = 0; if (campaign.rewardToken != address(0)) { cutAmount = mulDiv(campaign.amount, sharePercent, 10000); actualAmount = campaign.amount - cutAmount; cutAmount = mulDiv(msg.value, sharePercent, 10000); actualAmount = msg.value - cutAmount; } CampaignInfo memory campaignInfo = CampaignInfo( clonedRewardToken, campaign.collection, msg.sender, actualAmount, campaign.minimumBalance, campaign.startAt, campaign.endAt, campaign.checkNFT ); uint80 taskId = newTaskId; uint80 campaignId = newCampaignId; campaignInfos[campaignId] = campaignInfo; uint80[] memory taskIds = new uint80[](rewardEachTask.length); for (uint80 idx; idx < rewardEachTask.length; ++idx) { if (rewardEachTask[idx] >= campaign.amount) { revert InvalidNumber(); } if (isMultipleClaim[idx] == 1) { multipleClaim[taskId] = 1; } taskToAmountReward[taskId] = rewardEachTask[idx]; taskToCampaignId[taskId] = campaignId; taskIds[idx] = taskId; ++taskId; } newTaskId = taskId; ++newCampaignId; if (clonedRewardToken == address(0)) { if (msg.value != campaign.amount) { revert InvalidInput(); } (bool sent_cut, bytes memory data2) = payable(cutReceiver).call{ value: cutAmount }(""); if (sent_cut == false) { revert SentNativeFailed(); } if (msg.value != 0 ether) { revert NativeNotAllowed(); } IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), address(this), actualAmount ); IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), cutReceiver, cutAmount ); } emit CreateCampaign(campaignId, taskIds); } function createCampaign( CampaignInput calldata campaign, uint256[] calldata rewardEachTask, uint8[] calldata isMultipleClaim ) external payable onlyAdmins nonReentrant { if (rewardEachTask.length != isMultipleClaim.length) { revert InvalidInput(); } if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) { revert InvalidTime(); } if (campaign.collection == address(0)) { if (campaign.checkNFT == 1 || campaign.checkNFT == 2) { revert InvalidAddress(); } } if (campaign.checkNFT > 2) { revert InvalidValue(); } if ( campaign.rewardToken == address(0) && msg.value != campaign.amount ) { revert InvalidValue(); } if (campaign.rewardToken != address(0) && msg.value != 0) { revert InvalidValue(); } address clonedRewardToken = campaign.rewardToken; uint256 cutAmount = 0; uint256 actualAmount = 0; if (campaign.rewardToken != address(0)) { cutAmount = mulDiv(campaign.amount, sharePercent, 10000); actualAmount = campaign.amount - cutAmount; cutAmount = mulDiv(msg.value, sharePercent, 10000); actualAmount = msg.value - cutAmount; } CampaignInfo memory campaignInfo = CampaignInfo( clonedRewardToken, campaign.collection, msg.sender, actualAmount, campaign.minimumBalance, campaign.startAt, campaign.endAt, campaign.checkNFT ); uint80 taskId = newTaskId; uint80 campaignId = newCampaignId; campaignInfos[campaignId] = campaignInfo; uint80[] memory taskIds = new uint80[](rewardEachTask.length); for (uint80 idx; idx < rewardEachTask.length; ++idx) { if (rewardEachTask[idx] >= campaign.amount) { revert InvalidNumber(); } if (isMultipleClaim[idx] == 1) { multipleClaim[taskId] = 1; } taskToAmountReward[taskId] = rewardEachTask[idx]; taskToCampaignId[taskId] = campaignId; taskIds[idx] = taskId; ++taskId; } newTaskId = taskId; ++newCampaignId; if (clonedRewardToken == address(0)) { if (msg.value != campaign.amount) { revert InvalidInput(); } (bool sent_cut, bytes memory data2) = payable(cutReceiver).call{ value: cutAmount }(""); if (sent_cut == false) { revert SentNativeFailed(); } if (msg.value != 0 ether) { revert NativeNotAllowed(); } IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), address(this), actualAmount ); IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), cutReceiver, cutAmount ); } emit CreateCampaign(campaignId, taskIds); } function createCampaign( CampaignInput calldata campaign, uint256[] calldata rewardEachTask, uint8[] calldata isMultipleClaim ) external payable onlyAdmins nonReentrant { if (rewardEachTask.length != isMultipleClaim.length) { revert InvalidInput(); } if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) { revert InvalidTime(); } if (campaign.collection == address(0)) { if (campaign.checkNFT == 1 || campaign.checkNFT == 2) { revert InvalidAddress(); } } if (campaign.checkNFT > 2) { revert InvalidValue(); } if ( campaign.rewardToken == address(0) && msg.value != campaign.amount ) { revert InvalidValue(); } if (campaign.rewardToken != address(0) && msg.value != 0) { revert InvalidValue(); } address clonedRewardToken = campaign.rewardToken; uint256 cutAmount = 0; uint256 actualAmount = 0; if (campaign.rewardToken != address(0)) { cutAmount = mulDiv(campaign.amount, sharePercent, 10000); actualAmount = campaign.amount - cutAmount; cutAmount = mulDiv(msg.value, sharePercent, 10000); actualAmount = msg.value - cutAmount; } CampaignInfo memory campaignInfo = CampaignInfo( clonedRewardToken, campaign.collection, msg.sender, actualAmount, campaign.minimumBalance, campaign.startAt, campaign.endAt, campaign.checkNFT ); uint80 taskId = newTaskId; uint80 campaignId = newCampaignId; campaignInfos[campaignId] = campaignInfo; uint80[] memory taskIds = new uint80[](rewardEachTask.length); for (uint80 idx; idx < rewardEachTask.length; ++idx) { if (rewardEachTask[idx] >= campaign.amount) { revert InvalidNumber(); } if (isMultipleClaim[idx] == 1) { multipleClaim[taskId] = 1; } taskToAmountReward[taskId] = rewardEachTask[idx]; taskToCampaignId[taskId] = campaignId; taskIds[idx] = taskId; ++taskId; } newTaskId = taskId; ++newCampaignId; if (clonedRewardToken == address(0)) { if (msg.value != campaign.amount) { revert InvalidInput(); } (bool sent_cut, bytes memory data2) = payable(cutReceiver).call{ value: cutAmount }(""); if (sent_cut == false) { revert SentNativeFailed(); } if (msg.value != 0 ether) { revert NativeNotAllowed(); } IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), address(this), actualAmount ); IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), cutReceiver, cutAmount ); } emit CreateCampaign(campaignId, taskIds); } } else { function createCampaign( CampaignInput calldata campaign, uint256[] calldata rewardEachTask, uint8[] calldata isMultipleClaim ) external payable onlyAdmins nonReentrant { if (rewardEachTask.length != isMultipleClaim.length) { revert InvalidInput(); } if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) { revert InvalidTime(); } if (campaign.collection == address(0)) { if (campaign.checkNFT == 1 || campaign.checkNFT == 2) { revert InvalidAddress(); } } if (campaign.checkNFT > 2) { revert InvalidValue(); } if ( campaign.rewardToken == address(0) && msg.value != campaign.amount ) { revert InvalidValue(); } if (campaign.rewardToken != address(0) && msg.value != 0) { revert InvalidValue(); } address clonedRewardToken = campaign.rewardToken; uint256 cutAmount = 0; uint256 actualAmount = 0; if (campaign.rewardToken != address(0)) { cutAmount = mulDiv(campaign.amount, sharePercent, 10000); actualAmount = campaign.amount - cutAmount; cutAmount = mulDiv(msg.value, sharePercent, 10000); actualAmount = msg.value - cutAmount; } CampaignInfo memory campaignInfo = CampaignInfo( clonedRewardToken, campaign.collection, msg.sender, actualAmount, campaign.minimumBalance, campaign.startAt, campaign.endAt, campaign.checkNFT ); uint80 taskId = newTaskId; uint80 campaignId = newCampaignId; campaignInfos[campaignId] = campaignInfo; uint80[] memory taskIds = new uint80[](rewardEachTask.length); for (uint80 idx; idx < rewardEachTask.length; ++idx) { if (rewardEachTask[idx] >= campaign.amount) { revert InvalidNumber(); } if (isMultipleClaim[idx] == 1) { multipleClaim[taskId] = 1; } taskToAmountReward[taskId] = rewardEachTask[idx]; taskToCampaignId[taskId] = campaignId; taskIds[idx] = taskId; ++taskId; } newTaskId = taskId; ++newCampaignId; if (clonedRewardToken == address(0)) { if (msg.value != campaign.amount) { revert InvalidInput(); } (bool sent_cut, bytes memory data2) = payable(cutReceiver).call{ value: cutAmount }(""); if (sent_cut == false) { revert SentNativeFailed(); } if (msg.value != 0 ether) { revert NativeNotAllowed(); } IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), address(this), actualAmount ); IERC20Upgradeable(clonedRewardToken).safeTransferFrom( address(msg.sender), cutReceiver, cutAmount ); } emit CreateCampaign(campaignId, taskIds); } function addTasks( uint80 campaignId, uint256[] calldata rewardEachTask, uint8[] calldata isMultipleClaim ) external onlyAdmins { if (rewardEachTask.length != isMultipleClaim.length) { revert InvalidInput(); } CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.owner != msg.sender) { revert Unauthorized(); } uint80 taskId = newTaskId; uint80[] memory taskIds = new uint80[](rewardEachTask.length); for (uint80 idx; idx < rewardEachTask.length; ++idx) { if (isMultipleClaim[idx] == 1) { multipleClaim[taskId] = 1; } taskToAmountReward[taskId] = rewardEachTask[idx]; taskToCampaignId[taskId] = campaignId; taskIds[idx] = taskId; ++taskId; } newTaskId = taskId; emit AddTasks(campaignId, taskIds); } function addTasks( uint80 campaignId, uint256[] calldata rewardEachTask, uint8[] calldata isMultipleClaim ) external onlyAdmins { if (rewardEachTask.length != isMultipleClaim.length) { revert InvalidInput(); } CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.owner != msg.sender) { revert Unauthorized(); } uint80 taskId = newTaskId; uint80[] memory taskIds = new uint80[](rewardEachTask.length); for (uint80 idx; idx < rewardEachTask.length; ++idx) { if (isMultipleClaim[idx] == 1) { multipleClaim[taskId] = 1; } taskToAmountReward[taskId] = rewardEachTask[idx]; taskToCampaignId[taskId] = campaignId; taskIds[idx] = taskId; ++taskId; } newTaskId = taskId; emit AddTasks(campaignId, taskIds); } function addTasks( uint80 campaignId, uint256[] calldata rewardEachTask, uint8[] calldata isMultipleClaim ) external onlyAdmins { if (rewardEachTask.length != isMultipleClaim.length) { revert InvalidInput(); } CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.owner != msg.sender) { revert Unauthorized(); } uint80 taskId = newTaskId; uint80[] memory taskIds = new uint80[](rewardEachTask.length); for (uint80 idx; idx < rewardEachTask.length; ++idx) { if (isMultipleClaim[idx] == 1) { multipleClaim[taskId] = 1; } taskToAmountReward[taskId] = rewardEachTask[idx]; taskToCampaignId[taskId] = campaignId; taskIds[idx] = taskId; ++taskId; } newTaskId = taskId; emit AddTasks(campaignId, taskIds); } function addTasks( uint80 campaignId, uint256[] calldata rewardEachTask, uint8[] calldata isMultipleClaim ) external onlyAdmins { if (rewardEachTask.length != isMultipleClaim.length) { revert InvalidInput(); } CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.owner != msg.sender) { revert Unauthorized(); } uint80 taskId = newTaskId; uint80[] memory taskIds = new uint80[](rewardEachTask.length); for (uint80 idx; idx < rewardEachTask.length; ++idx) { if (isMultipleClaim[idx] == 1) { multipleClaim[taskId] = 1; } taskToAmountReward[taskId] = rewardEachTask[idx]; taskToCampaignId[taskId] = campaignId; taskIds[idx] = taskId; ++taskId; } newTaskId = taskId; emit AddTasks(campaignId, taskIds); } function addTasks( uint80 campaignId, uint256[] calldata rewardEachTask, uint8[] calldata isMultipleClaim ) external onlyAdmins { if (rewardEachTask.length != isMultipleClaim.length) { revert InvalidInput(); } CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.owner != msg.sender) { revert Unauthorized(); } uint80 taskId = newTaskId; uint80[] memory taskIds = new uint80[](rewardEachTask.length); for (uint80 idx; idx < rewardEachTask.length; ++idx) { if (isMultipleClaim[idx] == 1) { multipleClaim[taskId] = 1; } taskToAmountReward[taskId] = rewardEachTask[idx]; taskToCampaignId[taskId] = campaignId; taskIds[idx] = taskId; ++taskId; } newTaskId = taskId; emit AddTasks(campaignId, taskIds); } function changeCutReceiver( address receiver ) external byOperator nonReentrant { cutReceiver = receiver; emit ChangeCutReceiver(receiver); } function changeSharePercent( uint16 newSharePpercent ) external byOperator nonReentrant { if (newSharePpercent > 10000) { revert InvalidNumber(); } sharePercent = newSharePpercent; emit ChangeSharePercent(newSharePpercent); } function changeSharePercent( uint16 newSharePpercent ) external byOperator nonReentrant { if (newSharePpercent > 10000) { revert InvalidNumber(); } sharePercent = newSharePpercent; emit ChangeSharePercent(newSharePpercent); } function fundCampaign( uint80 campaignId, uint256 amount ) external payable nonReentrant { CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.owner != msg.sender) { revert Unauthorized(); } if (campaign.rewardToken == address(0) && msg.value != amount) { revert InvalidValue(); } if (campaign.rewardToken != address(0) && msg.value != 0) { revert InvalidValue(); } uint256 actualAmount = 0; if (campaign.rewardToken == address(0)) { if (msg.value != amount) { revert InvalidInput(); } uint256 cutAmount = mulDiv(msg.value, sharePercent, 10000); actualAmount = msg.value - cutAmount; campaign.amount = campaign.amount + actualAmount; (bool sent_cut, bytes memory data2) = payable(cutReceiver).call{ value: cutAmount }(""); if (sent_cut == false) { revert SentNativeFailed(); } if (msg.value != 0 ether) { revert NativeNotAllowed(); } uint256 cutAmount = mulDiv(amount, sharePercent, 10000); actualAmount = amount - cutAmount; campaign.amount = campaign.amount + actualAmount; IERC20Upgradeable(campaign.rewardToken).safeTransferFrom( address(msg.sender), address(this), actualAmount ); IERC20Upgradeable(campaign.rewardToken).safeTransferFrom( address(msg.sender), cutReceiver, cutAmount ); } emit FundCampaign(campaignId, actualAmount); } function fundCampaign( uint80 campaignId, uint256 amount ) external payable nonReentrant { CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.owner != msg.sender) { revert Unauthorized(); } if (campaign.rewardToken == address(0) && msg.value != amount) { revert InvalidValue(); } if (campaign.rewardToken != address(0) && msg.value != 0) { revert InvalidValue(); } uint256 actualAmount = 0; if (campaign.rewardToken == address(0)) { if (msg.value != amount) { revert InvalidInput(); } uint256 cutAmount = mulDiv(msg.value, sharePercent, 10000); actualAmount = msg.value - cutAmount; campaign.amount = campaign.amount + actualAmount; (bool sent_cut, bytes memory data2) = payable(cutReceiver).call{ value: cutAmount }(""); if (sent_cut == false) { revert SentNativeFailed(); } if (msg.value != 0 ether) { revert NativeNotAllowed(); } uint256 cutAmount = mulDiv(amount, sharePercent, 10000); actualAmount = amount - cutAmount; campaign.amount = campaign.amount + actualAmount; IERC20Upgradeable(campaign.rewardToken).safeTransferFrom( address(msg.sender), address(this), actualAmount ); IERC20Upgradeable(campaign.rewardToken).safeTransferFrom( address(msg.sender), cutReceiver, cutAmount ); } emit FundCampaign(campaignId, actualAmount); } function fundCampaign( uint80 campaignId, uint256 amount ) external payable nonReentrant { CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.owner != msg.sender) { revert Unauthorized(); } if (campaign.rewardToken == address(0) && msg.value != amount) { revert InvalidValue(); } if (campaign.rewardToken != address(0) && msg.value != 0) { revert InvalidValue(); } uint256 actualAmount = 0; if (campaign.rewardToken == address(0)) { if (msg.value != amount) { revert InvalidInput(); } uint256 cutAmount = mulDiv(msg.value, sharePercent, 10000); actualAmount = msg.value - cutAmount; campaign.amount = campaign.amount + actualAmount; (bool sent_cut, bytes memory data2) = payable(cutReceiver).call{ value: cutAmount }(""); if (sent_cut == false) { revert SentNativeFailed(); } if (msg.value != 0 ether) { revert NativeNotAllowed(); } uint256 cutAmount = mulDiv(amount, sharePercent, 10000); actualAmount = amount - cutAmount; campaign.amount = campaign.amount + actualAmount; IERC20Upgradeable(campaign.rewardToken).safeTransferFrom( address(msg.sender), address(this), actualAmount ); IERC20Upgradeable(campaign.rewardToken).safeTransferFrom( address(msg.sender), cutReceiver, cutAmount ); } emit FundCampaign(campaignId, actualAmount); } function fundCampaign( uint80 campaignId, uint256 amount ) external payable nonReentrant { CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.owner != msg.sender) { revert Unauthorized(); } if (campaign.rewardToken == address(0) && msg.value != amount) { revert InvalidValue(); } if (campaign.rewardToken != address(0) && msg.value != 0) { revert InvalidValue(); } uint256 actualAmount = 0; if (campaign.rewardToken == address(0)) { if (msg.value != amount) { revert InvalidInput(); } uint256 cutAmount = mulDiv(msg.value, sharePercent, 10000); actualAmount = msg.value - cutAmount; campaign.amount = campaign.amount + actualAmount; (bool sent_cut, bytes memory data2) = payable(cutReceiver).call{ value: cutAmount }(""); if (sent_cut == false) { revert SentNativeFailed(); } if (msg.value != 0 ether) { revert NativeNotAllowed(); } uint256 cutAmount = mulDiv(amount, sharePercent, 10000); actualAmount = amount - cutAmount; campaign.amount = campaign.amount + actualAmount; IERC20Upgradeable(campaign.rewardToken).safeTransferFrom( address(msg.sender), address(this), actualAmount ); IERC20Upgradeable(campaign.rewardToken).safeTransferFrom( address(msg.sender), cutReceiver, cutAmount ); } emit FundCampaign(campaignId, actualAmount); } function fundCampaign( uint80 campaignId, uint256 amount ) external payable nonReentrant { CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.owner != msg.sender) { revert Unauthorized(); } if (campaign.rewardToken == address(0) && msg.value != amount) { revert InvalidValue(); } if (campaign.rewardToken != address(0) && msg.value != 0) { revert InvalidValue(); } uint256 actualAmount = 0; if (campaign.rewardToken == address(0)) { if (msg.value != amount) { revert InvalidInput(); } uint256 cutAmount = mulDiv(msg.value, sharePercent, 10000); actualAmount = msg.value - cutAmount; campaign.amount = campaign.amount + actualAmount; (bool sent_cut, bytes memory data2) = payable(cutReceiver).call{ value: cutAmount }(""); if (sent_cut == false) { revert SentNativeFailed(); } if (msg.value != 0 ether) { revert NativeNotAllowed(); } uint256 cutAmount = mulDiv(amount, sharePercent, 10000); actualAmount = amount - cutAmount; campaign.amount = campaign.amount + actualAmount; IERC20Upgradeable(campaign.rewardToken).safeTransferFrom( address(msg.sender), address(this), actualAmount ); IERC20Upgradeable(campaign.rewardToken).safeTransferFrom( address(msg.sender), cutReceiver, cutAmount ); } emit FundCampaign(campaignId, actualAmount); } function fundCampaign( uint80 campaignId, uint256 amount ) external payable nonReentrant { CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.owner != msg.sender) { revert Unauthorized(); } if (campaign.rewardToken == address(0) && msg.value != amount) { revert InvalidValue(); } if (campaign.rewardToken != address(0) && msg.value != 0) { revert InvalidValue(); } uint256 actualAmount = 0; if (campaign.rewardToken == address(0)) { if (msg.value != amount) { revert InvalidInput(); } uint256 cutAmount = mulDiv(msg.value, sharePercent, 10000); actualAmount = msg.value - cutAmount; campaign.amount = campaign.amount + actualAmount; (bool sent_cut, bytes memory data2) = payable(cutReceiver).call{ value: cutAmount }(""); if (sent_cut == false) { revert SentNativeFailed(); } if (msg.value != 0 ether) { revert NativeNotAllowed(); } uint256 cutAmount = mulDiv(amount, sharePercent, 10000); actualAmount = amount - cutAmount; campaign.amount = campaign.amount + actualAmount; IERC20Upgradeable(campaign.rewardToken).safeTransferFrom( address(msg.sender), address(this), actualAmount ); IERC20Upgradeable(campaign.rewardToken).safeTransferFrom( address(msg.sender), cutReceiver, cutAmount ); } emit FundCampaign(campaignId, actualAmount); } function fundCampaign( uint80 campaignId, uint256 amount ) external payable nonReentrant { CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.owner != msg.sender) { revert Unauthorized(); } if (campaign.rewardToken == address(0) && msg.value != amount) { revert InvalidValue(); } if (campaign.rewardToken != address(0) && msg.value != 0) { revert InvalidValue(); } uint256 actualAmount = 0; if (campaign.rewardToken == address(0)) { if (msg.value != amount) { revert InvalidInput(); } uint256 cutAmount = mulDiv(msg.value, sharePercent, 10000); actualAmount = msg.value - cutAmount; campaign.amount = campaign.amount + actualAmount; (bool sent_cut, bytes memory data2) = payable(cutReceiver).call{ value: cutAmount }(""); if (sent_cut == false) { revert SentNativeFailed(); } if (msg.value != 0 ether) { revert NativeNotAllowed(); } uint256 cutAmount = mulDiv(amount, sharePercent, 10000); actualAmount = amount - cutAmount; campaign.amount = campaign.amount + actualAmount; IERC20Upgradeable(campaign.rewardToken).safeTransferFrom( address(msg.sender), address(this), actualAmount ); IERC20Upgradeable(campaign.rewardToken).safeTransferFrom( address(msg.sender), cutReceiver, cutAmount ); } emit FundCampaign(campaignId, actualAmount); } function fundCampaign( uint80 campaignId, uint256 amount ) external payable nonReentrant { CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.owner != msg.sender) { revert Unauthorized(); } if (campaign.rewardToken == address(0) && msg.value != amount) { revert InvalidValue(); } if (campaign.rewardToken != address(0) && msg.value != 0) { revert InvalidValue(); } uint256 actualAmount = 0; if (campaign.rewardToken == address(0)) { if (msg.value != amount) { revert InvalidInput(); } uint256 cutAmount = mulDiv(msg.value, sharePercent, 10000); actualAmount = msg.value - cutAmount; campaign.amount = campaign.amount + actualAmount; (bool sent_cut, bytes memory data2) = payable(cutReceiver).call{ value: cutAmount }(""); if (sent_cut == false) { revert SentNativeFailed(); } if (msg.value != 0 ether) { revert NativeNotAllowed(); } uint256 cutAmount = mulDiv(amount, sharePercent, 10000); actualAmount = amount - cutAmount; campaign.amount = campaign.amount + actualAmount; IERC20Upgradeable(campaign.rewardToken).safeTransferFrom( address(msg.sender), address(this), actualAmount ); IERC20Upgradeable(campaign.rewardToken).safeTransferFrom( address(msg.sender), cutReceiver, cutAmount ); } emit FundCampaign(campaignId, actualAmount); } } else { function fundCampaign( uint80 campaignId, uint256 amount ) external payable nonReentrant { CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.owner != msg.sender) { revert Unauthorized(); } if (campaign.rewardToken == address(0) && msg.value != amount) { revert InvalidValue(); } if (campaign.rewardToken != address(0) && msg.value != 0) { revert InvalidValue(); } uint256 actualAmount = 0; if (campaign.rewardToken == address(0)) { if (msg.value != amount) { revert InvalidInput(); } uint256 cutAmount = mulDiv(msg.value, sharePercent, 10000); actualAmount = msg.value - cutAmount; campaign.amount = campaign.amount + actualAmount; (bool sent_cut, bytes memory data2) = payable(cutReceiver).call{ value: cutAmount }(""); if (sent_cut == false) { revert SentNativeFailed(); } if (msg.value != 0 ether) { revert NativeNotAllowed(); } uint256 cutAmount = mulDiv(amount, sharePercent, 10000); actualAmount = amount - cutAmount; campaign.amount = campaign.amount + actualAmount; IERC20Upgradeable(campaign.rewardToken).safeTransferFrom( address(msg.sender), address(this), actualAmount ); IERC20Upgradeable(campaign.rewardToken).safeTransferFrom( address(msg.sender), cutReceiver, cutAmount ); } emit FundCampaign(campaignId, actualAmount); } function withdrawFundCampaign( uint80 campaignId, uint256 amount, bytes calldata signature ) external nonReentrant { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, signature) == false) { revert InvalidSignature(); } CampaignInfo storage campaign = campaignInfos[campaignId]; if (amount > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - amount; if (campaign.owner != msg.sender) { revert Unauthorized(); } if (campaign.rewardToken == address(0)) { (bool sent, bytes memory data) = payable(msg.sender).call{ value: amount }(""); if (sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(campaign.rewardToken).safeTransfer( address(msg.sender), amount ); } emit WithdrawFundCampaign(campaignId, amount); } function withdrawFundCampaign( uint80 campaignId, uint256 amount, bytes calldata signature ) external nonReentrant { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, signature) == false) { revert InvalidSignature(); } CampaignInfo storage campaign = campaignInfos[campaignId]; if (amount > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - amount; if (campaign.owner != msg.sender) { revert Unauthorized(); } if (campaign.rewardToken == address(0)) { (bool sent, bytes memory data) = payable(msg.sender).call{ value: amount }(""); if (sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(campaign.rewardToken).safeTransfer( address(msg.sender), amount ); } emit WithdrawFundCampaign(campaignId, amount); } function withdrawFundCampaign( uint80 campaignId, uint256 amount, bytes calldata signature ) external nonReentrant { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, signature) == false) { revert InvalidSignature(); } CampaignInfo storage campaign = campaignInfos[campaignId]; if (amount > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - amount; if (campaign.owner != msg.sender) { revert Unauthorized(); } if (campaign.rewardToken == address(0)) { (bool sent, bytes memory data) = payable(msg.sender).call{ value: amount }(""); if (sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(campaign.rewardToken).safeTransfer( address(msg.sender), amount ); } emit WithdrawFundCampaign(campaignId, amount); } function withdrawFundCampaign( uint80 campaignId, uint256 amount, bytes calldata signature ) external nonReentrant { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, signature) == false) { revert InvalidSignature(); } CampaignInfo storage campaign = campaignInfos[campaignId]; if (amount > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - amount; if (campaign.owner != msg.sender) { revert Unauthorized(); } if (campaign.rewardToken == address(0)) { (bool sent, bytes memory data) = payable(msg.sender).call{ value: amount }(""); if (sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(campaign.rewardToken).safeTransfer( address(msg.sender), amount ); } emit WithdrawFundCampaign(campaignId, amount); } function withdrawFundCampaign( uint80 campaignId, uint256 amount, bytes calldata signature ) external nonReentrant { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, signature) == false) { revert InvalidSignature(); } CampaignInfo storage campaign = campaignInfos[campaignId]; if (amount > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - amount; if (campaign.owner != msg.sender) { revert Unauthorized(); } if (campaign.rewardToken == address(0)) { (bool sent, bytes memory data) = payable(msg.sender).call{ value: amount }(""); if (sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(campaign.rewardToken).safeTransfer( address(msg.sender), amount ); } emit WithdrawFundCampaign(campaignId, amount); } function withdrawFundCampaign( uint80 campaignId, uint256 amount, bytes calldata signature ) external nonReentrant { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, signature) == false) { revert InvalidSignature(); } CampaignInfo storage campaign = campaignInfos[campaignId]; if (amount > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - amount; if (campaign.owner != msg.sender) { revert Unauthorized(); } if (campaign.rewardToken == address(0)) { (bool sent, bytes memory data) = payable(msg.sender).call{ value: amount }(""); if (sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(campaign.rewardToken).safeTransfer( address(msg.sender), amount ); } emit WithdrawFundCampaign(campaignId, amount); } function withdrawFundCampaign( uint80 campaignId, uint256 amount, bytes calldata signature ) external nonReentrant { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, signature) == false) { revert InvalidSignature(); } CampaignInfo storage campaign = campaignInfos[campaignId]; if (amount > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - amount; if (campaign.owner != msg.sender) { revert Unauthorized(); } if (campaign.rewardToken == address(0)) { (bool sent, bytes memory data) = payable(msg.sender).call{ value: amount }(""); if (sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(campaign.rewardToken).safeTransfer( address(msg.sender), amount ); } emit WithdrawFundCampaign(campaignId, amount); } } else { function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } uint256[] memory accRewardPerToken = new uint256[](claimInput.taskIds.length); function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } } else { function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } } else { function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } } else { function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } } else { } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } } else { } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } } else { function claimReward( ClaimInput calldata claimInput ) external nonReentrant payable { bytes32 messageHash = getMessageHash(_msgSender()); if (verifySignature(messageHash, claimInput.signature) == false) { revert InvalidSignature(); } if (claimInput.taskIds.length != claimInput.isValidUser.length) { revert InvalidInput(); } address[] memory addressPerToken = new address[](claimInput.taskIds.length); uint8 count = 0; uint8 counter = 0; uint8 checkClaimCookie = 0; uint256 reward; for (uint256 idx; idx < claimInput.taskIds.length; ++idx) { uint80[] memory tasksPerCampaign = claimInput.taskIds[idx]; uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]]; CampaignInfo storage campaign = campaignInfos[campaignId]; if (campaign.rewardToken == cookieToken) { checkClaimCookie = 1; } if (claimInput.isValidUser[idx] == 0) { uint256 nftBalance; uint256 balance = IERC20Upgradeable(chappyToken).balanceOf( msg.sender ); uint256 check = 0; if (campaign.checkNFT == 2) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance > 0 || balance > 0) { check += 1; } if (check == 0) { revert InvalidEligibility(campaignId); } } if (campaign.checkNFT == 1) { nftBalance = IERC721Upgradeable(campaign.collection) .balanceOf(msg.sender); if (nftBalance == 0) { revert InsufficentChappyNFT(campaignId); } if (balance < campaign.minimumBalance) { revert InsufficentChappy(campaignId); } } } if (campaign.startAt > block.timestamp) { revert UnavailableCampaign(campaignId); } reward = 0; for (uint80 id; id < tasksPerCampaign.length; ++id) { uint80 taskId = tasksPerCampaign[id]; if (taskToCampaignId[taskId] != campaignId) { revert TaskNotInCampaign(taskId, campaignId); } if ( claimedTasks[taskId][msg.sender] == 1 && multipleClaim[taskId] != 1 ) { revert ClaimedTask(taskId); } claimedTasks[taskId][msg.sender] = 1; if (multipleClaim[taskId] == 1) { uint80 userPoint = claimInput.pointForMultiple[counter][0]; uint80 totalPoint = claimInput.pointForMultiple[counter][1]; if (totalPoint == 0) { revert InvalidPoint(); } reward += taskToAmountReward[taskId] * userPoint / totalPoint; ++counter; reward += taskToAmountReward[taskId]; } } if (reward > campaign.amount) { revert InsufficentFund(campaignId); } campaign.amount = campaign.amount - reward; if (count == 0) { accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; if (addressPerToken[count-1] == addressPerToken[count]) { accRewardPerToken[count-1] += reward; accRewardPerToken[count] = reward; addressPerToken[count] = campaign.rewardToken; count++; } } for (uint idx = 0; idx < addressPerToken.length; ++idx) { if (addressPerToken[idx] == address(0)) { (bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{ value: accRewardPerToken[idx] }(""); if (reward_sent == false) { revert SentNativeFailed(); } IERC20Upgradeable(addressPerToken[idx]).safeTransfer( address(msg.sender), accRewardPerToken[idx] ); } if (checkClaimCookie == 1) { ( int answer, ) = dataFeed.latestRoundData(); if (answer == 0) { revert InvalidPriceFeed(); } int fourDollarInNative = (4 * 1e8 * 1e18)/answer; if (msg.value < uint256(fourDollarInNative)) { revert InvalidFee(); } (bool sent, bytes memory data) = payable(cutReceiver).call{ value: uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } (bool sent_back, bytes memory data_back) = payable(msg.sender).call{ value: msg.value - uint256(fourDollarInNative) }(""); if (sent == false) { revert SentNativeFailed(); } if (msg.value != 0) { revert NativeNotAllowed(); } } emit ClaimReward(claimInput.taskIds); } function changeOracle(address newDataFeed) external { dataFeed = AggregatorV3Interface( newDataFeed ); } function checkOperator(address operator) external view returns (uint8) { return isOperator[operator]; } function getCookieAddress() external view returns (address) { return cookieToken; } function getNonce() external view returns (uint72) { return nonce; } function getCampaignInfo( uint80 campaignId ) external view returns (CampaignInfo memory) { return campaignInfos[campaignId]; } function getTaskInCampaign(uint80 taskId) external view returns (uint80) { return taskToCampaignId[taskId]; } function checkClaimedTasks( uint80[] calldata taskIds, address[] memory users ) external view returns (uint80[] memory) { if (taskIds.length != users.length) { revert InvalidInput(); } uint80[] memory checkIndex = new uint80[](users.length); for (uint256 idx; idx < taskIds.length; ++idx) { uint80 taskId = taskIds[idx]; if (claimedTasks[taskId][users[idx]] == 1) { checkIndex[idx] = 1; checkIndex[idx] = 0; } } return checkIndex; } function checkClaimedTasks( uint80[] calldata taskIds, address[] memory users ) external view returns (uint80[] memory) { if (taskIds.length != users.length) { revert InvalidInput(); } uint80[] memory checkIndex = new uint80[](users.length); for (uint256 idx; idx < taskIds.length; ++idx) { uint80 taskId = taskIds[idx]; if (claimedTasks[taskId][users[idx]] == 1) { checkIndex[idx] = 1; checkIndex[idx] = 0; } } return checkIndex; } function checkClaimedTasks( uint80[] calldata taskIds, address[] memory users ) external view returns (uint80[] memory) { if (taskIds.length != users.length) { revert InvalidInput(); } uint80[] memory checkIndex = new uint80[](users.length); for (uint256 idx; idx < taskIds.length; ++idx) { uint80 taskId = taskIds[idx]; if (claimedTasks[taskId][users[idx]] == 1) { checkIndex[idx] = 1; checkIndex[idx] = 0; } } return checkIndex; } function checkClaimedTasks( uint80[] calldata taskIds, address[] memory users ) external view returns (uint80[] memory) { if (taskIds.length != users.length) { revert InvalidInput(); } uint80[] memory checkIndex = new uint80[](users.length); for (uint256 idx; idx < taskIds.length; ++idx) { uint80 taskId = taskIds[idx]; if (claimedTasks[taskId][users[idx]] == 1) { checkIndex[idx] = 1; checkIndex[idx] = 0; } } return checkIndex; } } else { function getMessageHash(address user) private view returns (bytes32) { return keccak256(abi.encodePacked(nonce, user)); } function verifySignature( bytes32 messageHash, bytes calldata signature ) private returns (bool) { ++nonce; bytes32 ethSignedMessageHash = ECDSAUpgradeable.toEthSignedMessageHash( messageHash ); address signer = getSignerAddress(ethSignedMessageHash, signature); return isOperator[signer] == 1; } function getSignerAddress( bytes32 messageHash, bytes calldata signature ) private pure returns (address) { return ECDSAUpgradeable.recover(messageHash, signature); } function mulDiv( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 result) { unchecked { assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } if (prod1 == 0) { return prod0 / denominator; } assembly { remainder := mulmod(x, y, denominator) prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } assembly { denominator := div(denominator, twos) prod0 := div(prod0, twos) twos := add(div(sub(0, twos), twos), 1) } return result; } } function mulDiv( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 result) { unchecked { assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } if (prod1 == 0) { return prod0 / denominator; } assembly { remainder := mulmod(x, y, denominator) prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } assembly { denominator := div(denominator, twos) prod0 := div(prod0, twos) twos := add(div(sub(0, twos), twos), 1) } return result; } } function mulDiv( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 result) { unchecked { assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } if (prod1 == 0) { return prod0 / denominator; } assembly { remainder := mulmod(x, y, denominator) prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } assembly { denominator := div(denominator, twos) prod0 := div(prod0, twos) twos := add(div(sub(0, twos), twos), 1) } return result; } } function mulDiv( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 result) { unchecked { assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } if (prod1 == 0) { return prod0 / denominator; } assembly { remainder := mulmod(x, y, denominator) prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } assembly { denominator := div(denominator, twos) prod0 := div(prod0, twos) twos := add(div(sub(0, twos), twos), 1) } return result; } } require(denominator > prod1); uint256 remainder; function mulDiv( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 result) { unchecked { assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } if (prod1 == 0) { return prod0 / denominator; } assembly { remainder := mulmod(x, y, denominator) prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } assembly { denominator := div(denominator, twos) prod0 := div(prod0, twos) twos := add(div(sub(0, twos), twos), 1) } return result; } } uint256 twos = denominator & (~denominator + 1); function mulDiv( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 result) { unchecked { assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } if (prod1 == 0) { return prod0 / denominator; } assembly { remainder := mulmod(x, y, denominator) prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } assembly { denominator := div(denominator, twos) prod0 := div(prod0, twos) twos := add(div(sub(0, twos), twos), 1) } return result; } } prod0 |= prod1 * twos; uint256 inverse = (3 * denominator) ^ 2; result = prod0 * inverse; }
3,033,899
[ 1, 14608, 67, 350, 1562, 67, 350, 317, 19890, 1801, 1562, 67, 350, 317, 8965, 67, 350, 1562, 67, 350, 16, 729, 1758, 317, 7516, 329, 1562, 67, 350, 317, 353, 8438, 9762, 329, 1758, 317, 1250, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 95, 203, 565, 1450, 14060, 654, 39, 3462, 10784, 429, 364, 467, 654, 39, 3462, 10784, 429, 31, 203, 565, 2874, 12, 11890, 3672, 516, 17820, 966, 13, 3238, 8965, 7655, 31, 203, 565, 2874, 12, 11890, 3672, 516, 2254, 5034, 13, 3238, 1562, 774, 6275, 17631, 1060, 31, 203, 565, 2874, 12, 11890, 3672, 516, 2254, 3672, 13, 3238, 1562, 774, 13432, 548, 31, 203, 565, 2874, 12, 11890, 3672, 516, 2874, 12, 2867, 516, 2254, 28, 3719, 3238, 7516, 329, 6685, 31, 203, 565, 2874, 12, 11890, 3672, 516, 2254, 28, 13, 3238, 3229, 9762, 31, 203, 565, 2874, 12, 2867, 516, 2254, 28, 13, 3238, 353, 5592, 31, 203, 203, 565, 10594, 639, 58, 23, 1358, 2713, 501, 8141, 31, 203, 565, 1758, 3238, 462, 438, 2074, 1345, 31, 203, 565, 1758, 3238, 3878, 1345, 31, 203, 565, 1758, 3238, 6391, 12952, 31, 203, 565, 1758, 8526, 3238, 31116, 31, 203, 565, 2254, 3672, 3238, 394, 13432, 548, 31, 203, 565, 2254, 3672, 3238, 394, 30182, 31, 203, 565, 2254, 9060, 3238, 7448, 31, 203, 203, 565, 555, 1962, 5374, 5621, 203, 565, 555, 22085, 3809, 335, 319, 782, 438, 2074, 12, 11890, 3672, 1769, 203, 565, 555, 22085, 3809, 335, 319, 782, 438, 2074, 50, 4464, 12, 11890, 3672, 1769, 203, 565, 555, 1351, 5699, 13432, 12, 11890, 3672, 1769, 203, 565, 555, 3837, 21855, 13432, 12, 11890, 3672, 16, 2254, 3672, 1769, 203, 565, 555, 18381, 329, 2174, 12, 11890, 3672, 1769, 203, 565, 555, 22085, 3809, 335, 319, 2 ]
pragma solidity ^0.4.24; /** * Libraries **/ library ExtendedMath { function limitLessThan(uint a, uint b) internal pure returns(uint c) { if (a > b) return b; return a; } } library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns(uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns(uint256) { require(_b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns(uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns(uint256) { uint256 c = _a + _b; require(c >= _a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns(uint256) { require(b != 0); return a % b; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } 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); } contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns(uint256); function transferFrom(address _from, address _to, uint256 _value) public returns(bool); function approve(address _spender, uint256 _value) public returns(bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns(uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns(bool) { //require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns(uint256) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping(address => mapping(address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns(bool) { //require(_value <= balances[_from]); //require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns(bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns(uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns(bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns(bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } interface IRemoteFunctions { function _externalAddMasternode(address) external; function _externalStopMasternode(address) external; } interface IcaelumVoting { function getTokenProposalDetails() external view returns(address, uint, uint, uint); function getExpiry() external view returns (uint); function getContractType () external view returns (uint); } interface EIP918Interface { /* * Externally facing mint function that is called by miners to validate challenge digests, calculate reward, * populate statistics, mutate epoch variables and adjust the solution difficulty as required. Once complete, * a Mint event is emitted before returning a success indicator. **/ function mint(uint256 nonce, bytes32 challenge_digest) external returns (bool success); /* * Returns the challenge number **/ function getChallengeNumber() external constant returns (bytes32); /* * Returns the mining difficulty. The number of digits that the digest of the PoW solution requires which * typically auto adjusts during reward generation. **/ function getMiningDifficulty() external constant returns (uint); /* * Returns the mining target **/ function getMiningTarget() external constant returns (uint); /* * Return the current reward amount. Depending on the algorithm, typically rewards are divided every reward era * as tokens are mined to provide scarcity **/ function getMiningReward() external constant returns (uint); /* * Upon successful verification and reward the mint method dispatches a Mint Event indicating the reward address, * the reward amount, the epoch count and newest challenge number. **/ event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); } contract NewMinerProposal is IcaelumVoting { enum VOTE_TYPE {MINER, MASTER, TOKEN} VOTE_TYPE public contractType = VOTE_TYPE.TOKEN; address contractAddress; uint validUntil; uint votingDurationInDays; /** * @dev Create a new vote proposal for an ERC20 token. * @param _contract ERC20 contract * @param _valid How long do we accept these tokens on the contract (UNIX timestamp) * @param _voteDuration How many days is this vote available */ constructor(address _contract, uint _valid, uint _voteDuration) public { require(_voteDuration >= 14 && _voteDuration <= 50, "Proposed voting duration does not meet requirements"); contractAddress = _contract; validUntil = _valid; votingDurationInDays = _voteDuration; } /** * @dev Returns all details about this proposal */ function getTokenProposalDetails() public view returns(address, uint, uint, uint) { return (contractAddress, 0, validUntil, uint(contractType)); } /** * @dev Displays the expiry date of contract * @return uint Days valid */ function getExpiry() external view returns (uint) { return votingDurationInDays; } /** * @dev Displays the type of contract * @return uint Enum value {TOKEN, TEAM} */ function getContractType () external view returns (uint){ return uint(contractType); } } contract CaelumVotings is Ownable { using SafeMath for uint; enum VOTE_TYPE {MINER, MASTER, TOKEN} struct Proposals { address tokenContract; uint totalVotes; uint proposedOn; uint acceptedOn; VOTE_TYPE proposalType; } struct Voters { bool isVoter; address owner; uint[] votedFor; } uint MAJORITY_PERCENTAGE_NEEDED = 60; uint MINIMUM_VOTERS_NEEDED = 1; bool public proposalPending; mapping(uint => Proposals) public proposalList; mapping (address => Voters) public voterMap; mapping(uint => address) public voterProposals; uint public proposalCounter; uint public votersCount; uint public votersCountTeam; function setMasternodeContractFromVote(address _t) internal ; function setTokenContractFromVote(address _t) internal; function setMiningContractFromVote (address _t) internal; event NewProposal(uint ProposalID); event ProposalAccepted(uint ProposalID); address _CaelumMasternodeContract; CaelumMasternode public MasternodeContract; function setMasternodeContractForData(address _t) onlyOwner public { MasternodeContract = CaelumMasternode(_t); _CaelumMasternodeContract = (_t); } function setVotingMinority(uint _total) onlyOwner public { require(_total > MINIMUM_VOTERS_NEEDED); MINIMUM_VOTERS_NEEDED = _total; } /** * @dev Create a new proposal. * @param _contract Proposal contract address * @return uint ProposalID */ function pushProposal(address _contract) onlyOwner public returns (uint) { if(proposalCounter != 0) require (pastProposalTimeRules (), "You need to wait 90 days before submitting a new proposal."); require (!proposalPending, "Another proposal is pending."); uint _contractType = IcaelumVoting(_contract).getContractType(); proposalList[proposalCounter] = Proposals(_contract, 0, now, 0, VOTE_TYPE(_contractType)); emit NewProposal(proposalCounter); proposalCounter++; proposalPending = true; return proposalCounter.sub(1); } /** * @dev Internal function that handles the proposal after it got accepted. * This function determines if the proposal is a token or team member proposal and executes the corresponding functions. * @return uint Returns the proposal ID. */ function handleLastProposal () internal returns (uint) { uint _ID = proposalCounter.sub(1); proposalList[_ID].acceptedOn = now; proposalPending = false; address _address; uint _required; uint _valid; uint _type; (_address, _required, _valid, _type) = getTokenProposalDetails(_ID); if(_type == uint(VOTE_TYPE.MINER)) { setMiningContractFromVote(_address); } if(_type == uint(VOTE_TYPE.MASTER)) { setMasternodeContractFromVote(_address); } if(_type == uint(VOTE_TYPE.TOKEN)) { setTokenContractFromVote(_address); } emit ProposalAccepted(_ID); return _ID; } /** * @dev Rejects the last proposal after the allowed voting time has expired and it's not accepted. */ function discardRejectedProposal() onlyOwner public returns (bool) { require(proposalPending); require (LastProposalCanDiscard()); proposalPending = false; return (true); } /** * @dev Checks if the last proposal allowed voting time has expired and it's not accepted. * @return bool */ function LastProposalCanDiscard () public view returns (bool) { uint daysBeforeDiscard = IcaelumVoting(proposalList[proposalCounter - 1].tokenContract).getExpiry(); uint entryDate = proposalList[proposalCounter - 1].proposedOn; uint expiryDate = entryDate + (daysBeforeDiscard * 1 days); if (now >= expiryDate) return true; } /** * @dev Returns all details about a proposal */ function getTokenProposalDetails(uint proposalID) public view returns(address, uint, uint, uint) { return IcaelumVoting(proposalList[proposalID].tokenContract).getTokenProposalDetails(); } /** * @dev Returns if our 90 day cooldown has passed * @return bool */ function pastProposalTimeRules() public view returns (bool) { uint lastProposal = proposalList[proposalCounter - 1].proposedOn; if (now >= lastProposal + 90 days) return true; } /** * @dev Allow any masternode user to become a voter. */ function becomeVoter() public { require (MasternodeContract.isMasternodeOwner(msg.sender), "User has no masternodes"); require (!voterMap[msg.sender].isVoter, "User Already voted for this proposal"); voterMap[msg.sender].owner = msg.sender; voterMap[msg.sender].isVoter = true; votersCount = votersCount + 1; if (MasternodeContract.isTeamMember(msg.sender)) votersCountTeam = votersCountTeam + 1; } /** * @dev Allow voters to submit their vote on a proposal. Voters can only cast 1 vote per proposal. * If the proposed vote is about adding Team members, only Team members are able to vote. * A proposal can only be published if the total of votes is greater then MINIMUM_VOTERS_NEEDED. * @param proposalID proposalID */ function voteProposal(uint proposalID) public returns (bool success) { require(voterMap[msg.sender].isVoter, "Sender not listed as voter"); require(proposalID >= 0, "No proposal was selected."); require(proposalID <= proposalCounter, "Proposal out of limits."); require(voterProposals[proposalID] != msg.sender, "Already voted."); require(votersCount >= MINIMUM_VOTERS_NEEDED, "Not enough voters in existence to push a proposal"); voterProposals[proposalID] = msg.sender; proposalList[proposalID].totalVotes++; if(reachedMajority(proposalID)) { // This is the prefered way of handling vote results. It costs more gas but prevents tampering. // If gas is an issue, you can comment handleLastProposal out and call it manually as onlyOwner. handleLastProposal(); return true; } } /** * @dev Check if a proposal has reached the majority vote * @param proposalID Token ID * @return bool */ function reachedMajority (uint proposalID) public view returns (bool) { uint getProposalVotes = proposalList[proposalID].totalVotes; if (getProposalVotes >= majority()) return true; } /** * @dev Internal function that calculates the majority * @return uint Total of votes needed for majority */ function majority () internal view returns (uint) { uint a = (votersCount * MAJORITY_PERCENTAGE_NEEDED ); return a / 100; } /** * @dev Check if a proposal has reached the majority vote for a team member * @param proposalID Token ID * @return bool */ function reachedMajorityForTeam (uint proposalID) public view returns (bool) { uint getProposalVotes = proposalList[proposalID].totalVotes; if (getProposalVotes >= majorityForTeam()) return true; } /** * @dev Internal function that calculates the majority * @return uint Total of votes needed for majority */ function majorityForTeam () internal view returns (uint) { uint a = (votersCountTeam * MAJORITY_PERCENTAGE_NEEDED ); return a / 100; } } contract CaelumAcceptERC20 is Ownable { using SafeMath for uint; IRemoteFunctions public DataVault; address[] public tokensList; bool setOwnContract = true; struct _whitelistTokens { address tokenAddress; bool active; uint requiredAmount; uint validUntil; uint timestamp; } mapping(address => mapping(address => uint)) public tokens; mapping(address => _whitelistTokens) acceptedTokens; event Deposit(address token, address user, uint amount, uint balance); event Withdraw(address token, address user, uint amount, uint balance); /** * @notice Allow the dev to set it's own token as accepted payment. * @dev Can be hardcoded in the constructor. Given the contract size, we decided to separate it. * @return bool */ function addOwnToken() onlyOwner public returns (bool) { require(setOwnContract); addToWhitelist(this, 5000 * 1e8, 36500); setOwnContract = false; return true; } /** * @notice Add a new token as accepted payment method. * @param _token Token contract address. * @param _amount Required amount of this Token as collateral * @param daysAllowed How many days will we accept this token? */ function addToWhitelist(address _token, uint _amount, uint daysAllowed) internal { _whitelistTokens storage newToken = acceptedTokens[_token]; newToken.tokenAddress = _token; newToken.requiredAmount = _amount; newToken.timestamp = now; newToken.validUntil = now + (daysAllowed * 1 days); newToken.active = true; tokensList.push(_token); } /** * @dev internal function to determine if we accept this token. * @param _ad Token contract address * @return bool */ function isAcceptedToken(address _ad) internal view returns(bool) { return acceptedTokens[_ad].active; } /** * @dev internal function to determine the requiredAmount for a specific token. * @param _ad Token contract address * @return bool */ function getAcceptedTokenAmount(address _ad) internal view returns(uint) { return acceptedTokens[_ad].requiredAmount; } /** * @dev internal function to determine if the token is still accepted timewise. * @param _ad Token contract address * @return bool */ function isValid(address _ad) internal view returns(bool) { uint endTime = acceptedTokens[_ad].validUntil; if (block.timestamp < endTime) return true; return false; } /** * @notice Returns an array of all accepted token. You can get more details by calling getTokenDetails function with this address. * @return array Address */ function listAcceptedTokens() public view returns(address[]) { return tokensList; } /** * @notice Returns a full list of the token details * @param token Token contract address */ function getTokenDetails(address token) public view returns(address ad,uint required, bool active, uint valid) { return (acceptedTokens[token].tokenAddress, acceptedTokens[token].requiredAmount,acceptedTokens[token].active, acceptedTokens[token].validUntil); } /** * @notice Public function that allows any user to deposit accepted tokens as collateral to become a masternode. * @param token Token contract address * @param amount Amount to deposit */ function depositCollateral(address token, uint amount) public { require(isAcceptedToken(token), "ERC20 not authorised"); // Should be a token from our list require(amount == getAcceptedTokenAmount(token)); // The amount needs to match our set amount require(isValid(token)); // It should be called within the setup timeframe tokens[token][msg.sender] = tokens[token][msg.sender].add(amount); require(StandardToken(token).transferFrom(msg.sender, this, amount), "error with token"); emit Deposit(token, msg.sender, amount, tokens[token][msg.sender]); DataVault._externalAddMasternode(msg.sender); } /** * @notice Public function that allows any user to withdraw deposited tokens and stop as masternode * @param token Token contract address * @param amount Amount to withdraw */ function withdrawCollateral(address token, uint amount) public { require(token != 0); // token should be an actual address require(isAcceptedToken(token), "ERC20 not authorised"); // Should be a token from our list require(amount == getAcceptedTokenAmount(token)); // The amount needs to match our set amount, allow only one withdrawal at a time. require(tokens[token][msg.sender] >= amount); // The owner must own at least this amount of tokens. uint amountToWithdraw = tokens[token][msg.sender]; tokens[token][msg.sender] = 0; DataVault._externalStopMasternode(msg.sender); if (!StandardToken(token).transfer(msg.sender, amountToWithdraw)) revert(); emit Withdraw(token, msg.sender, amountToWithdraw, amountToWithdraw); } function setDataStorage (address _masternodeContract) onlyOwner public { DataVault = IRemoteFunctions(_masternodeContract); } } contract CaelumAbstractMasternode is Ownable{ using SafeMath for uint; bool onTestnet = false; bool genesisAdded = false; uint public masternodeRound; uint public masternodeCandidate; uint public masternodeCounter; uint public masternodeEpoch; uint public miningEpoch; uint public rewardsProofOfWork; uint public rewardsMasternode; uint rewardsGlobal = 50 * 1e8; uint public MINING_PHASE_DURATION_BLOCKS = 4500; struct MasterNode { address accountOwner; bool isActive; bool isTeamMember; uint storedIndex; uint startingRound; uint[] indexcounter; } uint[] userArray; address[] userAddressArray; mapping(uint => MasterNode) userByIndex; // UINT masterMapping mapping(address => MasterNode) userByAddress; //masterMapping mapping(address => uint) userAddressIndex; event Deposit(address token, address user, uint amount, uint balance); event Withdraw(address token, address user, uint amount, uint balance); event NewMasternode(address candidateAddress, uint timeStamp); event RemovedMasternode(address candidateAddress, uint timeStamp); /** * @dev Add the genesis accounts */ function addGenesis(address _genesis, bool _team) onlyOwner public { require(!genesisAdded); addMasternode(_genesis); if (_team) { updateMasternodeAsTeamMember(msg.sender); } } /** * @dev Close the genesis accounts */ function closeGenesis() onlyOwner public { genesisAdded = true; // Forever lock this. } /** * @dev Add a user as masternode. Called as internal since we only add masternodes by depositing collateral or by voting. * @param _candidate Candidate address * @return uint Masternode index */ function addMasternode(address _candidate) internal returns(uint) { userByIndex[masternodeCounter].accountOwner = _candidate; userByIndex[masternodeCounter].isActive = true; userByIndex[masternodeCounter].startingRound = masternodeRound + 1; userByIndex[masternodeCounter].storedIndex = masternodeCounter; userByAddress[_candidate].accountOwner = _candidate; userByAddress[_candidate].indexcounter.push(masternodeCounter); userArray.push(userArray.length); masternodeCounter++; emit NewMasternode(_candidate, now); return masternodeCounter - 1; // } /** * @dev Allow us to update a masternode's round to keep progress * @param _candidate ID of masternode */ function updateMasternode(uint _candidate) internal returns(bool) { userByIndex[_candidate].startingRound++; return true; } /** * @dev Allow us to update a masternode to team member status * @param _member address */ function updateMasternodeAsTeamMember(address _member) internal returns (bool) { userByAddress[_member].isTeamMember = true; return (true); } /** * @dev Let us know if an address is part of the team. * @param _member address */ function isTeamMember (address _member) public view returns (bool) { if (userByAddress[_member].isTeamMember) return true; } /** * @dev Remove a specific masternode * @param _masternodeID ID of the masternode to remove */ function deleteMasternode(uint _masternodeID) internal returns(bool success) { uint rowToDelete = userByIndex[_masternodeID].storedIndex; uint keyToMove = userArray[userArray.length - 1]; userByIndex[_masternodeID].isActive = userByIndex[_masternodeID].isActive = (false); userArray[rowToDelete] = keyToMove; userByIndex[keyToMove].storedIndex = rowToDelete; userArray.length = userArray.length - 1; removeFromUserCounter(_masternodeID); emit RemovedMasternode(userByIndex[_masternodeID].accountOwner, now); return true; } /** * @dev returns what account belongs to a masternode */ function isPartOf(uint mnid) public view returns (address) { return userByIndex[mnid].accountOwner; } /** * @dev Internal function to remove a masternode from a user address if this address holds multpile masternodes * @param index MasternodeID */ function removeFromUserCounter(uint index) internal returns(uint[]) { address belong = isPartOf(index); if (index >= userByAddress[belong].indexcounter.length) return; for (uint i = index; i<userByAddress[belong].indexcounter.length-1; i++){ userByAddress[belong].indexcounter[i] = userByAddress[belong].indexcounter[i+1]; } delete userByAddress[belong].indexcounter[userByAddress[belong].indexcounter.length-1]; userByAddress[belong].indexcounter.length--; return userByAddress[belong].indexcounter; } /** * @dev Primary contract function to update the current user and prepare the next one. * A number of steps have been token to ensure the contract can never run out of gas when looping over our masternodes. */ function setMasternodeCandidate() internal returns(address) { uint hardlimitCounter = 0; while (getFollowingCandidate() == 0x0) { // We must return a value not to break the contract. Require is a secondary killswitch now. require(hardlimitCounter < 6, "Failsafe switched on"); // Choose if loop over revert/require to terminate the loop and return a 0 address. if (hardlimitCounter == 5) return (0); masternodeRound = masternodeRound + 1; masternodeCandidate = 0; hardlimitCounter++; } if (masternodeCandidate == masternodeCounter - 1) { masternodeRound = masternodeRound + 1; masternodeCandidate = 0; } for (uint i = masternodeCandidate; i < masternodeCounter; i++) { if (userByIndex[i].isActive) { if (userByIndex[i].startingRound == masternodeRound) { updateMasternode(i); masternodeCandidate = i; return (userByIndex[i].accountOwner); } } } masternodeRound = masternodeRound + 1; return (0); } /** * @dev Helper function to loop through our masternodes at start and return the correct round */ function getFollowingCandidate() internal view returns(address _address) { uint tmpRound = masternodeRound; uint tmpCandidate = masternodeCandidate; if (tmpCandidate == masternodeCounter - 1) { tmpRound = tmpRound + 1; tmpCandidate = 0; } for (uint i = masternodeCandidate; i < masternodeCounter; i++) { if (userByIndex[i].isActive) { if (userByIndex[i].startingRound == tmpRound) { tmpCandidate = i; return (userByIndex[i].accountOwner); } } } tmpRound = tmpRound + 1; return (0); } /** * @dev Displays all masternodes belonging to a user address. */ function belongsToUser(address userAddress) public view returns(uint[]) { return (userByAddress[userAddress].indexcounter); } /** * @dev Helper function to know if an address owns masternodes */ function isMasternodeOwner(address _candidate) public view returns(bool) { if(userByAddress[_candidate].indexcounter.length <= 0) return false; if (userByAddress[_candidate].accountOwner == _candidate) return true; } /** * @dev Helper function to get the last masternode belonging to a user */ function getLastPerUser(address _candidate) public view returns (uint) { return userByAddress[_candidate].indexcounter[userByAddress[_candidate].indexcounter.length - 1]; } /** * @dev Return the base rewards. This should be overrided by the miner contract. * Return a base value for standalone usage ONLY. */ function getMiningReward() public view returns(uint) { return 50 * 1e8; } /** * @dev Calculate and set the reward schema for Caelum. * Each mining phase is decided by multiplying the MINING_PHASE_DURATION_BLOCKS with factor 10. * Depending on the outcome (solidity always rounds), we can detect the current stage of mining. * First stage we cut the rewards to 5% to prevent instamining. * Last stage we leave 2% for miners to incentivize keeping miners running. */ function calculateRewardStructures() internal { //ToDo: Set uint _global_reward_amount = getMiningReward(); uint getStageOfMining = miningEpoch / MINING_PHASE_DURATION_BLOCKS * 10; if (getStageOfMining < 10) { rewardsProofOfWork = _global_reward_amount / 100 * 5; rewardsMasternode = 0; return; } if (getStageOfMining > 90) { rewardsProofOfWork = _global_reward_amount / 100 * 2; rewardsMasternode = _global_reward_amount / 100 * 98; return; } uint _mnreward = (_global_reward_amount / 100) * getStageOfMining; uint _powreward = (_global_reward_amount - _mnreward); setBaseRewards(_powreward, _mnreward); } function setBaseRewards(uint _pow, uint _mn) internal { rewardsMasternode = _mn; rewardsProofOfWork = _pow; } /** * @dev Executes the masternode flow. Should be called after mining a block. */ function _arrangeMasternodeFlow() internal { calculateRewardStructures(); setMasternodeCandidate(); miningEpoch++; } /** * @dev Executes the masternode flow. Should be called after mining a block. * This is an emergency manual loop method. */ function _emergencyLoop() onlyOwner public { calculateRewardStructures(); setMasternodeCandidate(); miningEpoch++; } function masternodeInfo(uint index) public view returns ( address, bool, uint, uint ) { return ( userByIndex[index].accountOwner, userByIndex[index].isActive, userByIndex[index].storedIndex, userByIndex[index].startingRound ); } function contractProgress() public view returns ( uint epoch, uint candidate, uint round, uint miningepoch, uint globalreward, uint powreward, uint masternodereward, uint usercounter ) { return ( masternodeEpoch, masternodeCandidate, masternodeRound, miningEpoch, getMiningReward(), rewardsProofOfWork, rewardsMasternode, masternodeCounter ); } } contract CaelumMasternode is CaelumVotings, CaelumAbstractMasternode { /** * @dev Hardcoded token mining address. For trust and safety we do not allow changing this. * Should anything change, a new instance needs to be redeployed. */ address public miningContract; address public tokenContract; bool minerSet = false; bool tokenSet = false; function setMiningContract(address _t) onlyOwner public { require(!minerSet); miningContract = _t; minerSet = true; } function setTokenContract(address _t) onlyOwner public { require(!tokenSet); tokenContract = _t; tokenSet = true; } function setMasternodeContractFromVote(address _t) internal { } function setTokenContractFromVote(address _t) internal{ tokenContract = _t; } function setMiningContractFromVote (address _t) internal { miningContract = _t; } /** * @dev Only allow the token mining contract to call this function when used remotely. * Use the internal function when working within the same contract. */ modifier onlyMiningContract() { require(msg.sender == miningContract); _; } /** * @dev Only allow the token contract to call this function when used remotely. * Use the internal function when working within the same contract. */ modifier onlyTokenContract() { require(msg.sender == tokenContract); _; } /** * @dev Only allow the token contract to call this function when used remotely. * Use the internal function when working within the same contract. */ modifier bothRemoteContracts() { require(msg.sender == tokenContract || msg.sender == miningContract); _; } /** * @dev Use this to externaly call the _arrangeMasternodeFlow function. ALWAYS set a modifier ! */ function _externalArrangeFlow() onlyMiningContract external { _arrangeMasternodeFlow(); } /** * @dev Use this to externaly call the addMasternode function. ALWAYS set a modifier ! */ function _externalAddMasternode(address _received) onlyMiningContract external { addMasternode(_received); } /** * @dev Use this to externaly call the deleteMasternode function. ALWAYS set a modifier ! */ function _externalStopMasternode(address _received) onlyMiningContract external { deleteMasternode(getLastPerUser(_received)); } function getMiningReward() public view returns(uint) { return CaelumMiner(miningContract).getMiningReward(); } address cloneDataFrom = 0x7600bF5112945F9F006c216d5d6db0df2806eDc6; function getDataFromContract () onlyOwner public returns(uint) { CaelumMasternode prev = CaelumMasternode(cloneDataFrom); (uint epoch, uint candidate, uint round, uint miningepoch, uint globalreward, uint powreward, uint masternodereward, uint usercounter) = prev.contractProgress(); masternodeEpoch = epoch; masternodeRound = round; miningEpoch = miningepoch; rewardsProofOfWork = powreward; rewardsMasternode = masternodereward; } } contract CaelumToken is Ownable, StandardToken, CaelumVotings, CaelumAcceptERC20 { using SafeMath for uint; ERC20 previousContract; bool contractSet = false; bool public swapClosed = false; uint public swapCounter; string public symbol = "CLM"; string public name = "Caelum Token"; uint8 public decimals = 8; uint256 public totalSupply = 2100000000000000; address public miningContract = 0x0; /** * @dev Only allow the token mining contract to call this function when used remotely. * Use the internal function when working within the same contract. */ modifier onlyMiningContract() { require(msg.sender == miningContract); _; } constructor(address _previousContract) public { previousContract = ERC20(_previousContract); swapClosed = false; swapCounter = 0; } function setMiningContract (address _t) onlyOwner public { require(!contractSet); miningContract = _t; contractSet = true; } function setMasternodeContractFromVote(address _t) internal { return; } function setTokenContractFromVote(address _t) internal{ return; } function setMiningContractFromVote (address _t) internal { miningContract = _t; } function changeSwapState (bool _state) onlyOwner public { require(swapCounter <= 9); swapClosed = _state; swapCounter++; } function rewardExternal(address _receiver, uint _amount) onlyMiningContract external { balances[_receiver] = balances[_receiver].add(_amount); emit Transfer(this, _receiver, _amount); } function upgradeTokens() public{ require(!swapClosed); uint amountToUpgrade = previousContract.balanceOf(msg.sender); require(amountToUpgrade <= previousContract.allowance(msg.sender, this)); if(previousContract.transferFrom(msg.sender, this, amountToUpgrade)){ balances[msg.sender] = balances[msg.sender].add(amountToUpgrade); // 2% Premine as determined by the community meeting. emit Transfer(this, msg.sender, amountToUpgrade); } require(previousContract.balanceOf(msg.sender) == 0); } } contract AbstractERC918 is EIP918Interface { // generate a new challenge number after a new reward is minted bytes32 public challengeNumber; // the current mining difficulty uint public difficulty; // cumulative counter of the total minted tokens uint public tokensMinted; // track read only minting statistics struct Statistics { address lastRewardTo; uint lastRewardAmount; uint lastRewardEthBlockNumber; uint lastRewardTimestamp; } Statistics public statistics; /* * Externally facing mint function that is called by miners to validate challenge digests, calculate reward, * populate statistics, mutate epoch variables and adjust the solution difficulty as required. Once complete, * a Mint event is emitted before returning a success indicator. **/ function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success); /* * Internal interface function _hash. Overide in implementation to define hashing algorithm and * validation **/ function _hash(uint256 nonce, bytes32 challenge_digest) internal returns (bytes32 digest); /* * Internal interface function _reward. Overide in implementation to calculate and return reward * amount **/ function _reward() internal returns (uint); /* * Internal interface function _newEpoch. Overide in implementation to define a cutpoint for mutating * mining variables in preparation for the next epoch **/ function _newEpoch(uint256 nonce) internal returns (uint); /* * Internal interface function _adjustDifficulty. Overide in implementation to adjust the difficulty * of the mining as required **/ function _adjustDifficulty() internal returns (uint); } contract CaelumAbstractMiner is AbstractERC918 { /** * CaelumMiner contract. * * We need to make sure the contract is 100% compatible when using the EIP918Interface. * This contract is an abstract Caelum miner contract. * * Function 'mint', and '_reward' are overriden in the CaelumMiner contract. * Function '_reward_masternode' is added and needs to be overriden in the CaelumMiner contract. */ using SafeMath for uint; using ExtendedMath for uint; uint256 public totalSupply = 2100000000000000; uint public latestDifficultyPeriodStarted; uint public epochCount; uint public baseMiningReward = 50; uint public blocksPerReadjustment = 512; uint public _MINIMUM_TARGET = 2 ** 16; uint public _MAXIMUM_TARGET = 2 ** 234; uint public rewardEra = 0; uint public maxSupplyForEra; uint public MAX_REWARD_ERA = 39; uint public MINING_RATE_FACTOR = 60; //mint the token 60 times less often than ether uint public MAX_ADJUSTMENT_PERCENT = 100; uint public TARGET_DIVISOR = 2000; uint public QUOTIENT_LIMIT = TARGET_DIVISOR.div(2); mapping(bytes32 => bytes32) solutionForChallenge; mapping(address => mapping(address => uint)) allowed; bytes32 public challengeNumber; uint public difficulty; uint public tokensMinted; Statistics public statistics; event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); event RewardMasternode(address candidate, uint amount); constructor() public { tokensMinted = 0; maxSupplyForEra = totalSupply.div(2); difficulty = _MAXIMUM_TARGET; latestDifficultyPeriodStarted = block.number; _newEpoch(0); } function _newEpoch(uint256 nonce) internal returns(uint) { if (tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < MAX_REWARD_ERA) { rewardEra = rewardEra + 1; } maxSupplyForEra = totalSupply - totalSupply.div(2 ** (rewardEra + 1)); epochCount = epochCount.add(1); challengeNumber = blockhash(block.number - 1); return (epochCount); } function mint(uint256 nonce, bytes32 challenge_digest) public returns(bool success); function _hash(uint256 nonce, bytes32 challenge_digest) internal returns(bytes32 digest) { digest = keccak256(challengeNumber, msg.sender, nonce); if (digest != challenge_digest) revert(); if (uint256(digest) > difficulty) revert(); bytes32 solution = solutionForChallenge[challengeNumber]; solutionForChallenge[challengeNumber] = digest; if (solution != 0x0) revert(); //prevent the same answer from awarding twice } function _reward() internal returns(uint); function _reward_masternode() internal returns(uint); function _adjustDifficulty() internal returns(uint) { //every so often, readjust difficulty. Dont readjust when deploying if (epochCount % blocksPerReadjustment != 0) { return difficulty; } uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted; //assume 360 ethereum blocks per hour //we want miners to spend 10 minutes to mine each 'block', about 60 ethereum blocks = one 0xbitcoin epoch uint epochsMined = blocksPerReadjustment; uint targetEthBlocksPerDiffPeriod = epochsMined * MINING_RATE_FACTOR; //if there were less eth blocks passed in time than expected if (ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod) { uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(MAX_ADJUSTMENT_PERCENT)).div(ethBlocksSinceLastDifficultyPeriod); uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(QUOTIENT_LIMIT); // If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100. //make it harder difficulty = difficulty.sub(difficulty.div(TARGET_DIVISOR).mul(excess_block_pct_extra)); //by up to 50 % } else { uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(MAX_ADJUSTMENT_PERCENT)).div(targetEthBlocksPerDiffPeriod); uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(QUOTIENT_LIMIT); //always between 0 and 1000 //make it easier difficulty = difficulty.add(difficulty.div(TARGET_DIVISOR).mul(shortage_block_pct_extra)); //by up to 50 % } latestDifficultyPeriodStarted = block.number; if (difficulty < _MINIMUM_TARGET) //very difficult { difficulty = _MINIMUM_TARGET; } if (difficulty > _MAXIMUM_TARGET) //very easy { difficulty = _MAXIMUM_TARGET; } } function getChallengeNumber() public view returns(bytes32) { return challengeNumber; } function getMiningDifficulty() public view returns(uint) { return _MAXIMUM_TARGET.div(difficulty); } function getMiningTarget() public view returns(uint) { return difficulty; } function getMiningReward() public view returns(uint) { return (baseMiningReward * 1e8).div(2 ** rewardEra); } function getMintDigest( uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number ) public view returns(bytes32 digesttest) { bytes32 digest = keccak256(challenge_number, msg.sender, nonce); return digest; } function checkMintSolution( uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget ) public view returns(bool success) { bytes32 digest = keccak256(challenge_number, msg.sender, nonce); if (uint256(digest) > testTarget) revert(); return (digest == challenge_digest); } } contract CaelumMiner is CaelumVotings, CaelumAbstractMiner { /** * CaelumMiner main contract * * Inherit from our abstract CaelumMiner contract and override some functions * of the AbstractERC918 contract to allow masternode rewardings. * * @dev use this contract to make all changes needed for your project. */ address cloneDataFrom = 0x7600bF5112945F9F006c216d5d6db0df2806eDc6; bool ACTIVE_CONTRACT_STATE = true; bool MasternodeSet = false; bool TokenSet = false; address _CaelumMasternodeContract; address _CaelumTokenContract; CaelumMasternode public MasternodeContract; CaelumToken public tokenContract; function setMasternodeContract(address _t) onlyOwner public { require(!MasternodeSet); MasternodeContract = CaelumMasternode(_t); _CaelumMasternodeContract = (_t); MasternodeSet = true; } function setTokenContract(address _t) onlyOwner public { require(!TokenSet); tokenContract = CaelumToken(_t); _CaelumTokenContract = (_t); TokenSet = true; } function setMiningContract (address _t) onlyOwner public { return; } function setMasternodeContractFromVote(address _t) internal { MasternodeContract = CaelumMasternode(_t); _CaelumMasternodeContract = (_t); } function setTokenContractFromVote(address _t) internal{ tokenContract = CaelumToken(_t); _CaelumTokenContract = (_t); } function setMiningContractFromVote (address _t) internal { return; } function lockMiningContract () onlyOwner public { ACTIVE_CONTRACT_STATE = false; } function getDataFromContract () onlyOwner public { require(_CaelumTokenContract != 0); require(_CaelumMasternodeContract != 0); CaelumMiner prev = CaelumMiner(cloneDataFrom); difficulty = prev.difficulty(); rewardEra = prev.rewardEra(); MINING_RATE_FACTOR = prev.MINING_RATE_FACTOR(); maxSupplyForEra = prev.maxSupplyForEra(); tokensMinted = prev.tokensMinted(); epochCount = prev.epochCount(); latestDifficultyPeriodStarted = prev.latestDifficultyPeriodStarted(); ACTIVE_CONTRACT_STATE = true; } /** * @dev override of the original function since we want to call the masternode contract remotely. */ function mint(uint256 nonce, bytes32 challenge_digest) public returns(bool success) { // If contract is no longer active, stop accepting solutions. require(ACTIVE_CONTRACT_STATE); _hash(nonce, challenge_digest); MasternodeContract._externalArrangeFlow(); uint rewardAmount =_reward(); uint rewardMasternode = _reward_masternode(); tokensMinted += rewardAmount.add(rewardMasternode); uint epochCounter = _newEpoch(nonce); _adjustDifficulty(); statistics = Statistics(msg.sender, rewardAmount, block.number, now); emit Mint(msg.sender, rewardAmount, epochCounter, challengeNumber); return true; } /** * @dev override of the original function since we want to call the masternode contract remotely. */ function _reward() internal returns(uint) { uint _pow = MasternodeContract.rewardsProofOfWork(); tokenContract.rewardExternal(msg.sender, _pow); return _pow; } /** * @dev override of the original function since we want to call the masternode contract remotely. */ function _reward_masternode() internal returns(uint) { uint _mnReward = MasternodeContract.rewardsMasternode(); if (MasternodeContract.masternodeCounter() == 0) return 0; uint getCandidate = MasternodeContract.masternodeCandidate(); address _mnCandidate = MasternodeContract.isPartOf(getCandidate); if (_mnCandidate == 0x0) return 0; tokenContract.rewardExternal(_mnCandidate, _mnReward); emit RewardMasternode(_mnCandidate, _mnReward); return _mnReward; } function getMiningReward() public view returns(uint) { return MasternodeContract.rewardsProofOfWork(); } } /** * Burn some gas and create all contracts in a single call :-) */ contract caelumFactory { CaelumMiner public MINER; CaelumMasternode public MASTER; CaelumToken public TOKEN; function newCookie() public { MINER = new CaelumMiner(); MASTER = new CaelumMasternode(); TOKEN = new CaelumToken(0x0); MASTER.setMiningContract(MINER); MASTER.setTokenContract(TOKEN); MINER.setMasternodeContract(MASTER); MINER.setTokenContract(TOKEN); TOKEN.setMiningContract(MINER); TOKEN.setDataStorage(MASTER); MASTER.transferOwnership(msg.sender); TOKEN.transferOwnership(msg.sender); MINER.transferOwnership(msg.sender); } }
* @dev Hardcoded token mining address. For trust and safety we do not allow changing this. Should anything change, a new instance needs to be redeployed./
function setMiningContract(address _t) onlyOwner public { require(!minerSet); miningContract = _t; minerSet = true; }
14,043,173
[ 1, 29601, 24808, 1147, 1131, 310, 1758, 18, 2457, 10267, 471, 24179, 732, 741, 486, 1699, 12770, 333, 18, 9363, 6967, 2549, 16, 279, 394, 791, 4260, 358, 506, 283, 12411, 329, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 27724, 310, 8924, 12, 2867, 389, 88, 13, 1338, 5541, 1071, 288, 203, 3639, 2583, 12, 5, 1154, 264, 694, 1769, 203, 3639, 1131, 310, 8924, 273, 389, 88, 31, 203, 3639, 1131, 264, 694, 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, -100, -100, -100, -100, -100, -100, -100, -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 "./CryptoverseAstronauts.sol"; /** * @title Cryptoverse Item System * @dev The cryptoverse item system manages all item related stuff like creating and trading. This * contract may throw the following error codes: * * - E-I1: You are not the owner of this item * - E-I2: You cannot perform this action while the item is equipped * - E-I3: This is not an item you can buy * - E-I4: This item is too expensive for you * - E-I5: This item was already destroyed * - E-I6: The upgrade is too expensive for you * - E-I7: This item has already reached maximum upgrade level - you cannot improve it further * - E-I8: You cannot equip more items - unequip one to equip a new one * - E-I9: This item is already unequipped * */ contract CryptoverseItems is CryptoverseAstronauts { event ItemBought(address buyer, uint itemId); event ItemUpgraded(address owner, uint itemId); event ItemEquipped(address owner, uint itemId); event ItemUnequipped(address owner, uint itemId); event ItemDestroyed(address destroyer, uint itemId); event ItemTypeCreated(uint itemTypeId); // The item struct is used both as an item type template and as the item itself which // the players can use. Items improve the players performance and can be sold. struct Item { // Unique item identifier uint id; // The name of the item (should be unique as well, but is no constraint) string name; // The items level. Improving typically makes the much stronger, thats why this // field should have an upper bound. uint16 level; // Indicators for how much this item improves the players capabilities uint16 mining; uint16 attack; uint16 defense; // Depending on the type (being a template or a purchased item owned by a player), // this field either indicates the initial purchase cost or the upgrade cost. uint64 cost; // Players can destroy and equip items. bool destroyed; bool equipped; } uint16 public maxItemLevel = 4; uint16 public maxEquipmentCount = 3; Item[] public itemTypes; Item[] public items; mapping(uint => address) itemToOwner; mapping(address => uint) ownerItemCount; mapping(address => uint) ownerEquippedItemCount; /** * @dev Some actions can only be performed by the owner of an item. * @param _itemId Item ID to check the owner of. */ modifier onlyOwnerOfItem(uint _itemId) { require(msg.sender == itemToOwner[_itemId], "E-I1"); _; } /** * @dev Some actions can only be performed when the item is not equipped at the moment. * @param _itemId Item ID to check if it is currently equipped. */ modifier onlyUnequippedItem(uint _itemId) { require(!items[_itemId].equipped, "E-I2"); _; } /** * @dev Some actions can only be performed for items that are not destroyed yet. * @param _itemId Item ID to check if not destroyed. */ modifier onlyNotDestroyedItem(uint _itemId) { require(!items[_itemId].destroyed, "E-I5"); _; } /** * @dev Owners of the contract (and the game) can create new item templates (or * types). Those can then be bought by the players. Please be careful with * the stats. They improve dramatically with the items level as well. * * @param _name The items (hopefully) unique name. * @param _mining How much does this item improve mining (at level 0). * @param _attack How much does this item improve attack (at level 0). * @param _defense How much does this item improve defense (at level 0). * @param _cost Initial purchase costs. */ function createItemType(string memory _name, uint16 _mining, uint16 _attack, uint16 _defense, uint64 _cost) external onlyOwner { uint id = itemTypes.length; itemTypes.push(Item(id, _name, 1, _mining, _attack, _defense, _cost, false, false)); emit ItemTypeCreated(id); } /** * @dev Returns all currently available item templates. */ function getItemTypes() external view returns (Item[] memory) { return itemTypes; } /** * @dev Tests if the given item type ID actually belongs to an item. */ function isItemType(uint _itemTypeId) public view returns (bool) { return itemTypes.length > _itemTypeId; } /** * @dev Players buy a certain item type. This function will revert if the player * does not have enough tokens. * @param _itemTypeId The type of item which the player want to purchase. */ function buyItem(uint _itemTypeId) external { require(isItemType(_itemTypeId), "E-I3"); Item memory itemType = itemTypes[_itemTypeId]; // Burn the items cost require(balanceOf(msg.sender) >= itemType.cost, "E-I4"); burn(itemType.cost); // Buy the item by copying the item type uint id = items.length; items.push(Item(id, itemType.name, itemType.level, itemType.mining, itemType.attack, itemType.defense, itemType.cost * 2, false, false)); itemToOwner[id] = msg.sender; ownerItemCount[msg.sender]++; // Emit the event to notify the buyer emit ItemBought(msg.sender, id); } /** * @dev Destroys the item with the given ID. Only the owner of the item can * destroy it. This action cannot be undone. * @param _itemId The item which should be destroyed. */ function destroyItem(uint _itemId) external onlyOwnerOfItem(_itemId) onlyUnequippedItem(_itemId) onlyNotDestroyedItem(_itemId) { items[_itemId].destroyed = true; ownerItemCount[msg.sender]--; emit ItemDestroyed(msg.sender, _itemId); } /** * @dev Increases the level of the item by one. This function will revert if the player * does not have enough tokens. * @param _itemId The item which should be upgraded. */ function upgradeItem(uint _itemId) external onlyOwnerOfItem(_itemId) onlyUnequippedItem(_itemId) onlyNotDestroyedItem(_itemId) { Item storage item = items[_itemId]; // Burn the amount of tokens that this upgrade costs require(balanceOf(msg.sender) >= item.cost, "E-I6"); require(item.level < maxItemLevel, "E-I7"); burn(item.cost); // Level up the item item.level++; item.mining *= 2; item.attack *= 2; item.defense *= 2; item.cost *= 2; // Emit the event to notify the owner of the upgrade emit ItemUpgraded(msg.sender, item.id); } /** * @dev For items to be in effect, players have to equip them. There is also a maximum * amount of equipment a player can use at a time. * @param _itemId The item which should be equipped. */ function equip(uint _itemId) external onlyOwnerOfItem(_itemId) onlyUnequippedItem(_itemId) onlyNotDestroyedItem(_itemId) { Astronaut storage me = ownerToAstronaut[msg.sender]; Item storage item = items[_itemId]; require(ownerEquippedItemCount[msg.sender] < maxEquipmentCount, "E-I8"); me.mining += item.mining; me.attack += item.attack; me.defense += item.defense; item.equipped = true; ownerEquippedItemCount[msg.sender]++; // Emit the event to notify the owner that the item is now equipped emit ItemEquipped(msg.sender, item.id); } /** * @dev Some actions require the player to unequip an item. * @param _itemId The item which should be unequipped. */ function unequip(uint _itemId) external onlyOwnerOfItem(_itemId) { Astronaut storage me = ownerToAstronaut[msg.sender]; Item storage item = items[_itemId]; require(item.equipped, "E-I9"); me.mining -= item.mining; me.attack -= item.attack; me.defense -= item.defense; item.equipped = false; ownerEquippedItemCount[msg.sender]--; // Emit the event to notify the owner that the item is now unequipped emit ItemUnequipped(msg.sender, item.id); } /** * @dev Returns all items of an owner. This function is external because it is really * expensive for a contract to perform on distributed transactions. * @param _owner The owners address. */ function getItemsByOwner(address _owner) external view returns (Item[] memory) { Item[] memory result = new Item[](ownerItemCount[_owner]); Item memory item; uint counter = 0; for (uint i = 0; i < items.length; i++) { item = items[i]; if (!item.destroyed && itemToOwner[i] == _owner) { result[counter] = item; counter++; } } return result; } /** * @dev Sets the max item level. Items cannot be level higher than that. If the level * should be decrease, items which are already higher than that will NOT be downgraded. * @param _maxItemLevel New max item level. */ function setMaxItemLevel(uint16 _maxItemLevel) external onlyOwner { maxItemLevel = _maxItemLevel; } /** * @dev Sets the max amount of items that can be equipped at a time by a player. * @param _maxEquipmentCount New max equipment count. */ function setMaxEquipmentCount(uint16 _maxEquipmentCount) external onlyOwner { maxEquipmentCount = _maxEquipmentCount; } }
* @title Cryptoverse Item System @dev The cryptoverse item system manages all item related stuff like creating and trading. This contract may throw the following error codes: - E-I1: You are not the owner of this item - E-I2: You cannot perform this action while the item is equipped - E-I3: This is not an item you can buy - E-I4: This item is too expensive for you - E-I5: This item was already destroyed - E-I6: The upgrade is too expensive for you - E-I7: This item has already reached maximum upgrade level - you cannot improve it further - E-I8: You cannot equip more items - unequip one to equip a new one - E-I9: This item is already unequipped/ The item struct is used both as an item type template and as the item itself which the players can use. Items improve the players performance and can be sold.
contract CryptoverseItems is CryptoverseAstronauts { event ItemBought(address buyer, uint itemId); event ItemUpgraded(address owner, uint itemId); event ItemEquipped(address owner, uint itemId); event ItemUnequipped(address owner, uint itemId); event ItemDestroyed(address destroyer, uint itemId); event ItemTypeCreated(uint itemTypeId); pragma solidity ^0.8.0; struct Item { uint id; string name; uint16 level; uint16 mining; uint16 attack; uint16 defense; uint64 cost; bool destroyed; bool equipped; } uint16 public maxItemLevel = 4; uint16 public maxEquipmentCount = 3; Item[] public itemTypes; Item[] public items; mapping(uint => address) itemToOwner; mapping(address => uint) ownerItemCount; mapping(address => uint) ownerEquippedItemCount; modifier onlyOwnerOfItem(uint _itemId) { require(msg.sender == itemToOwner[_itemId], "E-I1"); _; } modifier onlyUnequippedItem(uint _itemId) { require(!items[_itemId].equipped, "E-I2"); _; } modifier onlyNotDestroyedItem(uint _itemId) { require(!items[_itemId].destroyed, "E-I5"); _; } function createItemType(string memory _name, uint16 _mining, uint16 _attack, uint16 _defense, uint64 _cost) external onlyOwner { uint id = itemTypes.length; itemTypes.push(Item(id, _name, 1, _mining, _attack, _defense, _cost, false, false)); emit ItemTypeCreated(id); } function getItemTypes() external view returns (Item[] memory) { return itemTypes; } function isItemType(uint _itemTypeId) public view returns (bool) { return itemTypes.length > _itemTypeId; } function buyItem(uint _itemTypeId) external { require(isItemType(_itemTypeId), "E-I3"); Item memory itemType = itemTypes[_itemTypeId]; require(balanceOf(msg.sender) >= itemType.cost, "E-I4"); burn(itemType.cost); uint id = items.length; items.push(Item(id, itemType.name, itemType.level, itemType.mining, itemType.attack, itemType.defense, itemType.cost * 2, false, false)); itemToOwner[id] = msg.sender; ownerItemCount[msg.sender]++; emit ItemBought(msg.sender, id); } function destroyItem(uint _itemId) external onlyOwnerOfItem(_itemId) onlyUnequippedItem(_itemId) onlyNotDestroyedItem(_itemId) { items[_itemId].destroyed = true; ownerItemCount[msg.sender]--; emit ItemDestroyed(msg.sender, _itemId); } function upgradeItem(uint _itemId) external onlyOwnerOfItem(_itemId) onlyUnequippedItem(_itemId) onlyNotDestroyedItem(_itemId) { Item storage item = items[_itemId]; require(balanceOf(msg.sender) >= item.cost, "E-I6"); require(item.level < maxItemLevel, "E-I7"); burn(item.cost); item.level++; item.mining *= 2; item.attack *= 2; item.defense *= 2; item.cost *= 2; emit ItemUpgraded(msg.sender, item.id); } function equip(uint _itemId) external onlyOwnerOfItem(_itemId) onlyUnequippedItem(_itemId) onlyNotDestroyedItem(_itemId) { Astronaut storage me = ownerToAstronaut[msg.sender]; Item storage item = items[_itemId]; require(ownerEquippedItemCount[msg.sender] < maxEquipmentCount, "E-I8"); me.mining += item.mining; me.attack += item.attack; me.defense += item.defense; item.equipped = true; ownerEquippedItemCount[msg.sender]++; emit ItemEquipped(msg.sender, item.id); } function unequip(uint _itemId) external onlyOwnerOfItem(_itemId) { Astronaut storage me = ownerToAstronaut[msg.sender]; Item storage item = items[_itemId]; require(item.equipped, "E-I9"); me.mining -= item.mining; me.attack -= item.attack; me.defense -= item.defense; item.equipped = false; ownerEquippedItemCount[msg.sender]--; emit ItemUnequipped(msg.sender, item.id); } function getItemsByOwner(address _owner) external view returns (Item[] memory) { Item[] memory result = new Item[](ownerItemCount[_owner]); Item memory item; uint counter = 0; for (uint i = 0; i < items.length; i++) { item = items[i]; if (!item.destroyed && itemToOwner[i] == _owner) { result[counter] = item; counter++; } } return result; } function getItemsByOwner(address _owner) external view returns (Item[] memory) { Item[] memory result = new Item[](ownerItemCount[_owner]); Item memory item; uint counter = 0; for (uint i = 0; i < items.length; i++) { item = items[i]; if (!item.destroyed && itemToOwner[i] == _owner) { result[counter] = item; counter++; } } return result; } function getItemsByOwner(address _owner) external view returns (Item[] memory) { Item[] memory result = new Item[](ownerItemCount[_owner]); Item memory item; uint counter = 0; for (uint i = 0; i < items.length; i++) { item = items[i]; if (!item.destroyed && itemToOwner[i] == _owner) { result[counter] = item; counter++; } } return result; } function setMaxItemLevel(uint16 _maxItemLevel) external onlyOwner { maxItemLevel = _maxItemLevel; } function setMaxEquipmentCount(uint16 _maxEquipmentCount) external onlyOwner { maxEquipmentCount = _maxEquipmentCount; } }
12,939,014
[ 1, 22815, 1643, 307, 4342, 2332, 225, 1021, 13231, 1643, 307, 761, 2619, 20754, 281, 777, 761, 3746, 10769, 3007, 4979, 471, 1284, 7459, 18, 1220, 1377, 6835, 2026, 604, 326, 3751, 555, 6198, 30, 3639, 300, 512, 17, 45, 21, 30, 4554, 854, 486, 326, 3410, 434, 333, 761, 3639, 300, 512, 17, 45, 22, 30, 4554, 2780, 3073, 333, 1301, 1323, 326, 761, 353, 1298, 625, 1845, 3639, 300, 512, 17, 45, 23, 30, 1220, 353, 486, 392, 761, 1846, 848, 30143, 3639, 300, 512, 17, 45, 24, 30, 1220, 761, 353, 4885, 19326, 364, 1846, 3639, 300, 512, 17, 45, 25, 30, 1220, 761, 1703, 1818, 17689, 3639, 300, 512, 17, 45, 26, 30, 1021, 8400, 353, 4885, 19326, 364, 1846, 3639, 300, 512, 17, 45, 27, 30, 1220, 761, 711, 1818, 8675, 4207, 8400, 1801, 300, 1846, 2780, 21171, 518, 9271, 3639, 300, 512, 17, 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, 16351, 22752, 1643, 307, 3126, 353, 22752, 1643, 307, 37, 701, 265, 5854, 87, 288, 203, 203, 565, 871, 4342, 13809, 9540, 12, 2867, 27037, 16, 2254, 18424, 1769, 203, 565, 871, 4342, 1211, 19305, 12, 2867, 3410, 16, 2254, 18424, 1769, 203, 565, 871, 4342, 13142, 625, 1845, 12, 2867, 3410, 16, 2254, 18424, 1769, 203, 565, 871, 4342, 984, 14298, 625, 1845, 12, 2867, 3410, 16, 2254, 18424, 1769, 203, 565, 871, 4342, 28414, 12, 2867, 5546, 264, 16, 2254, 18424, 1769, 203, 203, 565, 871, 4342, 559, 6119, 12, 11890, 761, 11731, 1769, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 1958, 4342, 288, 203, 203, 3639, 2254, 612, 31, 203, 203, 3639, 533, 508, 31, 203, 203, 3639, 2254, 2313, 1801, 31, 203, 203, 3639, 2254, 2313, 1131, 310, 31, 203, 3639, 2254, 2313, 13843, 31, 203, 3639, 2254, 2313, 1652, 3558, 31, 203, 203, 3639, 2254, 1105, 6991, 31, 203, 203, 3639, 1426, 17689, 31, 203, 3639, 1426, 1298, 625, 1845, 31, 203, 565, 289, 203, 203, 565, 2254, 2313, 1071, 943, 1180, 2355, 273, 1059, 31, 203, 565, 2254, 2313, 1071, 943, 13142, 11568, 1380, 273, 890, 31, 203, 203, 565, 4342, 8526, 1071, 761, 2016, 31, 203, 565, 4342, 8526, 1071, 1516, 31, 203, 203, 565, 2874, 12, 11890, 516, 1758, 13, 761, 774, 5541, 31, 203, 565, 2874, 12, 2867, 516, 2254, 13, 3410, 30687, 31, 203, 565, 2874, 12, 2867, 516, 2254, 13, 3410, 13142, 625, 1845, 2 ]
./full_match/5/0x5358a276C28028dB9DCcD5Fe1fC92540652530aa/sources/contracts/ZkEvmV2.sol
* @notice Finalizes blocks without using a proof. @dev DEFAULT_ADMIN_ROLE is required to execute. @dev _blocksData[0].fromAddresses is a temporary workaround to pass bytes calldata @param _blocksData The full BlockData collection - block, transaction and log data./
function finalizeBlocksWithoutProof( BlockData[] calldata _blocksData ) external whenTypeNotPaused(GENERAL_PAUSE_TYPE) onlyRole(DEFAULT_ADMIN_ROLE) { _finalizeBlocks(_blocksData, _blocksData[0].fromAddresses, 0, bytes32(0), false); }
7,069,729
[ 1, 7951, 3128, 4398, 2887, 1450, 279, 14601, 18, 225, 3331, 67, 15468, 67, 16256, 353, 1931, 358, 1836, 18, 225, 389, 7996, 751, 63, 20, 8009, 2080, 7148, 353, 279, 6269, 18975, 358, 1342, 1731, 745, 892, 225, 389, 7996, 751, 1021, 1983, 3914, 751, 1849, 300, 1203, 16, 2492, 471, 613, 501, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 225, 445, 12409, 6450, 8073, 20439, 12, 203, 565, 3914, 751, 8526, 745, 892, 389, 7996, 751, 203, 225, 262, 3903, 1347, 559, 1248, 28590, 12, 13990, 1013, 67, 4066, 8001, 67, 2399, 13, 1338, 2996, 12, 5280, 67, 15468, 67, 16256, 13, 288, 203, 565, 389, 30343, 6450, 24899, 7996, 751, 16, 389, 7996, 751, 63, 20, 8009, 2080, 7148, 16, 374, 16, 1731, 1578, 12, 20, 3631, 629, 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 ]
pragma solidity ^0.4.18; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @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 SelfllerySaleFoundation is Ownable { using SafeMath for uint; // Amount of Ether paid from each address mapping (address => uint) public paidEther; // Pre-sale participant tokens for each address mapping (address => uint) public preSaleParticipantTokens; // Number of tokens was sent during the ICO for each address mapping (address => uint) public sentTokens; // SELFLLERY PTE LTD (manager wallet) address public selflleryManagerWallet; // The token contract used for this ICO ERC20 public token; // Number of cents for 1 YOU uint public tokenCents; // The token price from 1 wei uint public tokenPriceWei; // Number of tokens in cents for sale uint public saleTokensCents; // The amount purchased tokens at the moment uint public currentCapTokens; // The amount of Ether raised at the moment uint public currentCapEther; // Start date of the ICO uint public startDate; // End date of bonus time uint public bonusEndDate; // End date of the ICO uint public endDate; // Hard cap of tokens uint public hardCapTokens; // The minimum purchase for user uint public minimumPurchaseAmount; // The bonus percent for purchase first 48 hours uint8 public bonusPercent; event PreSalePurchase(address indexed purchasedBy, uint amountTokens); event Purchase(address indexed purchasedBy, uint amountTokens, uint etherWei); /** * @dev Throws if date isn't between ICO dates. */ modifier onlyDuringICODates() { require(now >= startDate && now <= endDate); _; } /** * @dev Initialize the ICO contract */ function SelfllerySaleFoundation( address _token, address _selflleryManagerWallet, uint _tokenCents, uint _tokenPriceWei, uint _saleTokensCents, uint _startDate, uint _bonusEndDate, uint _endDate, uint _hardCapTokens, uint _minimumPurchaseAmount, uint8 _bonusPercent ) public Ownable() { token = ERC20(_token); selflleryManagerWallet = _selflleryManagerWallet; tokenCents = _tokenCents; tokenPriceWei = _tokenPriceWei; saleTokensCents = _saleTokensCents; startDate = _startDate; bonusEndDate = _bonusEndDate; endDate = _endDate; hardCapTokens = _hardCapTokens; minimumPurchaseAmount = _minimumPurchaseAmount; bonusPercent = _bonusPercent; } /** * @dev Purchase tokens for the amount of ether sent to this contract */ function () public payable { purchase(); } /** * @dev Purchase tokens for the amount of ether sent to this contract * @return A boolean that indicates if the operation was successful. */ function purchase() public payable returns(bool) { return purchaseFor(msg.sender); } /** * @dev Purchase tokens for the amount of ether sent to this contract for custom address * @param _participant The address of the participant * @return A boolean that indicates if the operation was successful. */ function purchaseFor(address _participant) public payable onlyDuringICODates() returns(bool) { require(_participant != 0x0); require(paidEther[_participant].add(msg.value) >= minimumPurchaseAmount); selflleryManagerWallet.transfer(msg.value); uint currentBonusPercent = getCurrentBonusPercent(); uint totalTokens = calcTotalTokens(msg.value, currentBonusPercent); require(currentCapTokens.add(totalTokens) <= saleTokensCents); require(token.transferFrom(owner, _participant, totalTokens)); sentTokens[_participant] = sentTokens[_participant].add(totalTokens); currentCapTokens = currentCapTokens.add(totalTokens); currentCapEther = currentCapEther.add(msg.value); paidEther[_participant] = paidEther[_participant].add(msg.value); Purchase(_participant, totalTokens, msg.value); return true; } /** * @dev Change minimum purchase amount any time only owner * @param _newMinimumPurchaseAmount New minimum puchase amount * @return A boolean that indicates if the operation was successful. */ function changeMinimumPurchaseAmount(uint _newMinimumPurchaseAmount) public onlyOwner returns(bool) { require(_newMinimumPurchaseAmount >= 0); minimumPurchaseAmount = _newMinimumPurchaseAmount; return true; } /** * @dev Add pre-sale purchased tokens only owner * @param _participant The address of the participant * @param _totalTokens Total tokens amount for pre-sale participant * @return A boolean that indicates if the operation was successful. */ function addPreSalePurchaseTokens(address _participant, uint _totalTokens) public onlyOwner returns(bool) { require(_participant != 0x0); require(_totalTokens > 0); require(currentCapTokens.add(_totalTokens) <= saleTokensCents); require(token.transferFrom(owner, _participant, _totalTokens)); sentTokens[_participant] = sentTokens[_participant].add(_totalTokens); preSaleParticipantTokens[_participant] = preSaleParticipantTokens[_participant].add(_totalTokens); currentCapTokens = currentCapTokens.add(_totalTokens); PreSalePurchase(_participant, _totalTokens); return true; } /** * @dev Is finish date ICO reached? * @return A boolean that indicates if finish date ICO reached. */ function isFinishDateReached() public constant returns(bool) { return endDate <= now; } /** * @dev Is hard cap tokens reached? * @return A boolean that indicates if hard cap tokens reached. */ function isHardCapTokensReached() public constant returns(bool) { return hardCapTokens <= currentCapTokens; } /** * @dev Is ICO Finished? * @return A boolean that indicates if ICO finished. */ function isIcoFinished() public constant returns(bool) { return isFinishDateReached() || isHardCapTokensReached(); } /** * @dev Calc total tokens for fixed value and bonus percent * @param _value Amount of ether * @param _bonusPercent Bonus percent * @return uint */ function calcTotalTokens(uint _value, uint _bonusPercent) internal view returns(uint) { uint tokensAmount = _value.mul(tokenCents).div(tokenPriceWei); require(tokensAmount > 0); uint bonusTokens = tokensAmount.mul(_bonusPercent).div(100); uint totalTokens = tokensAmount.add(bonusTokens); return totalTokens; } /** * @dev Get current bonus percent for this transaction * @return uint */ function getCurrentBonusPercent() internal constant returns (uint) { uint currentBonusPercent; if (now <= bonusEndDate) { currentBonusPercent = bonusPercent; } else { currentBonusPercent = 0; } return currentBonusPercent; } } contract SelfllerySale is SelfllerySaleFoundation { address constant TOKEN_ADDRESS = 0x7e921CA9b78d9A6cCC39891BA545836365525C06; // Token YOU address constant SELFLLERY_MANAGER_WALLET = 0xdABb398298192192e5d4Ed2f120Ff7Af312B06eb;// SELFLLERY PTE LTD uint constant TOKEN_CENTS = 1e18; uint constant TOKEN_PRICE_WEI = 1e15; uint constant SALE_TOKENS_CENTS = 55000000 * TOKEN_CENTS; uint constant SALE_HARD_CAP_TOKENS = 55000000 * TOKEN_CENTS; uint8 constant BONUS_PERCENT = 5; uint constant MINIMUM_PURCHASE_AMOUNT = 0.1 ether; uint constant SALE_START_DATE = 1520240400; // 05.03.2018 9:00 UTC uint constant SALE_BONUS_END_DATE = 1520413200; // 07.03.2018 9:00 UTC uint constant SALE_END_DATE = 1522144800; // 27.03.2018 10:00 UTC /** * @dev Initialize the ICO contract */ function SelfllerySale() public SelfllerySaleFoundation( TOKEN_ADDRESS, SELFLLERY_MANAGER_WALLET, TOKEN_CENTS, TOKEN_PRICE_WEI, SALE_TOKENS_CENTS, SALE_START_DATE, SALE_BONUS_END_DATE, SALE_END_DATE, SALE_HARD_CAP_TOKENS, MINIMUM_PURCHASE_AMOUNT, BONUS_PERCENT ) {} }
* @dev Calc total tokens for fixed value and bonus percent @param _value Amount of ether @param _bonusPercent Bonus percent @return uint/
function calcTotalTokens(uint _value, uint _bonusPercent) internal view returns(uint) { uint tokensAmount = _value.mul(tokenCents).div(tokenPriceWei); require(tokensAmount > 0); uint bonusTokens = tokensAmount.mul(_bonusPercent).div(100); uint totalTokens = tokensAmount.add(bonusTokens); return totalTokens; }
1,050,275
[ 1, 25779, 2078, 2430, 364, 5499, 460, 471, 324, 22889, 5551, 225, 389, 1132, 16811, 434, 225, 2437, 225, 389, 18688, 407, 8410, 605, 22889, 5551, 327, 2254, 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 ]
[ 1, 1, 1, 1, 1, 1, 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, 565, 445, 7029, 5269, 5157, 12, 11890, 389, 1132, 16, 2254, 389, 18688, 407, 8410, 13, 2713, 1476, 1135, 12, 11890, 13, 288, 203, 3639, 2254, 2430, 6275, 273, 389, 1132, 18, 16411, 12, 2316, 39, 4877, 2934, 2892, 12, 2316, 5147, 3218, 77, 1769, 203, 3639, 2583, 12, 7860, 6275, 405, 374, 1769, 203, 3639, 2254, 324, 22889, 5157, 273, 2430, 6275, 18, 16411, 24899, 18688, 407, 8410, 2934, 2892, 12, 6625, 1769, 203, 3639, 2254, 2078, 5157, 273, 2430, 6275, 18, 1289, 12, 18688, 407, 5157, 1769, 203, 3639, 327, 2078, 5157, 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 ]
./full_match/100/0x1141fE08970c99dDA204D565Af7730870C46700f/sources/contracts/ALIENO-xDAI_Chain-Contract_Source_Code.sol
File: @openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.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 ERC20Burnable is Context, ERC20 { function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } pragma solidity ^0.8.9; function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } }
14,287,968
[ 1, 812, 30, 632, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 2316, 19, 654, 39, 3462, 19, 9489, 19, 654, 39, 3462, 38, 321, 429, 18, 18281, 225, 10021, 434, 288, 654, 39, 3462, 97, 716, 5360, 1147, 366, 4665, 358, 5546, 3937, 3675, 4953, 2430, 471, 5348, 716, 2898, 1240, 392, 1699, 1359, 364, 16, 316, 279, 4031, 716, 848, 506, 16332, 3397, 17, 5639, 261, 21985, 871, 6285, 2934, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 17801, 6835, 4232, 39, 3462, 38, 321, 429, 353, 1772, 16, 4232, 39, 3462, 288, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 29, 31, 203, 203, 565, 445, 18305, 12, 11890, 5034, 3844, 13, 1071, 5024, 288, 203, 3639, 389, 70, 321, 24899, 3576, 12021, 9334, 3844, 1769, 203, 565, 289, 203, 203, 565, 445, 18305, 1265, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 1071, 5024, 288, 203, 3639, 2254, 5034, 783, 7009, 1359, 273, 1699, 1359, 12, 4631, 16, 389, 3576, 12021, 10663, 203, 3639, 2583, 12, 2972, 7009, 1359, 1545, 3844, 16, 315, 654, 39, 3462, 30, 18305, 3844, 14399, 1699, 1359, 8863, 203, 3639, 22893, 288, 203, 5411, 389, 12908, 537, 12, 4631, 16, 389, 3576, 12021, 9334, 783, 7009, 1359, 300, 3844, 1769, 203, 3639, 289, 203, 3639, 389, 70, 321, 12, 4631, 16, 3844, 1769, 203, 565, 289, 203, 565, 445, 18305, 1265, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 1071, 5024, 288, 203, 3639, 2254, 5034, 783, 7009, 1359, 273, 1699, 1359, 12, 4631, 16, 389, 3576, 12021, 10663, 203, 3639, 2583, 12, 2972, 7009, 1359, 1545, 3844, 16, 315, 654, 39, 3462, 30, 18305, 3844, 14399, 1699, 1359, 8863, 203, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.7.5; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } } library Address { 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; } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, 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 { if (returndata.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns (bytes memory) { if (success) { return returndata; } else { if (returndata.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } interface IOwnable { function manager() external view returns (address); function renounceManagement() external; function pushManagement(address newOwner_) external; function pullManagement() external; } contract Ownable is IOwnable { address internal _owner; address internal _newOwner; event OwnershipPushed(address indexed previousOwner, address indexed newOwner); event OwnershipPulled(address indexed previousOwner, address indexed newOwner); constructor () { _owner = msg.sender; emit OwnershipPushed(address(0), _owner); } function manager() public view override returns (address) { return _owner; } modifier onlyManager() { require(_owner == msg.sender, "Ownable: caller is not the owner"); _; } function renounceManagement() public virtual override onlyManager() { emit OwnershipPushed(_owner, address(0)); _owner = address(0); } function pushManagement(address newOwner_) public virtual override onlyManager() { require(newOwner_ != address(0), "Ownable: new owner is the zero address"); emit OwnershipPushed(_owner, newOwner_); _newOwner = newOwner_; } function pullManagement() public virtual override { require(msg.sender == _newOwner, "Ownable: must be new owner to pull"); emit OwnershipPulled(_owner, _newOwner); _owner = _newOwner; } } interface IERC20 { function decimals() external view returns (uint8); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function totalSupply() external view returns (uint256); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library 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 _callOptionalReturn(IERC20 token, bytes memory data) private { 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"); } } } interface IERC20Mintable { function mint(uint256 amount_) external; function mint(address account_, uint256 ammount_) external; } interface IGWSERC20 { function burnFrom(address account_, uint256 amount_) external; } interface IBondCalculator { function valuation(address pair_, uint amount_) external view returns (uint _value); } contract GenerationalWealthSocietyTreasury is Ownable { using SafeMath for uint; using SafeERC20 for IERC20; event Deposit(address indexed token, uint amount, uint value); event Withdrawal(address indexed token, uint amount, uint value); event CreateDebt(address indexed debtor, address indexed token, uint amount, uint value); event RepayDebt(address indexed debtor, address indexed token, uint amount, uint value); event ReservesManaged(address indexed token, uint amount); event ReservesUpdated(uint indexed totalReserves); event ReservesAudited(uint indexed totalReserves); event RewardsMinted(address indexed caller, address indexed recipient, uint amount); event ChangeQueued(MANAGING indexed managing, address queued); event ChangeActivated(MANAGING indexed managing, address activated, bool result); enum MANAGING {RESERVEDEPOSITOR, RESERVESPENDER, RESERVETOKEN, RESERVEMANAGER, LIQUIDITYDEPOSITOR, LIQUIDITYTOKEN, LIQUIDITYMANAGER, DEBTOR, REWARDMANAGER, SGWS} address public immutable GWS; uint public immutable blocksNeededForQueue; address[] public reserveTokens; // Push only, beware false-positives. mapping(address => bool) public isReserveToken; mapping(address => uint) public reserveTokenQueue; // Delays changes to mapping. address[] public reserveDepositors; // Push only, beware false-positives. Only for viewing. mapping(address => bool) public isReserveDepositor; mapping(address => uint) public reserveDepositorQueue; // Delays changes to mapping. address[] public reserveSpenders; // Push only, beware false-positives. Only for viewing. mapping(address => bool) public isReserveSpender; mapping(address => uint) public reserveSpenderQueue; // Delays changes to mapping. address[] public liquidityTokens; // Push only, beware false-positives. mapping(address => bool) public isLiquidityToken; mapping(address => uint) public LiquidityTokenQueue; // Delays changes to mapping. address[] public liquidityDepositors; // Push only, beware false-positives. Only for viewing. mapping(address => bool) public isLiquidityDepositor; mapping(address => uint) public LiquidityDepositorQueue; // Delays changes to mapping. mapping(address => address) public bondCalculator; // bond calculator for liquidity token address[] public reserveManagers; // Push only, beware false-positives. Only for viewing. mapping(address => bool) public isReserveManager; mapping(address => uint) public ReserveManagerQueue; // Delays changes to mapping. address[] public liquidityManagers; // Push only, beware false-positives. Only for viewing. mapping(address => bool) public isLiquidityManager; mapping(address => uint) public LiquidityManagerQueue; // Delays changes to mapping. address[] public debtors; // Push only, beware false-positives. Only for viewing. mapping(address => bool) public isDebtor; mapping(address => uint) public debtorQueue; // Delays changes to mapping. mapping(address => uint) public debtorBalance; address[] public rewardManagers; // Push only, beware false-positives. Only for viewing. mapping(address => bool) public isRewardManager; mapping(address => uint) public rewardManagerQueue; // Delays changes to mapping. address public sGWS; uint public sGWSQueue; // Delays change to sGWS address uint public totalReserves; // Risk-free value of all assets uint public totalDebt; constructor ( address _GWS, address _DAI, uint _blocksNeededForQueue ) { require(_GWS != address(0)); GWS = _GWS; isReserveToken[_DAI] = true; reserveTokens.push(_DAI); // isLiquidityToken[_GWSDAI] = true; // liquidityTokens.push(_GWSDAI); blocksNeededForQueue = _blocksNeededForQueue; } /** @notice allow approved address to deposit an asset for GWS @param _amount uint @param _token address @param _profit uint @return send_ uint */ function deposit(uint _amount, address _token, uint _profit) external returns (uint send_) { require(isReserveToken[_token] || isLiquidityToken[_token], "Not accepted"); IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); if (isReserveToken[_token]) { require(isReserveDepositor[msg.sender], "Not approved"); } else { require(isLiquidityDepositor[msg.sender], "Not approved"); } uint value = valueOf(_token, _amount); // mint GWS needed and store amount of rewards for distribution send_ = value.sub(_profit); IERC20Mintable(GWS).mint(msg.sender, send_); totalReserves = totalReserves.add(value); emit ReservesUpdated(totalReserves); emit Deposit(_token, _amount, value); } /** @notice allow approved address to burn GWS for reserves @param _amount uint @param _token address */ function withdraw(uint _amount, address _token) external { require(isReserveToken[_token], "Not accepted"); // Only reserves can be used for redemptions require(isReserveSpender[msg.sender] == true, "Not approved"); uint value = valueOf(_token, _amount); IGWSERC20(GWS).burnFrom(msg.sender, value); totalReserves = totalReserves.sub(value); emit ReservesUpdated(totalReserves); IERC20(_token).safeTransfer(msg.sender, _amount); emit Withdrawal(_token, _amount, value); } /** @notice allow approved address to borrow reserves @param _amount uint @param _token address */ function incurDebt(uint _amount, address _token) external { require(isDebtor[msg.sender], "Not approved"); require(isReserveToken[_token], "Not accepted"); uint value = valueOf(_token, _amount); uint maximumDebt = IERC20(sGWS).balanceOf(msg.sender); // Can only borrow against sGWS held uint availableDebt = maximumDebt.sub(debtorBalance[msg.sender]); require(value <= availableDebt, "Exceeds debt limit"); debtorBalance[msg.sender] = debtorBalance[msg.sender].add(value); totalDebt = totalDebt.add(value); totalReserves = totalReserves.sub(value); emit ReservesUpdated(totalReserves); IERC20(_token).transfer(msg.sender, _amount); emit CreateDebt(msg.sender, _token, _amount, value); } /** @notice allow approved address to repay borrowed reserves with reserves @param _amount uint @param _token address */ function repayDebtWithReserve(uint _amount, address _token) external { require(isDebtor[msg.sender], "Not approved"); require(isReserveToken[_token], "Not accepted"); IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); uint value = valueOf(_token, _amount); debtorBalance[msg.sender] = debtorBalance[msg.sender].sub(value); totalDebt = totalDebt.sub(value); totalReserves = totalReserves.add(value); emit ReservesUpdated(totalReserves); emit RepayDebt(msg.sender, _token, _amount, value); } /** @notice allow approved address to repay borrowed reserves with GWS @param _amount uint */ function repayDebtWithGWS(uint _amount) external { require(isDebtor[msg.sender], "Not approved"); IGWSERC20(GWS).burnFrom(msg.sender, _amount); debtorBalance[msg.sender] = debtorBalance[msg.sender].sub(_amount); totalDebt = totalDebt.sub(_amount); emit RepayDebt(msg.sender, GWS, _amount, _amount); } /** @notice allow approved address to withdraw assets @param _token address @param _amount uint */ function manage(address _token, uint _amount) external { if (isLiquidityToken[_token]) { require(isLiquidityManager[msg.sender], "Not approved"); } else { require(isReserveManager[msg.sender], "Not approved"); } uint value = valueOf(_token, _amount); require(value <= excessReserves(), "Insufficient reserves"); totalReserves = totalReserves.sub(value); emit ReservesUpdated(totalReserves); IERC20(_token).safeTransfer(msg.sender, _amount); emit ReservesManaged(_token, _amount); } /** @notice send epoch reward to staking contract */ function mintRewards(address _recipient, uint _amount) external { require(isRewardManager[msg.sender], "Not approved"); require(_amount <= excessReserves(), "Insufficient reserves"); IERC20Mintable(GWS).mint(_recipient, _amount); emit RewardsMinted(msg.sender, _recipient, _amount); } /** @notice returns excess reserves not backing tokens @return uint */ function excessReserves() public view returns (uint) { return totalReserves.sub(IERC20(GWS).totalSupply().sub(totalDebt)); } /** @notice takes inventory of all tracked assets @notice always consolidate to recognized reserves before audit */ function auditReserves() external onlyManager() { uint reserves; for (uint i = 0; i < reserveTokens.length; i++) { reserves = reserves.add( valueOf(reserveTokens[i], IERC20(reserveTokens[i]).balanceOf(address(this))) ); } for (uint i = 0; i < liquidityTokens.length; i++) { reserves = reserves.add( valueOf(liquidityTokens[i], IERC20(liquidityTokens[i]).balanceOf(address(this))) ); } totalReserves = reserves; emit ReservesUpdated(reserves); emit ReservesAudited(reserves); } /** @notice returns GWS valuation of asset @param _token address @param _amount uint @return value_ uint */ function valueOf(address _token, uint _amount) public view returns (uint value_) { if (isReserveToken[_token]) { // convert amount to match GWS decimals value_ = _amount.mul(10 ** IERC20(GWS).decimals()).div(10 ** IERC20(_token).decimals()); } else if (isLiquidityToken[_token]) { value_ = IBondCalculator(bondCalculator[_token]).valuation(_token, _amount); } } /** @notice queue address to change boolean in mapping @param _managing MANAGING @param _address address @return bool */ function queue(MANAGING _managing, address _address) external onlyManager() returns (bool) { require(_address != address(0)); if (_managing == MANAGING.RESERVEDEPOSITOR) {// 0 reserveDepositorQueue[_address] = block.number.add(blocksNeededForQueue); } else if (_managing == MANAGING.RESERVESPENDER) {// 1 reserveSpenderQueue[_address] = block.number.add(blocksNeededForQueue); } else if (_managing == MANAGING.RESERVETOKEN) {// 2 reserveTokenQueue[_address] = block.number.add(blocksNeededForQueue); } else if (_managing == MANAGING.RESERVEMANAGER) {// 3 ReserveManagerQueue[_address] = block.number.add(blocksNeededForQueue.mul(2)); } else if (_managing == MANAGING.LIQUIDITYDEPOSITOR) {// 4 LiquidityDepositorQueue[_address] = block.number.add(blocksNeededForQueue); } else if (_managing == MANAGING.LIQUIDITYTOKEN) {// 5 LiquidityTokenQueue[_address] = block.number.add(blocksNeededForQueue); } else if (_managing == MANAGING.LIQUIDITYMANAGER) {// 6 LiquidityManagerQueue[_address] = block.number.add(blocksNeededForQueue.mul(2)); } else if (_managing == MANAGING.DEBTOR) {// 7 debtorQueue[_address] = block.number.add(blocksNeededForQueue); } else if (_managing == MANAGING.REWARDMANAGER) {// 8 rewardManagerQueue[_address] = block.number.add(blocksNeededForQueue); } else if (_managing == MANAGING.SGWS) {// 9 sGWSQueue = block.number.add(blocksNeededForQueue); } else return false; emit ChangeQueued(_managing, _address); return true; } /** @notice verify queue then set boolean in mapping @param _managing MANAGING @param _address address @param _calculator address @return bool */ function toggle(MANAGING _managing, address _address, address _calculator) external onlyManager() returns (bool) { require(_address != address(0)); bool result; if (_managing == MANAGING.RESERVEDEPOSITOR) {// 0 if (requirements(reserveDepositorQueue, isReserveDepositor, _address)) { reserveDepositorQueue[_address] = 0; if (!listContains(reserveDepositors, _address)) { reserveDepositors.push(_address); } } result = !isReserveDepositor[_address]; isReserveDepositor[_address] = result; } else if (_managing == MANAGING.RESERVESPENDER) {// 1 if (requirements(reserveSpenderQueue, isReserveSpender, _address)) { reserveSpenderQueue[_address] = 0; if (!listContains(reserveSpenders, _address)) { reserveSpenders.push(_address); } } result = !isReserveSpender[_address]; isReserveSpender[_address] = result; } else if (_managing == MANAGING.RESERVETOKEN) {// 2 if (requirements(reserveTokenQueue, isReserveToken, _address)) { reserveTokenQueue[_address] = 0; if (!listContains(reserveTokens, _address)) { reserveTokens.push(_address); } } result = !isReserveToken[_address]; isReserveToken[_address] = result; } else if (_managing == MANAGING.RESERVEMANAGER) {// 3 if (requirements(ReserveManagerQueue, isReserveManager, _address)) { reserveManagers.push(_address); ReserveManagerQueue[_address] = 0; if (!listContains(reserveManagers, _address)) { reserveManagers.push(_address); } } result = !isReserveManager[_address]; isReserveManager[_address] = result; } else if (_managing == MANAGING.LIQUIDITYDEPOSITOR) {// 4 if (requirements(LiquidityDepositorQueue, isLiquidityDepositor, _address)) { liquidityDepositors.push(_address); LiquidityDepositorQueue[_address] = 0; if (!listContains(liquidityDepositors, _address)) { liquidityDepositors.push(_address); } } result = !isLiquidityDepositor[_address]; isLiquidityDepositor[_address] = result; } else if (_managing == MANAGING.LIQUIDITYTOKEN) {// 5 if (requirements(LiquidityTokenQueue, isLiquidityToken, _address)) { LiquidityTokenQueue[_address] = 0; if (!listContains(liquidityTokens, _address)) { liquidityTokens.push(_address); } } result = !isLiquidityToken[_address]; isLiquidityToken[_address] = result; bondCalculator[_address] = _calculator; } else if (_managing == MANAGING.LIQUIDITYMANAGER) {// 6 if (requirements(LiquidityManagerQueue, isLiquidityManager, _address)) { LiquidityManagerQueue[_address] = 0; if (!listContains(liquidityManagers, _address)) { liquidityManagers.push(_address); } } result = !isLiquidityManager[_address]; isLiquidityManager[_address] = result; } else if (_managing == MANAGING.DEBTOR) {// 7 if (requirements(debtorQueue, isDebtor, _address)) { debtorQueue[_address] = 0; if (!listContains(debtors, _address)) { debtors.push(_address); } } result = !isDebtor[_address]; isDebtor[_address] = result; } else if (_managing == MANAGING.REWARDMANAGER) {// 8 if (requirements(rewardManagerQueue, isRewardManager, _address)) { rewardManagerQueue[_address] = 0; if (!listContains(rewardManagers, _address)) { rewardManagers.push(_address); } } result = !isRewardManager[_address]; isRewardManager[_address] = result; } else if (_managing == MANAGING.SGWS) {// 9 sGWSQueue = 0; sGWS = _address; result = true; } else return false; emit ChangeActivated(_managing, _address, result); return true; } /** @notice checks requirements and returns altered structs @param queue_ mapping( address => uint ) @param status_ mapping( address => bool ) @param _address address @return bool */ function requirements( mapping(address => uint) storage queue_, mapping(address => bool) storage status_, address _address ) internal view returns (bool) { if (!status_[_address]) { require(queue_[_address] != 0, "Must queue"); require(queue_[_address] <= block.number, "Queue not expired"); return true; } return false; } /** @notice checks array to ensure against duplicate @param _list address[] @param _token address @return bool */ function listContains(address[] storage _list, address _token) internal view returns (bool) { for (uint i = 0; i < _list.length; i++) { if (_list[i] == _token) { return true; } } return false; } }
Delays changes to mapping.
mapping(address => uint) public LiquidityTokenQueue;
1,402,076
[ 1, 6763, 87, 3478, 358, 2874, 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, 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, 2874, 12, 2867, 516, 2254, 13, 1071, 511, 18988, 24237, 1345, 3183, 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/42/0xcf64F81b71E864340e08D41B0e194Bc261eD28d7/sources/new1.sol
run bonus rewards calculations
uint256 totalMinersInPool = valueKeyCount(_poolID);
16,279,340
[ 1, 2681, 324, 22889, 283, 6397, 20882, 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, 3639, 2254, 5034, 2078, 2930, 414, 382, 2864, 273, 460, 653, 1380, 24899, 6011, 734, 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 ]
pragma solidity ^0.4.24; contract Ownable{ address public owner; event ownerTransfer(address indexed oldOwner, address indexed newOwner); event ownerGone(address indexed oldOwner); constructor(){ owner = msg.sender; } modifier onlyOwner(){ require(msg.sender == owner); _; } function changeOwner(address _newOwner) public onlyOwner{ require(_newOwner != address(0x0)); emit ownerTransfer(owner, _newOwner); owner = _newOwner; } } contract Haltable is Ownable{ bool public paused; event ContractPaused(address by); event ContractUnpaused(address by); /** * @dev Paused by default. */ constructor(){ paused = true; } function pause() public onlyOwner { paused = true; emit ContractPaused(owner); } function unpause() public onlyOwner { paused = false; emit ContractUnpaused(owner); } modifier stopOnPause(){ if(msg.sender != owner){ require(paused == false); } _; } } interface ABIO_Token { function owner() external returns (address); function transfer(address receiver, uint amount) external; function burnMyBalance() external; } interface ABIO_preICO{ function weiRaised() external returns (uint); function fundingGoal() external returns (uint); function extGoalReached() external returns (uint); } contract ABIO_BaseICO is Haltable{ mapping(address => uint256) ethBalances; uint public weiRaised;//total raised in wei uint public abioSold;//amount of ABIO sold uint public volume; //total amount of ABIO selling in this preICO uint public startDate; uint public length; uint public deadline; bool public restTokensBurned; uint public weiPerABIO; //how much wei one ABIO costs uint public minInvestment; uint public fundingGoal; bool public fundingGoalReached; address public treasury; ABIO_Token public abioToken; event ICOStart(uint volume, uint weiPerABIO, uint minInvestment); event SoftcapReached(address recipient, uint totalAmountRaised); event FundsReceived(address backer, uint amount); event FundsWithdrawn(address receiver, uint amount); event ChangeTreasury(address operator, address newTreasury); event PriceAdjust(address operator, uint multipliedBy ,uint newMin, uint newPrice); /** * @notice allows owner to change the treasury in case of hack/lost keys. * @dev Marked external because it is never called from this contract. */ function changeTreasury(address _newTreasury) external onlyOwner{ treasury = _newTreasury; emit ChangeTreasury(msg.sender, _newTreasury); } /** * @notice allows owner to adjust `minInvestment` and `weiPerABIO` in case of extreme jumps of Ether&#39;s dollar-value. * @param _multiplier Both `minInvestment` and `weiPerABIO` will be multiplied by `_multiplier`. It is supposed to be close to oldEthPrice/newEthPrice * @param _multiplier MULTIPLIER IS SUPPLIED AS PERCENTAGE */ function adjustPrice(uint _multiplier) external onlyOwner{ require(_multiplier < 400 && _multiplier > 25); minInvestment = minInvestment * _multiplier / 100; weiPerABIO = weiPerABIO * _multiplier / 100; emit PriceAdjust(msg.sender, _multiplier, minInvestment, weiPerABIO); } /** * @notice Called everytime we receive a contribution in ETH. * @dev Tokens are immediately transferred to the contributor, even if goal doesn&#39;t get reached. */ function () payable stopOnPause{ require(now < deadline); require(msg.value >= minInvestment); uint amount = msg.value; ethBalances[msg.sender] += amount; weiRaised += amount; if(!fundingGoalReached && weiRaised >= fundingGoal){goalReached();} uint ABIOAmount = amount / weiPerABIO ; abioToken.transfer(msg.sender, ABIOAmount); abioSold += ABIOAmount; emit FundsReceived(msg.sender, amount); } /** * @notice We implement tokenFallback in case someone decides to send us tokens or we want to increase ICO Volume. * @dev If someone sends random tokens transaction is reverted. * @dev If owner of token sends tokens, we accept them. * @dev Crowdsale opens once this contract gets the tokens. */ function tokenFallback(address _from, uint _value, bytes) external{ require(msg.sender == address(abioToken)); require(_from == abioToken.owner() || _from == owner); volume = _value; paused = false; deadline = now + length; emit ICOStart(_value, weiPerABIO, minInvestment); } /** * @notice Burns tokens leftover from an ICO round. * @dev This can be called by anyone after deadline since it&#39;s an essential and inevitable part. */ function burnRestTokens() afterDeadline{ require(!restTokensBurned); abioToken.burnMyBalance(); restTokensBurned = true; } function isRunning() view returns (bool){ return (now < deadline); } function goalReached() internal; modifier afterDeadline() { if (now >= deadline) _; } } contract ABIO_ICO is ABIO_BaseICO{ ABIO_preICO PICO; uint weiRaisedInPICO; uint abioSoldInPICO; event Prolonged(address oabiotor, uint newDeadline); bool didProlong; constructor(address _abioAddress, address _treasury, address _PICOAddr, uint _lenInMins,uint _minInvestment, uint _priceInWei){ abioToken = ABIO_Token(_abioAddress); treasury = _treasury; PICO = ABIO_preICO(_PICOAddr); weiRaisedInPICO = PICO.weiRaised(); fundingGoal = PICO.fundingGoal(); if (weiRaisedInPICO >= fundingGoal){ goalReached(); } minInvestment = _minInvestment; startDate = now; length = _lenInMins * 1 minutes; weiPerABIO = _priceInWei; fundingGoal = PICO.fundingGoal(); } /** * @notice a function that changes state if goal reached. If the PICO didn&#39;t reach goal, it reports back to it. */ function goalReached() internal { emit SoftcapReached(treasury, fundingGoal); fundingGoalReached = true; if (weiRaisedInPICO < fundingGoal){ PICO.extGoalReached(); } } /** * @notice Lets participants withdraw the funds if goal was missed. * @notice Lets treasury collect the funds if goal was reached. * @dev The contract is obligated to return the ETH to contributors if goal isn&#39;t reached, * so we have to wait until the end for a withdrawal. */ function safeWithdrawal() afterDeadline stopOnPause{ if (!fundingGoalReached) { uint amount = ethBalances[msg.sender]; ethBalances[msg.sender] = 0; if (amount > 0) { if (msg.sender.send(amount)) { emit FundsWithdrawn(msg.sender, amount); } else { ethBalances[msg.sender] = amount; } } } else if (fundingGoalReached) { require(treasury == msg.sender); if (treasury.send(weiRaised)) { emit FundsWithdrawn(treasury, weiRaised); } else if (treasury.send(address(this).balance)){ emit FundsWithdrawn(treasury, address(this).balance); } } } /** * @notice Is going to be called in an extreme case where we need to prolong the ICO (e.g. missed Softcap by a few ETH)/ * @dev It&#39;s only called once, has to be called at least 4 days before ICO end and prolongs the ICO for no more than 3 weeks. */ function prolong(uint _timeInMins) external onlyOwner{ require(!didProlong); require(now <= deadline - 4 days); uint t = _timeInMins * 1 minutes; require(t <= 3 weeks); deadline += t; length += t; didProlong = true; emit Prolonged(msg.sender, deadline); } }
* @notice allows owner to change the treasury in case of hack/lost keys. @dev Marked external because it is never called from this contract./
function changeTreasury(address _newTreasury) external onlyOwner{ treasury = _newTreasury; emit ChangeTreasury(msg.sender, _newTreasury); }
1,980,680
[ 1, 5965, 87, 3410, 358, 2549, 326, 9787, 345, 22498, 316, 648, 434, 11769, 19, 383, 334, 1311, 18, 225, 6622, 329, 3903, 2724, 518, 353, 5903, 2566, 628, 333, 6835, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 540, 445, 2549, 56, 266, 345, 22498, 12, 2867, 389, 2704, 56, 266, 345, 22498, 13, 3903, 1338, 5541, 95, 203, 2398, 9787, 345, 22498, 273, 389, 2704, 56, 266, 345, 22498, 31, 203, 2398, 3626, 7576, 56, 266, 345, 22498, 12, 3576, 18, 15330, 16, 389, 2704, 56, 266, 345, 22498, 1769, 203, 540, 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 ]
pragma solidity ^0.5.16; import "./SafeMath.sol"; /** * @title Logic for Rifi's JumpRateModel Contract. * @author Rifi (modified by Dharma Labs, refactored by Arr00) * @notice Version 2 modifies Version 1 by enabling updateable parameters. */ contract BaseJumpRateModel { using SafeMath for uint256; event NewInterestParams( uint256 baseRatePerBlock, uint256 lowerBaseRatePerBlock, uint256 multiplierPerBlock, uint256 jumpMultiplierPerBlock, uint256 kink, uint256 lowerKink ); /** * @notice The address of the owner, i.e. the Timelock contract, which can update parameters directly */ address public owner; /** * @notice The approximate number of blocks per year that is assumed by the interest rate model */ uint256 public constant blocksPerYear = 2102400; /** * @notice The multiplier of utilization rate that gives the slope of the interest rate */ uint256 public multiplierPerBlock; /** * @notice The base interest rate which is the y-intercept when utilization rate is 0 */ uint256 public baseRatePerBlock; /** * @notice The base interest rate which is the y-intercept when utilization rate is 0 */ uint256 public lowerBaseRatePerBlock; /** * @notice The multiplierPerBlock after hitting a specified utilization point */ uint256 public jumpMultiplierPerBlock; /** * @notice The utilization point at which the jump multiplier is applied */ uint256 public kink; /** * @notice The utilization point at which the jump multiplier is applied */ uint256 public lowerKink; /** * @notice Construct an interest rate model * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18) * @param lowerBaseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18) * @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18) * @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point * @param kink_ The utilization point at which the jump multiplier is applied * @param owner_ The address of the owner, i.e. the Timelock contract (which has the ability to update parameters directly) */ constructor( uint256 baseRatePerYear, uint256 lowerBaseRatePerYear, uint256 multiplierPerYear, uint256 jumpMultiplierPerYear, uint256 kink_, uint256 lowerKink_, address owner_ ) internal { owner = owner_; updateJumpRateModelInternal( baseRatePerYear, lowerBaseRatePerYear, multiplierPerYear, jumpMultiplierPerYear, kink_, lowerKink_ ); } /** * @notice Update the parameters of the interest rate model (only callable by owner, i.e. Timelock) * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18) * @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18) * @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point * @param kink_ The utilization point at which the jump multiplier is applied */ function updateJumpRateModel( uint256 baseRatePerYear, uint256 lowerBaseRatePerYear, uint256 multiplierPerYear, uint256 jumpMultiplierPerYear, uint256 kink_, uint256 lowerKink_ ) external { require(msg.sender == owner, "only the owner may call this function."); updateJumpRateModelInternal( baseRatePerYear, lowerBaseRatePerYear, multiplierPerYear, jumpMultiplierPerYear, kink_, lowerKink_ ); } /** * @notice Calculates the utilization rate of the market: `borrows / (cash + borrows - reserves)` * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market (currently unused) * @return The utilization rate as a mantissa between [0, 1e18] */ function utilizationRate( uint256 cash, uint256 borrows, uint256 reserves ) public pure returns (uint256) { // Utilization rate is 0 when there are no borrows if (borrows == 0) { return 0; } return borrows.mul(1e18).div(cash.add(borrows).sub(reserves)); } /** * @notice Calculates the current borrow rate per block, with the error code expected by the market * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market * @return The borrow rate percentage per block as a mantissa (scaled by 1e18) */ function getBorrowRateInternal( uint256 cash, uint256 borrows, uint256 reserves ) internal view returns (uint256) { uint256 util = utilizationRate(cash, borrows, reserves); // TODO: change `multiplierPerBlock` if (util <= lowerKink) { uint256 baseChange = (baseRatePerBlock.sub(lowerBaseRatePerBlock)).div(lowerKink); uint256 lowerMultiplierPerBlock = multiplierPerBlock.add(baseChange); return util.mul(lowerMultiplierPerBlock).div(1e18).add( lowerBaseRatePerBlock ); } if (util <= kink) { return util.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock); } else { uint256 normalRate = kink.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock); uint256 excessUtil = util.sub(kink); return excessUtil.mul(jumpMultiplierPerBlock).div(1e18).add( normalRate ); } } /** * @notice Calculates the current supply rate per block * @param cash The amount of cash in the market * @param borrows The amount of borrows in the market * @param reserves The amount of reserves in the market * @param reserveFactorMantissa The current reserve factor for the market * @return The supply rate percentage per block as a mantissa (scaled by 1e18) */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa ) public view returns (uint256) { uint256 oneMinusReserveFactor = uint256(1e18).sub(reserveFactorMantissa); uint256 borrowRate = getBorrowRateInternal(cash, borrows, reserves); uint256 rateToPool = borrowRate.mul(oneMinusReserveFactor).div(1e18); return utilizationRate(cash, borrows, reserves).mul(rateToPool).div(1e18); } /** * @notice Internal function to update the parameters of the interest rate model * @param lowerBaseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18) * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18) * @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18) * @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point * @param kink_ The utilization point at which the jump multiplier is applied */ function updateJumpRateModelInternal( uint256 baseRatePerYear, uint256 lowerBaseRatePerYear, uint256 multiplierPerYear, uint256 jumpMultiplierPerYear, uint256 kink_, uint256 lowerKink_ ) internal { lowerBaseRatePerBlock = lowerBaseRatePerYear.div(blocksPerYear); baseRatePerBlock = baseRatePerYear.div(blocksPerYear); multiplierPerBlock = (multiplierPerYear.mul(1e18)).div( blocksPerYear.mul(kink_) ); jumpMultiplierPerBlock = jumpMultiplierPerYear.div(blocksPerYear); kink = kink_; lowerKink = lowerKink_; emit NewInterestParams( baseRatePerBlock, lowerBaseRatePerBlock, multiplierPerBlock, jumpMultiplierPerBlock, kink, lowerKink ); } }
* @notice Calculates the current borrow rate per block, with the error code expected by the market @param cash The amount of cash in the market @param borrows The amount of borrows in the market @param reserves The amount of reserves in the market @return The borrow rate percentage per block as a mantissa (scaled by 1e18)/ TODO: change `multiplierPerBlock`
function getBorrowRateInternal( uint256 cash, uint256 borrows, uint256 reserves ) internal view returns (uint256) { uint256 util = utilizationRate(cash, borrows, reserves); if (util <= lowerKink) { uint256 baseChange = (baseRatePerBlock.sub(lowerBaseRatePerBlock)).div(lowerKink); uint256 lowerMultiplierPerBlock = multiplierPerBlock.add(baseChange); return util.mul(lowerMultiplierPerBlock).div(1e18).add( lowerBaseRatePerBlock ); } if (util <= kink) { return util.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock); uint256 normalRate = kink.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock); uint256 excessUtil = util.sub(kink); return excessUtil.mul(jumpMultiplierPerBlock).div(1e18).add( normalRate ); } }
965,578
[ 1, 10587, 326, 783, 29759, 4993, 1534, 1203, 16, 598, 326, 555, 981, 2665, 635, 326, 13667, 225, 276, 961, 1021, 3844, 434, 276, 961, 316, 326, 13667, 225, 324, 280, 3870, 1021, 3844, 434, 324, 280, 3870, 316, 326, 13667, 225, 400, 264, 3324, 1021, 3844, 434, 400, 264, 3324, 316, 326, 13667, 327, 1021, 29759, 4993, 11622, 1534, 1203, 487, 279, 31340, 261, 20665, 635, 404, 73, 2643, 13176, 2660, 30, 2549, 1375, 20538, 2173, 1768, 68, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 2882, 15318, 4727, 3061, 12, 203, 3639, 2254, 5034, 276, 961, 16, 203, 3639, 2254, 5034, 324, 280, 3870, 16, 203, 3639, 2254, 5034, 400, 264, 3324, 203, 565, 262, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 1709, 273, 1709, 1588, 4727, 12, 71, 961, 16, 324, 280, 3870, 16, 400, 264, 3324, 1769, 203, 203, 3639, 309, 261, 1367, 1648, 2612, 47, 754, 13, 288, 203, 5411, 2254, 5034, 1026, 3043, 273, 203, 7734, 261, 1969, 4727, 2173, 1768, 18, 1717, 12, 8167, 2171, 4727, 2173, 1768, 13, 2934, 2892, 12, 8167, 47, 754, 1769, 203, 5411, 2254, 5034, 2612, 23365, 2173, 1768, 273, 203, 7734, 15027, 2173, 1768, 18, 1289, 12, 1969, 3043, 1769, 203, 5411, 327, 203, 7734, 1709, 18, 16411, 12, 8167, 23365, 2173, 1768, 2934, 2892, 12, 21, 73, 2643, 2934, 1289, 12, 203, 10792, 2612, 2171, 4727, 2173, 1768, 203, 7734, 11272, 203, 3639, 289, 203, 203, 3639, 309, 261, 1367, 1648, 417, 754, 13, 288, 203, 5411, 327, 1709, 18, 16411, 12, 20538, 2173, 1768, 2934, 2892, 12, 21, 73, 2643, 2934, 1289, 12, 1969, 4727, 2173, 1768, 1769, 203, 5411, 2254, 5034, 2212, 4727, 273, 203, 7734, 417, 754, 18, 16411, 12, 20538, 2173, 1768, 2934, 2892, 12, 21, 73, 2643, 2934, 1289, 12, 1969, 4727, 2173, 1768, 1769, 203, 5411, 2254, 5034, 23183, 1304, 273, 1709, 18, 1717, 12, 79, 754, 1769, 203, 5411, 327, 203, 7734, 23183, 1304, 18, 16411, 12, 24574, 23365, 2173, 1768, 2934, 2892, 2 ]
./full_match/80001/0xc3565c660DF86E6D31B96A3FBfBE6F37A659D238/sources/contracts/core/NFTLottery.sol
============================================================= Modifiers =============================================================
contract NFTLottery is INFTLottery, PermissionsEnumerable, ReentrancyGuard, ProtocolFee { using SafeERC20 for IERC20; using SafeMath for uint256; using FixedPointMathLib for uint256; uint256 public nextLotteryId; FundVault fundVault; pragma solidity 0.8.19; modifier onlyLotteryOwnerOrAdmin(uint256 lotteryId) { require(msg.sender == lotteries[lotteryId].owner || hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Only the lottery owner or admin can open the lottery"); _; } modifier onlyLotteryOwner(uint256 lotteryId) { require(msg.sender == lotteries[lotteryId].owner, "Only the lottery owner can open the lottery"); _; } modifier whenLotteryPending(uint256 lotteryId) { require(lotteries[lotteryId].state == LotteryState.Pending, "Lottery is not pending"); _; } modifier whenLotteryOpen(uint256 lotteryId) { require(lotteries[lotteryId].state == LotteryState.Open, "Lottery is not running"); _; } modifier whenLotteryOpenOrPending(uint256 lotteryId) { require(lotteries[lotteryId].state == LotteryState.Pending || lotteries[lotteryId].state == LotteryState.Open, "Lottery is not pending nor open"); _; } modifier nonExpired(uint256 lotteryId) { require(lotteries[lotteryId].endTimestamp == 0 || block.timestamp < lotteries[lotteryId].endTimestamp, "Lottery time end"); _; } constructor(address fundVaultAddress) { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); nextLotteryId = 1; addFeeInfo(0, Fee(FeeType.Bps, 500, 0, msg.sender)); addFeeInfo(1, Fee(FeeType.Bps, 300, 0, msg.sender)); fundVault = FundVault(fundVaultAddress); } function updateFundVault(address newFundVaultAddress) external onlyRole(DEFAULT_ADMIN_ROLE) { fundVault = FundVault(newFundVaultAddress); } function createLottery(Lottery calldata lotteryData) external virtual override { require(lotteryData.minTickets > 0, "Min tickets Zero"); uint256 lotteryId = nextLotteryId++; lotteries[lotteryId] = Lottery({ owner: lotteryData.owner, salesRecipient: lotteryData.salesRecipient, nftAddress: lotteryData.nftAddress, tokenId: lotteryData.tokenId, ticketCurrency: lotteryData.ticketCurrency, ticketCost: lotteryData.ticketCost, minTickets: lotteryData.minTickets, startTimestamp: 0, endTimestamp: 0, state: LotteryState.Pending, winner: address(0) }); IERC721 nftContract = IERC721(lotteryData.nftAddress); nftContract.safeTransferFrom(msg.sender, address(this), lotteryData.tokenId); emit LotteryCreated(lotteryId, lotteryData); } function createLottery(Lottery calldata lotteryData) external virtual override { require(lotteryData.minTickets > 0, "Min tickets Zero"); uint256 lotteryId = nextLotteryId++; lotteries[lotteryId] = Lottery({ owner: lotteryData.owner, salesRecipient: lotteryData.salesRecipient, nftAddress: lotteryData.nftAddress, tokenId: lotteryData.tokenId, ticketCurrency: lotteryData.ticketCurrency, ticketCost: lotteryData.ticketCost, minTickets: lotteryData.minTickets, startTimestamp: 0, endTimestamp: 0, state: LotteryState.Pending, winner: address(0) }); IERC721 nftContract = IERC721(lotteryData.nftAddress); nftContract.safeTransferFrom(msg.sender, address(this), lotteryData.tokenId); emit LotteryCreated(lotteryId, lotteryData); } function openLottery(uint256 lotteryId) external virtual override onlyLotteryOwner(lotteryId) whenLotteryPending(lotteryId) { lotteries[lotteryId].state = LotteryState.Open; lotteries[lotteryId].startTimestamp = block.timestamp; lotteries[lotteryId].endTimestamp = block.timestamp + 7 days; emit LotteryOpened(lotteryId, lotteries[lotteryId]); } function closeLottery(uint256 lotteryId) external virtual override onlyLotteryOwnerOrAdmin(lotteryId) whenLotteryOpenOrPending(lotteryId) { lotteries[lotteryId].state = LotteryState.Closed; lotteries[lotteryId].endTimestamp = block.timestamp; if (players[lotteryId].totalTicketsSold < lotteries[lotteryId].minTickets) { _refund(lotteryId); } else if (players[lotteryId].totalTicketsSold < 1) { _refundNFT(lotteryId); } else { _pickWinner(lotteryId); } emit LotteryClosed(lotteryId, lotteries[lotteryId]); } function closeLottery(uint256 lotteryId) external virtual override onlyLotteryOwnerOrAdmin(lotteryId) whenLotteryOpenOrPending(lotteryId) { lotteries[lotteryId].state = LotteryState.Closed; lotteries[lotteryId].endTimestamp = block.timestamp; if (players[lotteryId].totalTicketsSold < lotteries[lotteryId].minTickets) { _refund(lotteryId); } else if (players[lotteryId].totalTicketsSold < 1) { _refundNFT(lotteryId); } else { _pickWinner(lotteryId); } emit LotteryClosed(lotteryId, lotteries[lotteryId]); } function closeLottery(uint256 lotteryId) external virtual override onlyLotteryOwnerOrAdmin(lotteryId) whenLotteryOpenOrPending(lotteryId) { lotteries[lotteryId].state = LotteryState.Closed; lotteries[lotteryId].endTimestamp = block.timestamp; if (players[lotteryId].totalTicketsSold < lotteries[lotteryId].minTickets) { _refund(lotteryId); } else if (players[lotteryId].totalTicketsSold < 1) { _refundNFT(lotteryId); } else { _pickWinner(lotteryId); } emit LotteryClosed(lotteryId, lotteries[lotteryId]); } function closeLottery(uint256 lotteryId) external virtual override onlyLotteryOwnerOrAdmin(lotteryId) whenLotteryOpenOrPending(lotteryId) { lotteries[lotteryId].state = LotteryState.Closed; lotteries[lotteryId].endTimestamp = block.timestamp; if (players[lotteryId].totalTicketsSold < lotteries[lotteryId].minTickets) { _refund(lotteryId); } else if (players[lotteryId].totalTicketsSold < 1) { _refundNFT(lotteryId); } else { _pickWinner(lotteryId); } emit LotteryClosed(lotteryId, lotteries[lotteryId]); } function extendEndtime(uint256 lotteryId) external onlyLotteryOwnerOrAdmin(lotteryId) whenLotteryOpenOrPending(lotteryId) nonExpired(lotteryId) { lotteries[lotteryId].endTimestamp = block.timestamp + 7 days; } function buyTicket(uint256 lotteryId, uint256 numberOfTickets) public virtual override whenLotteryOpen(lotteryId) nonExpired(lotteryId) nonReentrant { IERC20(lotteries[lotteryId].ticketCurrency).safeTransferFrom(msg.sender, address(this), numberOfTickets * lotteries[lotteryId].ticketCost); players[lotteryId].totalTicketsSold += numberOfTickets; players[lotteryId].tickets[msg.sender] += numberOfTickets; if (!isPlayerOf(lotteryId, msg.sender)) players[lotteryId].playerWallets.push(msg.sender); emit LotteryTicketBought(lotteryId, msg.sender, numberOfTickets); } function _refund(uint256 lotteryId) internal virtual { Lottery memory lottery = lotteries[lotteryId]; LotteryPlayers storage lotteryPlayers = players[lotteryId]; for (uint256 i = 0; i < lotteryPlayers.playerWallets.length; i++) { address player = lotteryPlayers.playerWallets[i]; uint256 tickets = lotteryPlayers.tickets[player]; uint256 refundAmount = tickets.mul(lottery.ticketCost); refunds[lotteryId][player] = refundAmount; lotteryPlayers.tickets[player] = 0; emit RefundCalculated(lotteryId, player, refundAmount); } emit LotteryRefund(lotteryId, lotteries[lotteryId]); } function _refund(uint256 lotteryId) internal virtual { Lottery memory lottery = lotteries[lotteryId]; LotteryPlayers storage lotteryPlayers = players[lotteryId]; for (uint256 i = 0; i < lotteryPlayers.playerWallets.length; i++) { address player = lotteryPlayers.playerWallets[i]; uint256 tickets = lotteryPlayers.tickets[player]; uint256 refundAmount = tickets.mul(lottery.ticketCost); refunds[lotteryId][player] = refundAmount; lotteryPlayers.tickets[player] = 0; emit RefundCalculated(lotteryId, player, refundAmount); } emit LotteryRefund(lotteryId, lotteries[lotteryId]); } _refundNFT(lotteryId); function _refundNFT(uint256 lotteryId) internal virtual { IERC721 nftContract = IERC721(lotteries[lotteryId].nftAddress); nftContract.safeTransferFrom(address(this), lotteries[lotteryId].owner, lotteries[lotteryId].tokenId); } function withdrawRefund(uint256 lotteryId) external { uint256 refundAmount = refunds[lotteryId][msg.sender]; require(refundAmount > 0, "No refund available"); Lottery memory lottery = lotteries[lotteryId]; IERC20 token = IERC20(lottery.ticketCurrency); token.safeTransfer(msg.sender, refundAmount); refunds[lotteryId][msg.sender] = 0; } function _pickWinner(uint256 lotteryId) internal virtual { Lottery memory lottery = lotteries[lotteryId]; IERC721 nftContract = IERC721(lottery.nftAddress); address winner = _randomPlayer(lotteryId); lotteries[lotteryId].winner = winner; emit LotteryWinner(lotteryId, winner, lottery); nftContract.safeTransferFrom(address(this), winner, lottery.tokenId); IERC20 token = IERC20(lottery.ticketCurrency); uint256 minTicketSales = lotteries[lotteryId].minTickets * lotteries[lotteryId].ticketCost; uint256 minSalesFee = _chargeFee(token, 0, minTicketSales); token.safeTransfer(lottery.salesRecipient, minTicketSales.sub(minSalesFee)); uint256 numberOfOversoldTickets = players[lotteryId].totalTicketsSold - lotteries[lotteryId].minTickets; if (numberOfOversoldTickets > 0) { uint256 overSales = numberOfOversoldTickets * lotteries[lotteryId].ticketCost; uint256 overSalesFee = _chargeFee(token, 1, overSales); uint256 totalOverSalesDistribution = overSales.sub(overSalesFee); uint256 toVault = totalOverSalesDistribution.mulDivDown(fundBps, MAX_BPS); token.safeTransfer(address(fundVault), toVault); token.safeTransfer(winner, totalOverSalesDistribution.sub(toVault)); } lotteries[lotteryId].state = LotteryState.Closed; } function _pickWinner(uint256 lotteryId) internal virtual { Lottery memory lottery = lotteries[lotteryId]; IERC721 nftContract = IERC721(lottery.nftAddress); address winner = _randomPlayer(lotteryId); lotteries[lotteryId].winner = winner; emit LotteryWinner(lotteryId, winner, lottery); nftContract.safeTransferFrom(address(this), winner, lottery.tokenId); IERC20 token = IERC20(lottery.ticketCurrency); uint256 minTicketSales = lotteries[lotteryId].minTickets * lotteries[lotteryId].ticketCost; uint256 minSalesFee = _chargeFee(token, 0, minTicketSales); token.safeTransfer(lottery.salesRecipient, minTicketSales.sub(minSalesFee)); uint256 numberOfOversoldTickets = players[lotteryId].totalTicketsSold - lotteries[lotteryId].minTickets; if (numberOfOversoldTickets > 0) { uint256 overSales = numberOfOversoldTickets * lotteries[lotteryId].ticketCost; uint256 overSalesFee = _chargeFee(token, 1, overSales); uint256 totalOverSalesDistribution = overSales.sub(overSalesFee); uint256 toVault = totalOverSalesDistribution.mulDivDown(fundBps, MAX_BPS); token.safeTransfer(address(fundVault), toVault); token.safeTransfer(winner, totalOverSalesDistribution.sub(toVault)); } lotteries[lotteryId].state = LotteryState.Closed; } function _randomPlayer(uint256 lotteryId) internal virtual returns (address) { uint256 totalTickets = players[lotteryId].totalTicketsSold; uint256 randomNumber = uint256(keccak256(abi.encodePacked(block.prevrandao, block.timestamp, totalTickets))) % totalTickets; for (uint256 i = 0; i < players[lotteryId].playerWallets.length; i++) { address player = players[lotteryId].playerWallets[i]; uint256 tickets = players[lotteryId].tickets[player]; if (randomNumber < tickets) { return player; } } return players[lotteryId].playerWallets[players[lotteryId].playerWallets.length - 1]; } function _randomPlayer(uint256 lotteryId) internal virtual returns (address) { uint256 totalTickets = players[lotteryId].totalTicketsSold; uint256 randomNumber = uint256(keccak256(abi.encodePacked(block.prevrandao, block.timestamp, totalTickets))) % totalTickets; for (uint256 i = 0; i < players[lotteryId].playerWallets.length; i++) { address player = players[lotteryId].playerWallets[i]; uint256 tickets = players[lotteryId].tickets[player]; if (randomNumber < tickets) { return player; } } return players[lotteryId].playerWallets[players[lotteryId].playerWallets.length - 1]; } function _randomPlayer(uint256 lotteryId) internal virtual returns (address) { uint256 totalTickets = players[lotteryId].totalTicketsSold; uint256 randomNumber = uint256(keccak256(abi.encodePacked(block.prevrandao, block.timestamp, totalTickets))) % totalTickets; for (uint256 i = 0; i < players[lotteryId].playerWallets.length; i++) { address player = players[lotteryId].playerWallets[i]; uint256 tickets = players[lotteryId].tickets[player]; if (randomNumber < tickets) { return player; } } return players[lotteryId].playerWallets[players[lotteryId].playerWallets.length - 1]; } randomNumber -= tickets; function getTotalTicketsSold(uint256 lotteryId) external view returns (uint256) { return players[lotteryId].totalTicketsSold; } function getPlayerWallets(uint256 lotteryId) external view returns (address[] memory) { return players[lotteryId].playerWallets; } function getTickets(uint256 lotteryId, address player) external view returns (uint256) { return players[lotteryId].tickets[player]; } function isPlayerOf(uint256 lotteryId, address participant) private view returns (bool) { for (uint256 i = 0; i < players[lotteryId].playerWallets.length; i++) { if (players[lotteryId].playerWallets[i] == participant) { return true; } } return false; } function isPlayerOf(uint256 lotteryId, address participant) private view returns (bool) { for (uint256 i = 0; i < players[lotteryId].playerWallets.length; i++) { if (players[lotteryId].playerWallets[i] == participant) { return true; } } return false; } function isPlayerOf(uint256 lotteryId, address participant) private view returns (bool) { for (uint256 i = 0; i < players[lotteryId].playerWallets.length; i++) { if (players[lotteryId].playerWallets[i] == participant) { return true; } } return false; } function _canSetFeeInfo() internal view virtual override returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } function onERC721Received(address, address, uint256, bytes calldata) external pure override returns(bytes4) { return this.onERC721Received.selector; } }
874,949
[ 1, 20775, 14468, 33, 10792, 3431, 3383, 422, 20775, 1432, 12275, 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, 16351, 423, 4464, 48, 352, 387, 93, 353, 2120, 4464, 48, 352, 387, 93, 16, 15684, 3572, 25121, 16, 868, 8230, 12514, 16709, 16, 4547, 14667, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 15038, 2148, 10477, 5664, 364, 2254, 5034, 31, 203, 203, 565, 2254, 5034, 1071, 1024, 48, 352, 387, 93, 548, 31, 203, 377, 203, 203, 565, 478, 1074, 12003, 284, 1074, 12003, 31, 203, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 3657, 31, 203, 565, 9606, 1338, 48, 352, 387, 93, 5541, 1162, 4446, 12, 11890, 5034, 17417, 387, 93, 548, 13, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 17417, 387, 606, 63, 23372, 387, 93, 548, 8009, 8443, 747, 28335, 12, 5280, 67, 15468, 67, 16256, 16, 1234, 18, 15330, 3631, 315, 3386, 326, 17417, 387, 93, 3410, 578, 3981, 848, 1696, 326, 17417, 387, 93, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 48, 352, 387, 93, 5541, 12, 11890, 5034, 17417, 387, 93, 548, 13, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 17417, 387, 606, 63, 23372, 387, 93, 548, 8009, 8443, 16, 315, 3386, 326, 17417, 387, 93, 3410, 848, 1696, 326, 17417, 387, 93, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1347, 48, 352, 387, 93, 8579, 12, 11890, 5034, 17417, 387, 93, 548, 13, 288, 203, 3639, 2583, 12, 23372, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-08-26 */ pragma solidity ^0.5.16; // Copied from compound/EIP20Interface /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // Copied from compound/EIP20NonStandardInterface /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external; /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // Copied from Compound/ExponentialNoError /** * @title Exponential module for storing fixed-precision decimals * @author DeFil * @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 ExponentialNoError { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } interface Distributor { // The asset to be distributed function asset() external view returns (address); // Return the accrued amount of account based on stored data function accruedStored(address account) external view returns (uint); // Accrue and distribute for caller, but not actually transfer assets to the caller // returns the new accrued amount function accrue() external returns (uint); // Claim asset, transfer the given amount assets to receiver function claim(address receiver, uint amount) external returns (uint); } contract Redistributor is Distributor, ExponentialNoError { /** * @notice The superior Distributor contract */ Distributor public superior; // The accrued amount of this address in superior Distributor uint public superiorAccruedAmount; // The initial accrual index uint internal constant initialAccruedIndex = 1e36; // The last accrued block number uint public accrualBlockNumber; // The last accrued index uint public globalAccruedIndex; // Total count of shares. uint internal totalShares; struct AccountState { /// @notice The share of account uint share; // The last accrued index of account uint accruedIndex; /// @notice The accrued but not yet transferred to account uint accruedAmount; } // The AccountState for each account mapping(address => AccountState) internal accountStates; /*** Events ***/ // Emitted when dfl is accrued event Accrued(uint amount, uint globalAccruedIndex); // Emitted when distribute to a account event Distributed(address account, uint amount, uint accruedIndex); // Emitted when account claims asset event Claimed(address account, address receiver, uint amount); // Emitted when account transfer asset event Transferred(address from, address to, uint amount); constructor(Distributor superior_) public { // set superior superior = superior_; // init accrued index globalAccruedIndex = initialAccruedIndex; } function asset() external view returns (address) { return superior.asset(); } // Return the accrued amount of account based on stored data function accruedStored(address account) external view returns(uint) { uint storedGlobalAccruedIndex; if (totalShares == 0) { storedGlobalAccruedIndex = globalAccruedIndex; } else { uint superiorAccruedStored = superior.accruedStored(address(this)); uint delta = sub_(superiorAccruedStored, superiorAccruedAmount); Double memory ratio = fraction(delta, totalShares); Double memory doubleGlobalAccruedIndex = add_(Double({mantissa: globalAccruedIndex}), ratio); storedGlobalAccruedIndex = doubleGlobalAccruedIndex.mantissa; } (, uint instantAccountAccruedAmount) = accruedStoredInternal(account, storedGlobalAccruedIndex); return instantAccountAccruedAmount; } // Return the accrued amount of account based on stored data function accruedStoredInternal(address account, uint withGlobalAccruedIndex) internal view returns(uint, uint) { AccountState memory state = accountStates[account]; Double memory doubleGlobalAccruedIndex = Double({mantissa: withGlobalAccruedIndex}); Double memory doubleAccountAccruedIndex = Double({mantissa: state.accruedIndex}); if (doubleAccountAccruedIndex.mantissa == 0 && doubleGlobalAccruedIndex.mantissa > 0) { doubleAccountAccruedIndex.mantissa = initialAccruedIndex; } Double memory deltaIndex = sub_(doubleGlobalAccruedIndex, doubleAccountAccruedIndex); uint delta = mul_(state.share, deltaIndex); return (delta, add_(state.accruedAmount, delta)); } function accrueInternal() internal { uint blockNumber = getBlockNumber(); if (accrualBlockNumber == blockNumber) { return; } uint newSuperiorAccruedAmount = superior.accrue(); if (totalShares == 0) { accrualBlockNumber = blockNumber; return; } uint delta = sub_(newSuperiorAccruedAmount, superiorAccruedAmount); Double memory ratio = fraction(delta, totalShares); Double memory doubleAccruedIndex = add_(Double({mantissa: globalAccruedIndex}), ratio); // update globalAccruedIndex globalAccruedIndex = doubleAccruedIndex.mantissa; superiorAccruedAmount = newSuperiorAccruedAmount; accrualBlockNumber = blockNumber; emit Accrued(delta, doubleAccruedIndex.mantissa); } /** * @notice accrue and returns accrued stored of msg.sender */ function accrue() external returns (uint) { accrueInternal(); (, uint instantAccountAccruedAmount) = accruedStoredInternal(msg.sender, globalAccruedIndex); return instantAccountAccruedAmount; } function distributeInternal(address account) internal { (uint delta, uint instantAccruedAmount) = accruedStoredInternal(account, globalAccruedIndex); AccountState storage state = accountStates[account]; state.accruedIndex = globalAccruedIndex; state.accruedAmount = instantAccruedAmount; // emit Distributed event emit Distributed(account, delta, globalAccruedIndex); } function claim(address receiver, uint amount) external returns (uint) { address account = msg.sender; // keep fresh accrueInternal(); distributeInternal(account); AccountState storage state = accountStates[account]; require(amount <= state.accruedAmount, "claim: insufficient value"); // claim from superior require(superior.claim(receiver, amount) == amount, "claim: amount mismatch"); // update storage state.accruedAmount = sub_(state.accruedAmount, amount); superiorAccruedAmount = sub_(superiorAccruedAmount, amount); emit Claimed(account, receiver, amount); return amount; } function claimAll() external { address account = msg.sender; // accrue and distribute accrueInternal(); distributeInternal(account); AccountState storage state = accountStates[account]; uint amount = state.accruedAmount; // claim from superior require(superior.claim(account, amount) == amount, "claim: amount mismatch"); // update storage state.accruedAmount = 0; superiorAccruedAmount = sub_(superiorAccruedAmount, amount); emit Claimed(account, account, amount); } function transfer(address to, uint amount) external { address from = msg.sender; // keep fresh accrueInternal(); distributeInternal(from); AccountState storage fromState = accountStates[from]; uint actualAmount = amount; if (actualAmount == 0) { actualAmount = fromState.accruedAmount; } require(fromState.accruedAmount >= actualAmount, "transfer: insufficient value"); AccountState storage toState = accountStates[to]; // update storage fromState.accruedAmount = sub_(fromState.accruedAmount, actualAmount); toState.accruedAmount = add_(toState.accruedAmount, actualAmount); emit Transferred(from, to, actualAmount); } function getBlockNumber() public view returns (uint) { return block.number; } } contract Staking is Redistributor { // The token to deposit address public property; /*** Events ***/ // Event emitted when new property tokens is deposited event Deposit(address account, uint amount); // Event emitted when new property tokens is withdrawed event Withdraw(address account, uint amount); constructor(address property_, Distributor superior_) Redistributor(superior_) public { property = property_; } function totalDeposits() external view returns (uint) { return totalShares; } function accountState(address account) external view returns (uint, uint, uint) { AccountState memory state = accountStates[account]; return (state.share, state.accruedIndex, state.accruedAmount); } // Deposit property tokens function deposit(uint amount) external returns (uint) { address account = msg.sender; // accrue & distribute accrueInternal(); distributeInternal(account); // transfer property token in uint actualAmount = doTransferIn(account, amount); // update storage AccountState storage state = accountStates[account]; totalShares = add_(totalShares, actualAmount); state.share = add_(state.share, actualAmount); emit Deposit(account, actualAmount); return actualAmount; } // Withdraw property tokens function withdraw(uint amount) external returns (uint) { address account = msg.sender; AccountState storage state = accountStates[account]; require(state.share >= amount, "withdraw: insufficient value"); // accrue & distribute accrueInternal(); distributeInternal(account); // decrease total deposits totalShares = sub_(totalShares, amount); state.share = sub_(state.share, amount); // transfer property tokens back to account doTransferOut(account, amount); emit Withdraw(account, amount); return amount; } /*** Safe Token ***/ /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address from, uint amount) internal returns (uint) { EIP20NonStandardInterface token = EIP20NonStandardInterface(property); uint balanceBefore = EIP20Interface(property).balanceOf(address(this)); token.transferFrom(from, address(this), amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_IN_FAILED"); // Calculate the amount that was *actually* transferred uint balanceAfter = EIP20Interface(property).balanceOf(address(this)); require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW"); return balanceAfter - balanceBefore; // underflow already checked above, just subtract } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address to, uint amount) internal { EIP20NonStandardInterface token = EIP20NonStandardInterface(property); token.transfer(to, amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_OUT_FAILED"); } }
* @notice accrue and returns accrued stored of msg.sender/
function accrue() external returns (uint) { accrueInternal(); (, uint instantAccountAccruedAmount) = accruedStoredInternal(msg.sender, globalAccruedIndex); return instantAccountAccruedAmount; }
2,405,847
[ 1, 8981, 86, 344, 471, 1135, 4078, 86, 5957, 4041, 434, 1234, 18, 15330, 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 ]
[ 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, 4078, 86, 344, 1435, 3903, 1135, 261, 11890, 13, 288, 203, 3639, 4078, 86, 344, 3061, 5621, 203, 203, 3639, 261, 16, 2254, 5934, 3032, 8973, 86, 5957, 6275, 13, 273, 4078, 86, 5957, 18005, 3061, 12, 3576, 18, 15330, 16, 2552, 8973, 86, 5957, 1016, 1769, 203, 3639, 327, 5934, 3032, 8973, 86, 5957, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/82/0x6e0A51cc2Ef554EE31dcF5c1362772616db03741/sources/versions/meter/2/citiesUniversity.sol
File: contracts/tokenController.sol
contract TokenController is Context, Initializable, AccessControl { bytes32 public constant CONNECTION = keccak256("CONNECTION"); bytes32 public constant ROLE_ADMIN = keccak256("ROLE_ADMIN"); string public constant INVALID_ROLE = "TC: Invalid Role"; string public constant INVALID_ADDRESS = "TC: Invalid Address"; string public constant INVALID_TOKENS = "TC: Invalid Amount of tokens"; string public constant INVALID_FEES = "TC: Invalid fees payment"; string public constant INVALID_PAYMENT = "TC: Invalid payment"; string public constant BLACKLIST = "TC: You are in blacklist"; mapping(address => bool) private blacklist; uint8 public constant CREATOR_FEE = 5; ERC20 private token; address public creator; function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } pragma solidity ^0.8.0; function initialize(ERC20 _token) public initializer { _setupRole(ROLE_ADMIN, _msgSender()); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); creator = _msgSender(); token = _token; } function addConnectionContract(address connection) public onlyRole(ROLE_ADMIN) { grantRole(CONNECTION, connection); } function sendTokens(address to, uint256 amount) public onlyRole(CONNECTION) { require(!blacklist[to], BLACKLIST); require(token.balanceOf(address(this)) > amount, INVALID_TOKENS); token.transfer(creator, (amount * CREATOR_FEE) / 100); token.transfer(to, (amount * (100 - CREATOR_FEE)) / 100); } function changeBlackListState(address bad, bool state) public onlyRole(ROLE_ADMIN) { blacklist[bad] = state; } }
16,896,894
[ 1, 812, 30, 20092, 19, 2316, 2933, 18, 18281, 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, 16351, 3155, 2933, 353, 1772, 16, 10188, 6934, 16, 24349, 288, 203, 565, 1731, 1578, 1071, 5381, 20695, 273, 417, 24410, 581, 5034, 2932, 15461, 8863, 203, 565, 1731, 1578, 1071, 5381, 22005, 67, 15468, 273, 417, 24410, 581, 5034, 2932, 16256, 67, 15468, 8863, 203, 203, 565, 533, 1071, 5381, 10071, 67, 16256, 273, 315, 15988, 30, 1962, 6204, 14432, 203, 565, 533, 1071, 5381, 10071, 67, 15140, 273, 315, 15988, 30, 1962, 5267, 14432, 203, 565, 533, 1071, 5381, 10071, 67, 8412, 55, 273, 315, 15988, 30, 1962, 16811, 434, 2430, 14432, 203, 565, 533, 1071, 5381, 10071, 67, 8090, 3991, 273, 315, 15988, 30, 1962, 1656, 281, 5184, 14432, 203, 565, 533, 1071, 5381, 10071, 67, 16436, 273, 315, 15988, 30, 1962, 5184, 14432, 203, 565, 533, 1071, 5381, 19238, 3649, 7085, 273, 315, 15988, 30, 4554, 854, 316, 11709, 14432, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 11709, 31, 203, 203, 565, 2254, 28, 1071, 5381, 9666, 3575, 67, 8090, 41, 273, 1381, 31, 203, 203, 565, 4232, 39, 3462, 3238, 1147, 31, 203, 203, 565, 1758, 1071, 11784, 31, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 2 ]
./full_match/1/0x15315dFc9E2Cc4F7F5456323Ab7010a1A74a337d/sources/contracts/BasePool_v_1_1.sol
denominated in loanCcy decimals
uint256 maxLoanPerColl;
3,121,199
[ 1, 13002, 362, 7458, 316, 28183, 39, 2431, 15105, 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, 2254, 5034, 943, 1504, 304, 2173, 13535, 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 ]
./partial_match/1/0x0004C6404f9E4D3e799De533dE985ca427934028/sources/HodlrKeysContract.sol
* @dev unpauses minting for all tokens in the contract/
function unpause() public onlyTeamOrOwner { _unpause(); }
3,976,697
[ 1, 318, 8774, 6117, 312, 474, 310, 364, 777, 2430, 316, 326, 6835, 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, 640, 19476, 1435, 1071, 1338, 8689, 1162, 5541, 288, 203, 3639, 389, 318, 19476, 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 ]
pragma solidity 0.4.25; contract X2Contract { using SafeMath for uint256; address public constant promotionAddress = 0x22e483dBeb45EDBC74d4fE25d79B5C28eA6Aa8Dd; address public constant adminAddress = 0x3C1FD40A99066266A60F60d17d5a7c51434d74bB; mapping (address => uint256) public deposit; mapping (address => uint256) public withdrawals; mapping (address => uint256) public time; uint256 public minimum = 0.01 ether; uint public promotionPercent = 10; uint public adminPercent = 2; uint256 public countOfInvestors; /** * @dev Get percent depends on balance of contract * @return Percent */ function getPhasePercent() view public returns (uint){ uint contractBalance = address(this).balance; if (contractBalance < 300 ether) { return 2; } if (contractBalance >= 300 ether && contractBalance < 1200 ether) { return 3; } if (contractBalance >= 1200 ether) { return 4; } } /** * @dev Evaluate current balance * @param _address Address of investor * @return Payout amount */ function getUserBalance(address _address) view public returns (uint256) { uint percent = getPhasePercent(); uint256 differentTime = now.sub(time[_address]).div(1 hours); uint256 differentPercent = deposit[_address].mul(percent).div(100); uint256 payout = differentPercent.mul(differentTime).div(24); return payout; } /** * @dev Withdraw profit from contract. Investor will be deleted if he will try withdraw after received x2 * @param _address Address of investor */ function withdraw(address _address) private { //Get user balance uint256 balance = getUserBalance(_address); //Conditions for withdraw, deposit should be more than 0, balance of contract should be more than balance of //investor and balance of investor should be more than 0 if (deposit[_address] > 0 && address(this).balance >= balance && balance > 0) { //Add withdrawal to storage withdrawals[_address] = withdrawals[_address].add(balance); //Reset time time[_address] = now; //If withdrawals more greater or equal deposit * 2 - delete investor if (withdrawals[_address] >= deposit[_address].mul(2)){ deposit[_address] = 0; time[_address] = 0; withdrawals[_address] = 0; countOfInvestors--; } //Transfer percents to investor _address.transfer(balance); } } /** * @dev Payable function */ function () external payable { if (msg.value >= minimum){ //Payout for promotion promotionAddress.transfer(msg.value.mul(promotionPercent).div(100)); //Payout for admin adminAddress.transfer(msg.value.mul(adminPercent).div(100)); //Withdraw a profit withdraw(msg.sender); //Increase counter of investors if (deposit[msg.sender] == 0){ countOfInvestors++; } //Add deposit to storage deposit[msg.sender] = deposit[msg.sender].add(msg.value); //Reset last time of deposit time[msg.sender] = now; } else { //Withdraw a profit withdraw(msg.sender); } } } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper then requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
* @title SafeMath @dev Math operations with safety checks that revert on error/
library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); 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) { require(b <= a); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
1,791,584
[ 1, 9890, 10477, 225, 2361, 5295, 598, 24179, 4271, 716, 15226, 603, 555, 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, 12083, 14060, 10477, 288, 203, 203, 565, 445, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 69, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 276, 273, 279, 380, 324, 31, 203, 3639, 2583, 12, 71, 342, 279, 422, 324, 1769, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 69, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 276, 273, 279, 380, 324, 31, 203, 3639, 2583, 12, 71, 342, 279, 422, 324, 1769, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 3739, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 276, 273, 279, 342, 324, 31, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 720, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 70, 1648, 279, 1769, 203, 3639, 2254, 5034, 276, 273, 279, 300, 324, 31, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 527, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 2 ]
/* Copyright 2018 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. */ pragma solidity ^0.5.5; contract ReentrancyGuard { // Locked state of mutex bool private locked = false; /// @dev Functions with this modifer cannot be reentered. The mutex will be locked /// before function execution and unlocked after. modifier nonReentrant() { // Ensure mutex is unlocked require( !locked, "REENTRANCY_ILLEGAL" ); // Lock mutex before function call locked = true; // Perform function call _; // Unlock mutex after function call locked = false; } }
Locked state of mutex
contract ReentrancyGuard { bool private locked = false; modifier nonReentrant() { require( !locked, "REENTRANCY_ILLEGAL" ); locked = true; _; locked = false; } }
13,135,454
[ 1, 8966, 919, 434, 9020, 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, 868, 8230, 12514, 16709, 288, 203, 203, 565, 1426, 3238, 8586, 273, 629, 31, 203, 203, 203, 203, 565, 9606, 1661, 426, 8230, 970, 1435, 288, 203, 3639, 2583, 12, 203, 5411, 401, 15091, 16, 203, 5411, 315, 862, 2222, 54, 1258, 16068, 67, 2627, 19384, 1013, 6, 203, 3639, 11272, 203, 203, 3639, 8586, 273, 638, 31, 203, 203, 3639, 389, 31, 203, 203, 3639, 8586, 273, 629, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x3133E21977CcaEf2C3b22945b25D8aF938539af9/sources/SENSHI.sol
* @dev Collection of functions related to the address type/
library Address { /@/ &@ @@@@@/ @@@@@.@@@@@ @@@@@. function isContract(address account) internal view returns (bool) { return account.code.length > 0; } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); require(success, "Address: unable to send value, recipient may have reverted"); } (bool success, ) = recipient.call{value: amount}(""); function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } 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"); } 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 verifyCallResultFromTarget(target, success, returndata, errorMessage); } (bool success, bytes memory returndata) = target.call{value: value}(data); function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { require(isContract(target), "Address: call to non-contract"); } return returndata; _revert(returndata, errorMessage); } } function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { require(isContract(target), "Address: call to non-contract"); } return returndata; _revert(returndata, errorMessage); } } function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { require(isContract(target), "Address: call to non-contract"); } return returndata; _revert(returndata, errorMessage); } } } else { function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; _revert(returndata, errorMessage); } } function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; _revert(returndata, errorMessage); } } } else { function _revert(bytes memory returndata, string memory errorMessage) private pure { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } else { }
4,264,062
[ 1, 2532, 434, 4186, 3746, 358, 326, 1758, 618, 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 ]
[ 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, 12083, 5267, 288, 203, 2398, 342, 36, 19, 4766, 1171, 473, 36, 2868, 203, 2398, 22175, 30989, 36, 19, 7734, 22175, 30989, 36, 18, 30989, 30989, 36, 7734, 22175, 30989, 36, 18, 2398, 203, 203, 203, 203, 203, 565, 445, 353, 8924, 12, 2867, 2236, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 203, 3639, 327, 2236, 18, 710, 18, 2469, 405, 374, 31, 203, 565, 289, 203, 203, 565, 445, 1366, 620, 12, 2867, 8843, 429, 8027, 16, 2254, 5034, 3844, 13, 2713, 288, 203, 3639, 2583, 12, 2867, 12, 2211, 2934, 12296, 1545, 3844, 16, 315, 1887, 30, 2763, 11339, 11013, 8863, 203, 203, 3639, 2583, 12, 4768, 16, 315, 1887, 30, 13496, 358, 1366, 460, 16, 8027, 2026, 1240, 15226, 329, 8863, 203, 565, 289, 203, 203, 3639, 261, 6430, 2216, 16, 262, 273, 8027, 18, 1991, 95, 1132, 30, 3844, 97, 2932, 8863, 203, 565, 445, 445, 1477, 12, 2867, 1018, 16, 1731, 3778, 501, 13, 2713, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 327, 445, 26356, 620, 12, 3299, 16, 501, 16, 374, 16, 315, 1887, 30, 4587, 17, 2815, 745, 2535, 8863, 203, 565, 289, 203, 203, 565, 445, 445, 1477, 12, 203, 3639, 1758, 1018, 16, 203, 3639, 1731, 3778, 501, 16, 203, 3639, 533, 3778, 9324, 203, 565, 262, 2713, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 327, 445, 26356, 620, 12, 3299, 16, 501, 16, 374, 16, 9324, 1769, 203, 565, 289, 203, 203, 565, 445, 445, 26356, 620, 12, 2867, 1018, 2 ]
./full_match/3/0x6a42dfdD170cFC8DfBC2605F226437AA6Bc16Ca5/sources/browser/HYPER.sol
* @dev Unlocks the unlockable tokens of a specified address @param _of Address of user, claiming back unlockable tokens/
function unlock(address _of) public override returns (uint256 _unlockableTokens) { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender)); uint256 _lockedTokens; for (uint256 i = 0; i < lockReason[_of].length; i++) { _lockedTokens = tokensUnlockable(_of, lockReason[_of][i]); if (_lockedTokens > 0) { _unlockableTokens = _unlockableTokens.add(_lockedTokens); locked[_of][lockReason[_of][i]].claimed = true; emit Unlocked(_of, lockReason[_of][i], _lockedTokens); } } if (_unlockableTokens > 0) this.transfer(_of, _unlockableTokens); }
14,210,364
[ 1, 7087, 87, 326, 7186, 429, 2430, 434, 279, 1269, 1758, 225, 389, 792, 5267, 434, 729, 16, 7516, 310, 1473, 7186, 429, 2430, 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, 225, 445, 7186, 12, 2867, 389, 792, 13, 1071, 3849, 1135, 261, 11890, 5034, 389, 26226, 429, 5157, 13, 288, 203, 565, 2583, 12, 5332, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 1234, 18, 15330, 10019, 203, 565, 2254, 5034, 389, 15091, 5157, 31, 203, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 2176, 8385, 63, 67, 792, 8009, 2469, 31, 277, 27245, 288, 203, 1377, 389, 15091, 5157, 273, 2430, 7087, 429, 24899, 792, 16, 2176, 8385, 63, 67, 792, 6362, 77, 19226, 203, 203, 1377, 309, 261, 67, 15091, 5157, 405, 374, 13, 288, 203, 3639, 389, 26226, 429, 5157, 273, 389, 26226, 429, 5157, 18, 1289, 24899, 15091, 5157, 1769, 203, 3639, 8586, 63, 67, 792, 6362, 739, 8385, 63, 67, 792, 6362, 77, 65, 8009, 14784, 329, 273, 638, 31, 203, 3639, 3626, 3967, 329, 24899, 792, 16, 2176, 8385, 63, 67, 792, 6362, 77, 6487, 389, 15091, 5157, 1769, 203, 1377, 289, 203, 565, 289, 203, 203, 565, 309, 261, 67, 26226, 429, 5157, 405, 374, 13, 203, 1377, 333, 18, 13866, 24899, 792, 16, 389, 26226, 429, 5157, 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 ]
//! { "cases": [ { //! "name": "test1", //! "input": [ //! { //! "entry": "test1", //! "calldata": [ //! ] //! } //! ], //! "expected": [ //! "1260830800381296" //! ] //! }, { //! "name": "test2", //! "input": [ //! { //! "entry": "test2", //! "calldata": [ //! ] //! } //! ], //! "expected": [ //! "781327317812" //! ] //! }, { //! "name": "test3", //! "input": [ //! { //! "entry": "test3", //! "calldata": [ //! ] //! } //! ], //! "expected": [ //! "0" //! ] //! } ] } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; contract Test { uint64 constant BASE = 1000000000; uint16 constant LEN = 12; struct BigUint { uint64[LEN] digits; uint16 len; } function _new() private pure returns(BigUint memory) { BigUint memory bigUint; bigUint.len = 1; return bigUint; } function fromUint(uint64 n) private pure returns(BigUint memory) { BigUint memory number; uint16 curr = 0; while (n > 0) { number.digits[number.len] = n % BASE; n /= BASE; number.len += 1; } if (number.len == 0) { number.len = 1; } return number; } function asUint(BigUint memory self) private pure returns(uint64) { uint64 n = 0; uint16 i = self.len - 1; while (true) { n = n * BASE + self.digits[i]; if (i == 0) { break; } i--; } return n; } function less(BigUint memory self, BigUint memory other) private pure returns(bool) { if (self.len != other.len) { return self.len < other.len; } uint16 i = self.len - 1; while (true) { if (self.digits[i] != other.digits[i]) { return self.digits[i] < other.digits[i]; } if (i == 0) { break; } i--; } return false; } function greater(BigUint memory self, BigUint memory other) private pure returns(bool) { return less(other, self); } function equals(BigUint memory self, BigUint memory other) private pure returns(bool) { return !less(self, other) && !less(other, self); } function add(BigUint memory self, BigUint memory other) private pure returns(BigUint memory) { uint16 len = self.len; if (other.len > len) { len = other.len; } BigUint memory result; result.len = len; uint64 carry = 0; for (uint16 i = 0; i < len; i++) { result.digits[i] += carry; if (i < self.len) { result.digits[i] += self.digits[i]; } if (i < other.len) { result.digits[i] += other.digits[i]; } carry = result.digits[i] / BASE; result.digits[i] %= BASE; } if (carry > 0) { result.digits[result.len] = carry; result.len++; } return result; } // if second greater - 0 function sub(BigUint memory self, BigUint memory other) private pure returns(BigUint memory) { if (less(self, other)) { return _new(); } BigUint memory result; result.len = self.len; uint64 carry = 0; for (uint16 i = 0; i < self.len; i++) { uint64 d = carry; if (i < other.len) { d += other.digits[i]; } if (self.digits[i] < d) { carry = 1; result.digits[i] = self.digits[i] + BASE - d; } else { carry = 0; result.digits[i] = self.digits[i] - d; } } while (result.len > 1 && result.digits[result.len - 1] == 0) { result.len--; } return result; } function mul(BigUint memory self, BigUint memory other) private pure returns(BigUint memory) { BigUint memory result; result.len = self.len + other.len; for (uint16 i = 0; i < self.len; i++) { uint64 carry = 0; uint16 j = 0; while (j < other.len || carry != 0) { uint64 b = 0; if (j < other.len) { b = other.digits[j]; } uint64 curr = result.digits[i + j] + self.digits[i] * b + carry; result.digits[i + j] = curr % BASE; carry = curr / BASE; j++; } } while (result.len > 1 && result.digits[result.len - 1] == 0) { result.len--; } return result; } function div(BigUint memory self, uint64 other) private pure returns(BigUint memory) { BigUint memory result; result.len = self.len; uint64 carry = 0; uint16 i = self.len - 1; while (true) { uint64 curr = self.digits[i] + carry * BASE; result.digits[i] = curr / other; carry = curr / other; carry = curr % other; if (i == 0) { break; } i--; } while (result.len > 1 && result.digits[result.len - 1] == 0) { result.len--; } return result; } function pow(BigUint memory self, uint64 n) private pure returns(BigUint memory) { BigUint memory result; result.len = 1; result.digits[0] = 1; while (n != 0) { if (n & 1 != 0) { result = mul(result, self); } self = mul(self, self); n >>= 1; } return result; } function test1() public pure returns(uint64) { BigUint memory number = fromUint(9124712378731); number = add(number, fromUint(129213344)); // 9 124 841 592 075 number = pow(number, 5); // 63 259 633 147 891 755 508 903 200 605 498 033 555 974 923 078 789 924 986 748 046 875 number = div(number, 987659234); // 64 050 059 950 020 935 569 872 068 452 202 648 627 264 211 938 497 326 889 number = add(number, fromUint(12332455)); // 64 050 059 950 020 935 569 872 068 452 202 648 627 264 211 938 509 659 344 number = div(number, 100000000); // 640 500 599 500 209 355 698 720 684 522 026 486 272 642 119 385 number = sub(number, mul(pow(fromUint(794121), 7), fromUint(3215975))); // 163 633 183 869 615 894 606 020 115 919 720 373 594 410 number = sub(number, mul(fromUint(46971696617), pow(fromUint(123123), 6))); // 1 307 733 141 469 273 444 912 310 500 297 number = div(number, 92348823); // 14 160 799 228 261 668 748 201 number = div(number, 11231324); // 1 260 830 800 381 296 return asUint(number); } function test2() public pure returns(uint64) { BigUint memory number = fromUint(781327317812); number = mul(number, fromUint(8712712)); number = div(number, 8712712); return asUint(number); } function test3() public pure returns(uint64) { BigUint memory number = fromUint(13123121); number = sub(number, fromUint(13123122)); return asUint(number); } }
if second greater - 0
function sub(BigUint memory self, BigUint memory other) private pure returns(BigUint memory) { if (less(self, other)) { return _new(); } BigUint memory result; result.len = self.len; uint64 carry = 0; for (uint16 i = 0; i < self.len; i++) { uint64 d = carry; if (i < other.len) { d += other.digits[i]; } if (self.digits[i] < d) { carry = 1; result.digits[i] = self.digits[i] + BASE - d; carry = 0; result.digits[i] = self.digits[i] - d; } } while (result.len > 1 && result.digits[result.len - 1] == 0) { result.len--; } return result; }
13,000,100
[ 1, 430, 2205, 6802, 300, 374, 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, 720, 12, 9901, 5487, 3778, 365, 16, 4454, 5487, 3778, 1308, 13, 3238, 16618, 1135, 12, 9901, 5487, 3778, 13, 288, 203, 3639, 309, 261, 2656, 12, 2890, 16, 1308, 3719, 288, 203, 5411, 327, 389, 2704, 5621, 203, 3639, 289, 203, 3639, 4454, 5487, 3778, 563, 31, 203, 3639, 563, 18, 1897, 273, 365, 18, 1897, 31, 203, 3639, 2254, 1105, 9331, 273, 374, 31, 203, 3639, 364, 261, 11890, 2313, 277, 273, 374, 31, 277, 411, 365, 18, 1897, 31, 277, 27245, 288, 203, 5411, 2254, 1105, 302, 273, 9331, 31, 203, 5411, 309, 261, 77, 411, 1308, 18, 1897, 13, 288, 203, 7734, 302, 1011, 1308, 18, 16649, 63, 77, 15533, 203, 5411, 289, 203, 5411, 309, 261, 2890, 18, 16649, 63, 77, 65, 411, 302, 13, 288, 203, 7734, 9331, 273, 404, 31, 203, 7734, 563, 18, 16649, 63, 77, 65, 273, 365, 18, 16649, 63, 77, 65, 397, 10250, 300, 302, 31, 203, 7734, 9331, 273, 374, 31, 203, 7734, 563, 18, 16649, 63, 77, 65, 273, 365, 18, 16649, 63, 77, 65, 300, 302, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 1323, 261, 2088, 18, 1897, 405, 404, 597, 563, 18, 16649, 63, 2088, 18, 1897, 300, 404, 65, 422, 374, 13, 288, 203, 5411, 563, 18, 1897, 413, 31, 203, 3639, 289, 203, 3639, 327, 563, 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 ]
// SPDX-License-Identifier: MIT-open-group pragma solidity ^0.8.11; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "contracts/libraries/governance/GovernanceMaxLock.sol"; import "contracts/libraries/StakingNFT/StakingNFTStorage.sol"; import "contracts/utils/ImmutableAuth.sol"; import "contracts/utils/EthSafeTransfer.sol"; import "contracts/utils/ERC20SafeTransfer.sol"; import "contracts/utils/MagicValue.sol"; import "contracts/interfaces/ICBOpener.sol"; import "contracts/interfaces/IStakingNFT.sol"; import "contracts/interfaces/IStakingNFTDescriptor.sol"; import {StakingNFTErrorCodes} from "contracts/libraries/errorCodes/StakingNFTErrorCodes.sol"; import { CircuitBreakerErrorCodes } from "contracts/libraries/errorCodes/CircuitBreakerErrorCodes.sol"; abstract contract StakingNFT is Initializable, ERC721Upgradeable, StakingNFTStorage, MagicValue, EthSafeTransfer, ERC20SafeTransfer, GovernanceMaxLock, ICBOpener, IStakingNFT, ImmutableFactory, ImmutableValidatorPool, ImmutableAToken, ImmutableGovernance, ImmutableStakingPositionDescriptor { // withCircuitBreaker is a modifier to enforce the CircuitBreaker must // be set for a call to succeed modifier withCircuitBreaker() { require( _circuitBreaker == _CIRCUIT_BREAKER_CLOSED, string(abi.encodePacked(CircuitBreakerErrorCodes.CIRCUIT_BREAKER_OPENED)) ); _; } constructor() ImmutableFactory(msg.sender) ImmutableAToken() ImmutableGovernance() ImmutableValidatorPool() ImmutableStakingPositionDescriptor() {} /// gets the current value for the Eth accumulator function getEthAccumulator() external view returns (uint256 accumulator, uint256 slush) { accumulator = _ethState.accumulator; slush = _ethState.slush; } /// gets the current value for the Token accumulator function getTokenAccumulator() external view returns (uint256 accumulator, uint256 slush) { accumulator = _tokenState.accumulator; slush = _tokenState.slush; } /// @dev tripCB opens the circuit breaker may only be called by _admin function tripCB() public override onlyFactory { _tripCB(); } /// skimExcessEth will send to the address passed as to_ any amount of Eth /// held by this contract that is not tracked by the Accumulator system. This /// function allows the Admin role to refund any Eth sent to this contract in /// error by a user. This method can not return any funds sent to the contract /// via the depositEth method. This function should only be necessary if a /// user somehow manages to accidentally selfDestruct a contract with this /// contract as the recipient. function skimExcessEth(address to_) public onlyFactory returns (uint256 excess) { excess = _estimateExcessEth(); _safeTransferEth(to_, excess); return excess; } /// skimExcessToken will send to the address passed as to_ any amount of /// AToken held by this contract that is not tracked by the Accumulator /// system. This function allows the Admin role to refund any AToken sent to /// this contract in error by a user. This method can not return any funds /// sent to the contract via the depositToken method. function skimExcessToken(address to_) public onlyFactory returns (uint256 excess) { IERC20Transferable aToken; (aToken, excess) = _estimateExcessToken(); _safeTransferERC20(aToken, to_, excess); return excess; } /// lockPosition is called by governance system when a governance /// vote is cast. This function will lock the specified Position for up to /// _MAX_GOVERNANCE_LOCK. This method may only be called by the governance /// contract. This function will fail if the circuit breaker is tripped function lockPosition( address caller_, uint256 tokenID_, uint256 lockDuration_ ) public override withCircuitBreaker onlyGovernance returns (uint256) { require( caller_ == ownerOf(tokenID_), string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_CALLER_NOT_TOKEN_OWNER)) ); require( lockDuration_ <= _MAX_GOVERNANCE_LOCK, string( abi.encodePacked( StakingNFTErrorCodes.STAKENFT_LOCK_DURATION_GREATER_THAN_GOVERNANCE_LOCK ) ) ); return _lockPosition(tokenID_, lockDuration_); } /// This function will lock an owned Position for up to _MAX_GOVERNANCE_LOCK. This method may /// only be called by the owner of the Position. This function will fail if the circuit breaker /// is tripped function lockOwnPosition(uint256 tokenID_, uint256 lockDuration_) public withCircuitBreaker returns (uint256) { require( msg.sender == ownerOf(tokenID_), string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_CALLER_NOT_TOKEN_OWNER)) ); require( lockDuration_ <= _MAX_GOVERNANCE_LOCK, string( abi.encodePacked( StakingNFTErrorCodes.STAKENFT_LOCK_DURATION_GREATER_THAN_GOVERNANCE_LOCK ) ) ); return _lockPosition(tokenID_, lockDuration_); } /// This function will lock withdraws on the specified Position for up to /// _MAX_GOVERNANCE_LOCK. This function will fail if the circuit breaker is tripped function lockWithdraw(uint256 tokenID_, uint256 lockDuration_) public withCircuitBreaker returns (uint256) { require( msg.sender == ownerOf(tokenID_), string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_CALLER_NOT_TOKEN_OWNER)) ); require( lockDuration_ <= _MAX_GOVERNANCE_LOCK, string( abi.encodePacked( StakingNFTErrorCodes.STAKENFT_LOCK_DURATION_GREATER_THAN_GOVERNANCE_LOCK ) ) ); return _lockWithdraw(tokenID_, lockDuration_); } /// DO NOT CALL THIS METHOD UNLESS YOU ARE MAKING A DISTRIBUTION AS ALL VALUE /// WILL BE DISTRIBUTED TO STAKERS EVENLY. depositToken distributes AToken /// to all stakers evenly should only be called during a slashing event. Any /// AToken sent to this method in error will be lost. This function will /// fail if the circuit breaker is tripped. The magic_ parameter is intended /// to stop some one from successfully interacting with this method without /// first reading the source code and hopefully this comment function depositToken(uint8 magic_, uint256 amount_) public withCircuitBreaker checkMagic(magic_) { // collect tokens _safeTransferFromERC20(IERC20Transferable(_aTokenAddress()), msg.sender, amount_); // update state _tokenState = _deposit(_shares, amount_, _tokenState); _reserveToken += amount_; } /// DO NOT CALL THIS METHOD UNLESS YOU ARE MAKING A DISTRIBUTION ALL VALUE /// WILL BE DISTRIBUTED TO STAKERS EVENLY depositEth distributes Eth to all /// stakers evenly should only be called by BTokens contract any Eth sent to /// this method in error will be lost this function will fail if the circuit /// breaker is tripped the magic_ parameter is intended to stop some one from /// successfully interacting with this method without first reading the /// source code and hopefully this comment function depositEth(uint8 magic_) public payable withCircuitBreaker checkMagic(magic_) { _ethState = _deposit(_shares, msg.value, _ethState); _reserveEth += msg.value; } /// mint allows a staking position to be opened. This function /// requires the caller to have performed an approve invocation against /// AToken into this contract. This function will fail if the circuit /// breaker is tripped. function mint(uint256 amount_) public virtual withCircuitBreaker returns (uint256 tokenID) { return _mintNFT(msg.sender, amount_); } /// mintTo allows a staking position to be opened in the name of an /// account other than the caller. This method also allows a lock to be /// placed on the position up to _MAX_MINT_LOCK . This function requires the /// caller to have performed an approve invocation against AToken into /// this contract. This function will fail if the circuit breaker is /// tripped. function mintTo( address to_, uint256 amount_, uint256 lockDuration_ ) public virtual withCircuitBreaker returns (uint256 tokenID) { require( lockDuration_ <= _MAX_MINT_LOCK, string( abi.encodePacked(StakingNFTErrorCodes.STAKENFT_LOCK_DURATION_GREATER_THAN_MINT_LOCK) ) ); tokenID = _mintNFT(to_, amount_); if (lockDuration_ > 0) { _lockPosition(tokenID, lockDuration_); } return tokenID; } /// burn exits a staking position such that all accumulated value is /// transferred to the owner on burn. function burn(uint256 tokenID_) public virtual returns (uint256 payoutEth, uint256 payoutAToken) { return _burn(msg.sender, msg.sender, tokenID_); } /// burnTo exits a staking position such that all accumulated value /// is transferred to a specified account on burn function burnTo(address to_, uint256 tokenID_) public virtual returns (uint256 payoutEth, uint256 payoutAToken) { return _burn(msg.sender, to_, tokenID_); } /// collectEth returns all due Eth allocations to caller. The caller /// of this function must be the owner of the tokenID function collectEth(uint256 tokenID_) public returns (uint256 payout) { address owner = ownerOf(tokenID_); require( msg.sender == owner, string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_CALLER_NOT_TOKEN_OWNER)) ); Position memory position = _positions[tokenID_]; require( _positions[tokenID_].withdrawFreeAfter < block.number, string( abi.encodePacked( StakingNFTErrorCodes.STAKENFT_LOCK_DURATION_WITHDRAW_TIME_NOT_REACHED ) ) ); // get values and update state (_positions[tokenID_], payout) = _collectEth(_shares, position); _reserveEth -= payout; // perform transfer and return amount paid out _safeTransferEth(owner, payout); return payout; } /// collectToken returns all due AToken allocations to caller. The /// caller of this function must be the owner of the tokenID function collectToken(uint256 tokenID_) public returns (uint256 payout) { address owner = ownerOf(tokenID_); require( msg.sender == owner, string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_CALLER_NOT_TOKEN_OWNER)) ); Position memory position = _positions[tokenID_]; require( position.withdrawFreeAfter < block.number, string( abi.encodePacked( StakingNFTErrorCodes.STAKENFT_LOCK_DURATION_WITHDRAW_TIME_NOT_REACHED ) ) ); // get values and update state (_positions[tokenID_], payout) = _collectToken(_shares, position); _reserveToken -= payout; // perform transfer and return amount paid out _safeTransferERC20(IERC20Transferable(_aTokenAddress()), owner, payout); return payout; } /// collectEth returns all due Eth allocations to the to_ address. The caller /// of this function must be the owner of the tokenID function collectEthTo(address to_, uint256 tokenID_) public returns (uint256 payout) { address owner = ownerOf(tokenID_); require( msg.sender == owner, string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_CALLER_NOT_TOKEN_OWNER)) ); Position memory position = _positions[tokenID_]; require( _positions[tokenID_].withdrawFreeAfter < block.number, string( abi.encodePacked( StakingNFTErrorCodes.STAKENFT_LOCK_DURATION_WITHDRAW_TIME_NOT_REACHED ) ) ); // get values and update state (_positions[tokenID_], payout) = _collectEth(_shares, position); _reserveEth -= payout; // perform transfer and return amount paid out _safeTransferEth(to_, payout); return payout; } /// collectTokenTo returns all due AToken allocations to the to_ address. The /// caller of this function must be the owner of the tokenID function collectTokenTo(address to_, uint256 tokenID_) public returns (uint256 payout) { address owner = ownerOf(tokenID_); require( msg.sender == owner, string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_CALLER_NOT_TOKEN_OWNER)) ); Position memory position = _positions[tokenID_]; require( position.withdrawFreeAfter < block.number, string( abi.encodePacked( StakingNFTErrorCodes.STAKENFT_LOCK_DURATION_WITHDRAW_TIME_NOT_REACHED ) ) ); // get values and update state (_positions[tokenID_], payout) = _collectToken(_shares, position); _reserveToken -= payout; // perform transfer and return amount paid out _safeTransferERC20(IERC20Transferable(_aTokenAddress()), to_, payout); return payout; } function circuitBreakerState() public view returns (bool) { return _circuitBreaker; } /// gets the total amount of AToken staked in contract function getTotalShares() public view returns (uint256) { return _shares; } /// gets the total amount of Ether staked in contract function getTotalReserveEth() public view returns (uint256) { return _reserveEth; } /// gets the total amount of AToken staked in contract function getTotalReserveAToken() public view returns (uint256) { return _reserveToken; } /// estimateEthCollection returns the amount of eth a tokenID may withdraw function estimateEthCollection(uint256 tokenID_) public view returns (uint256 payout) { require( _exists(tokenID_), string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_INVALID_TOKEN_ID)) ); Position memory p = _positions[tokenID_]; (, , , payout) = _collect(_shares, _ethState, p, p.accumulatorEth); return payout; } /// estimateTokenCollection returns the amount of AToken a tokenID may withdraw function estimateTokenCollection(uint256 tokenID_) public view returns (uint256 payout) { require( _exists(tokenID_), string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_INVALID_TOKEN_ID)) ); Position memory p = _positions[tokenID_]; (, , , payout) = _collect(_shares, _tokenState, p, p.accumulatorToken); return payout; } /// estimateExcessToken returns the amount of AToken that is held in the /// name of this contract. The value returned is the value that would be /// returned by a call to skimExcessToken. function estimateExcessToken() public view returns (uint256 excess) { (, excess) = _estimateExcessToken(); return excess; } /// estimateExcessEth returns the amount of Eth that is held in the name of /// this contract. The value returned is the value that would be returned by /// a call to skimExcessEth. function estimateExcessEth() public view returns (uint256 excess) { return _estimateExcessEth(); } /// gets the position struct given a tokenID. The tokenId must /// exist. function getPosition(uint256 tokenID_) public view returns ( uint256 shares, uint256 freeAfter, uint256 withdrawFreeAfter, uint256 accumulatorEth, uint256 accumulatorToken ) { require( _exists(tokenID_), string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_INVALID_TOKEN_ID)) ); Position memory p = _positions[tokenID_]; shares = uint256(p.shares); freeAfter = uint256(p.freeAfter); withdrawFreeAfter = uint256(p.withdrawFreeAfter); accumulatorEth = p.accumulatorEth; accumulatorToken = p.accumulatorToken; } /// Gets token URI function tokenURI(uint256 tokenId) public view override(ERC721Upgradeable) returns (string memory) { require( _exists(tokenId), string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_INVALID_TOKEN_ID)) ); return IStakingNFTDescriptor(_stakingPositionDescriptorAddress()).tokenURI(this, tokenId); } /// gets the _ACCUMULATOR_SCALE_FACTOR used to scale the ether and tokens /// deposited on this contract to reduce the integer division errors. function getAccumulatorScaleFactor() public pure returns (uint256) { return _ACCUMULATOR_SCALE_FACTOR; } /// gets the _MAX_MINT_LOCK value. This value is the maximum duration of blocks that we allow a /// position to be locked function getMaxMintLock() public pure returns (uint256) { return _MAX_MINT_LOCK; } function __stakingNFTInit(string memory name_, string memory symbol_) internal onlyInitializing { __ERC721_init(name_, symbol_); } // _lockPosition prevents a position from being burned for duration_ number // of blocks by setting the freeAfter field on the Position struct returns // the number of shares in the locked Position so that governance vote // counting may be performed when setting a lock function _lockPosition(uint256 tokenID_, uint256 duration_) internal returns (uint256 shares) { require( _exists(tokenID_), string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_INVALID_TOKEN_ID)) ); Position memory p = _positions[tokenID_]; uint32 freeDur = uint32(block.number) + uint32(duration_); p.freeAfter = freeDur > p.freeAfter ? freeDur : p.freeAfter; _positions[tokenID_] = p; return p.shares; } // _lockWithdraw prevents a position from being collected and burned for duration_ number of blocks // by setting the withdrawFreeAfter field on the Position struct. // returns the number of shares in the locked Position so that function _lockWithdraw(uint256 tokenID_, uint256 duration_) internal returns (uint256 shares) { require( _exists(tokenID_), string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_INVALID_TOKEN_ID)) ); Position memory p = _positions[tokenID_]; uint256 freeDur = block.number + duration_; p.withdrawFreeAfter = freeDur > p.withdrawFreeAfter ? freeDur : p.withdrawFreeAfter; _positions[tokenID_] = p; return p.shares; } // _mintNFT performs the mint operation and invokes the inherited _mint method function _mintNFT(address to_, uint256 amount_) internal returns (uint256 tokenID) { // this is to allow struct packing and is safe due to AToken having a // total distribution of 220M require( amount_ <= 2**224 - 1, string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_MINT_AMOUNT_EXCEEDS_MAX_SUPPLY)) ); // transfer the number of tokens specified by amount_ into contract // from the callers account _safeTransferFromERC20(IERC20Transferable(_aTokenAddress()), msg.sender, amount_); // get local copy of storage vars to save gas uint256 shares = _shares; Accumulator memory ethState = _ethState; Accumulator memory tokenState = _tokenState; // get new tokenID from counter tokenID = _increment(); // update storage shares += amount_; _shares = shares; _positions[tokenID] = Position( uint224(amount_), uint32(block.number) + 1, uint32(block.number) + 1, ethState.accumulator, tokenState.accumulator ); _reserveToken += amount_; // invoke inherited method and return ERC721Upgradeable._mint(to_, tokenID); return tokenID; } // _burn performs the burn operation and invokes the inherited _burn method function _burn( address from_, address to_, uint256 tokenID_ ) internal returns (uint256 payoutEth, uint256 payoutToken) { require( from_ == ownerOf(tokenID_), string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_CALLER_NOT_TOKEN_OWNER)) ); // collect state Position memory p = _positions[tokenID_]; // enforce freeAfter to prevent burn during lock require( p.freeAfter < block.number && p.withdrawFreeAfter < block.number, string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_FREE_AFTER_TIME_NOT_REACHED)) ); // get copy of storage to save gas uint256 shares = _shares; // calc Eth amounts due (p, payoutEth) = _collectEth(shares, p); // calc token amounts due (p, payoutToken) = _collectToken(shares, p); // add back to token payout the original stake position payoutToken += p.shares; // debit global shares counter and delete from mapping _shares -= p.shares; _reserveToken -= payoutToken; _reserveEth -= payoutEth; delete _positions[tokenID_]; // invoke inherited burn method ERC721Upgradeable._burn(tokenID_); // transfer out all eth and tokens owed _safeTransferERC20(IERC20Transferable(_aTokenAddress()), to_, payoutToken); _safeTransferEth(to_, payoutEth); return (payoutEth, payoutToken); } function _collectToken(uint256 shares_, Position memory p_) internal returns (Position memory p, uint256 payout) { uint256 acc; (_tokenState, p, acc, payout) = _collect(shares_, _tokenState, p_, p_.accumulatorToken); p.accumulatorToken = acc; return (p, payout); } // _collectEth performs call to _collect and updates state during a request // for an eth distribution function _collectEth(uint256 shares_, Position memory p_) internal returns (Position memory p, uint256 payout) { uint256 acc; (_ethState, p, acc, payout) = _collect(shares_, _ethState, p_, p_.accumulatorEth); p.accumulatorEth = acc; return (p, payout); } function _tripCB() internal { require( _circuitBreaker == _CIRCUIT_BREAKER_CLOSED, string(abi.encodePacked(CircuitBreakerErrorCodes.CIRCUIT_BREAKER_OPENED)) ); _circuitBreaker = _CIRCUIT_BREAKER_OPENED; } function _resetCB() internal { require( _circuitBreaker == _CIRCUIT_BREAKER_OPENED, string(abi.encodePacked(CircuitBreakerErrorCodes.CIRCUIT_BREAKER_CLOSED)) ); _circuitBreaker = _CIRCUIT_BREAKER_CLOSED; } // _newTokenID increments the counter and returns the new value function _increment() internal returns (uint256 count) { count = _counter; count += 1; _counter = count; return count; } // _estimateExcessEth returns the amount of Eth that is held in the name of // this contract function _estimateExcessEth() internal view returns (uint256 excess) { uint256 reserve = _reserveEth; uint256 balance = address(this).balance; require( balance >= reserve, string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_BALANCE_LESS_THAN_RESERVE)) ); excess = balance - reserve; } // _estimateExcessToken returns the amount of AToken that is held in the // name of this contract function _estimateExcessToken() internal view returns (IERC20Transferable aToken, uint256 excess) { uint256 reserve = _reserveToken; aToken = IERC20Transferable(_aTokenAddress()); uint256 balance = aToken.balanceOf(address(this)); require( balance >= reserve, string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_BALANCE_LESS_THAN_RESERVE)) ); excess = balance - reserve; return (aToken, excess); } function _getCount() internal view returns (uint256) { return _counter; } // _collect performs calculations necessary to determine any distributions // due to an account such that it may be used for both token and eth // distributions this prevents the need to keep redundant logic function _collect( uint256 shares_, Accumulator memory state_, Position memory p_, uint256 positionAccumulatorValue_ ) internal pure returns ( Accumulator memory, Position memory, uint256, uint256 ) { // determine number of accumulator steps this Position needs distributions from uint256 accumulatorDelta = 0; if (positionAccumulatorValue_ > state_.accumulator) { accumulatorDelta = type(uint168).max - positionAccumulatorValue_; accumulatorDelta += state_.accumulator; positionAccumulatorValue_ = state_.accumulator; } else { accumulatorDelta = state_.accumulator - positionAccumulatorValue_; // update accumulator value for calling method positionAccumulatorValue_ += accumulatorDelta; } // calculate payout based on shares held in position uint256 payout = accumulatorDelta * p_.shares; // if there are no shares other than this position, flush the slush fund // into the payout and update the in memory state object if (shares_ == p_.shares) { payout += state_.slush; state_.slush = 0; } uint256 payoutRemainder = payout; // reduce payout by scale factor payout /= _ACCUMULATOR_SCALE_FACTOR; // Computing and saving the numeric error from the floor division in the // slush. payoutRemainder -= payout * _ACCUMULATOR_SCALE_FACTOR; state_.slush += payoutRemainder; return (state_, p_, positionAccumulatorValue_, payout); } // _deposit allows an Accumulator to be updated with new value if there are // no currently staked positions, all value is stored in the slush function _deposit( uint256 shares_, uint256 delta_, Accumulator memory state_ ) internal pure returns (Accumulator memory) { state_.slush += (delta_ * _ACCUMULATOR_SCALE_FACTOR); if (shares_ > 0) { (state_.accumulator, state_.slush) = _slushSkim( shares_, state_.accumulator, state_.slush ); } // Slush should be never be above 2**167 to protect against overflow in // the later code. require( state_.slush < 2**167, string(abi.encodePacked(StakingNFTErrorCodes.STAKENFT_SLUSH_TOO_LARGE)) ); return state_; } // _slushSkim flushes value from the slush into the accumulator if there are // no currently staked positions, all value is stored in the slush function _slushSkim( uint256 shares_, uint256 accumulator_, uint256 slush_ ) internal pure returns (uint256, uint256) { if (shares_ > 0) { uint256 deltaAccumulator = slush_ / shares_; slush_ -= deltaAccumulator * shares_; accumulator_ += deltaAccumulator; // avoiding accumulator_ overflow. if (accumulator_ > type(uint168).max) { // The maximum allowed value for the accumulator is 2**168-1. // This hard limit was set to not overflow the operation // `accumulator * shares` that happens later in the code. accumulator_ = accumulator_ % type(uint168).max; } } return (accumulator_, slush_); } }
gets the _ACCUMULATOR_SCALE_FACTOR used to scale the ether and tokens deposited on this contract to reduce the integer division errors.
function getAccumulatorScaleFactor() public pure returns (uint256) { return _ACCUMULATOR_SCALE_FACTOR; }
7,278,427
[ 1, 14665, 326, 389, 31414, 2799, 1506, 3575, 67, 19378, 67, 26835, 1399, 358, 3159, 326, 225, 2437, 471, 2430, 443, 1724, 329, 603, 333, 6835, 358, 5459, 326, 3571, 16536, 1334, 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, 4506, 952, 18514, 5587, 6837, 1435, 1071, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 31414, 2799, 1506, 3575, 67, 19378, 67, 26835, 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, -100 ]
./partial_match/42/0xb67e3087b617C68F81b6A85a086C3F6833a7334B/sources/astronaut7/acap-pw/42/0xb67e3087b617C68F81b6A85a086C3F6833a7334B/Agreement.sol
* @dev Update Agreement state. Calls needed function according to the expireDate (terminates or liquidated or updates the agreement) @return Operation success/
function updateAgreement() external onlyContractOwner hasStatus(Statuses.Active) returns(bool _success) { if (now > expireDate) { _closeAgreement(ClosedTypes.Ended); _updateAgreementState(true); return true; } if (!isCdpSafe(collateralType, cdpId)) { _closeAgreement(ClosedTypes.Liquidated); _updateAgreementState(true); return true; } _updateAgreementState(false); return true; }
9,085,826
[ 1, 1891, 5495, 10606, 919, 18, 23665, 3577, 445, 4888, 358, 326, 6930, 1626, 1850, 261, 9505, 815, 578, 4501, 26595, 690, 578, 4533, 326, 19602, 13, 327, 225, 4189, 2216, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 17420, 1435, 3903, 1338, 8924, 5541, 711, 1482, 12, 15220, 18, 3896, 13, 1135, 12, 6430, 389, 4768, 13, 288, 203, 3639, 309, 261, 3338, 405, 6930, 1626, 13, 288, 203, 5411, 389, 4412, 17420, 12, 7395, 2016, 18, 28362, 1769, 203, 5411, 389, 2725, 17420, 1119, 12, 3767, 1769, 203, 5411, 327, 638, 31, 203, 3639, 289, 203, 3639, 309, 16051, 291, 39, 9295, 9890, 12, 12910, 2045, 287, 559, 16, 7976, 84, 548, 3719, 288, 203, 5411, 389, 4412, 17420, 12, 7395, 2016, 18, 48, 18988, 350, 690, 1769, 203, 5411, 389, 2725, 17420, 1119, 12, 3767, 1769, 203, 5411, 327, 638, 31, 203, 3639, 289, 203, 3639, 389, 2725, 17420, 1119, 12, 5743, 1769, 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 ]
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.7; // OpenZeppelin Contracts @ version 4.3.2 import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "../interfaces/IRandomNumberConsumer.sol"; import "../interfaces/IERC2981.sol"; /** * @title TicketVariantVRF721NFT * @notice ERC-721 NFT Contract with VRF-powered offset after ticket period completion * * Key features: * - Uses Chainlink VRF to establish random distribution at time of "reveal" */ contract SEENTicketVariantVRF721NFT is ERC721, Ownable { using Strings for uint256; // Controlled state variables using Counters for Counters.Counter; Counters.Counter private _ticketIds; bool public isRandomnessRequested; bytes32 public randomNumberRequestId; uint256 public vrfResult; uint256 public randomOffset; mapping(address => uint256[]) public buyerToTicketIds; mapping(uint256 => address) public ticketIdToBuyer; mapping(address => uint256) public buyerToRedeemedTicketCount; // Configurable state variables string public baseURI; uint256 public supplyLimit; uint256 public start; uint256 public end; uint256 public price; uint256 public limitPerOrder; address public vrfProvider; address[] public payoutAddresses; uint16[] public payoutAddressBasisPoints; address public royaltyReceiver; uint16 public royaltyBasisPoints; // Events event Buy(address indexed buyer, uint256 amount); event PlacedReservation(address indexed buyer, uint256 indexed ticketId); event RequestedVRF(bool isRequested, bytes32 randomNumberRequestId); event CommittedVRF(bytes32 requestId, uint256 vrfResult, uint256 randomOffset); event MintedOffset(address indexed minter, uint256 indexed ticketId, uint256 indexed tokenId); event UpdatedPayoutScheme(address indexed updatedBy, address[] payoutAddresses, uint16[] payoutAddressBasisPoints, uint256 timestamp); constructor( string memory _tokenName, string memory _tokenSymbol, string memory _baseURI, uint256 _supplyLimit, uint256 _start, uint256 _end, uint256 _price, uint256 _limitPerOrder, address _vrfProvider, address[] memory _payoutAddresses, uint16[] memory _payoutAddressBasisPoints ) public ERC721(_tokenName, _tokenSymbol) { require(_payoutAddresses.length > 0, "PAYOUT_ADDRESSES_EMPTY"); require(_payoutAddresses.length == _payoutAddressBasisPoints.length, "MISSING_BASIS_POINTS"); randomOffset = 0; // Must be zero at time of deployment baseURI = _baseURI; supplyLimit = _supplyLimit; start = _start; end = _end; price = _price; limitPerOrder = _limitPerOrder; vrfProvider = _vrfProvider; uint256 totalBasisPoints; for(uint256 i = 0; i < _payoutAddresses.length; i++) { // _payoutAddressBasisPoints may not contain values of 0 and may not exceed 10000 (100%) require((_payoutAddressBasisPoints[i] > 0) && (_payoutAddressBasisPoints[i] <= 10000), "INVALID_BASIS_POINTS_1"); totalBasisPoints += _payoutAddressBasisPoints[i]; } // _payoutAddressBasisPoints must add up to 10000 together require(totalBasisPoints == 10000, "INVALID_BASIS_POINTS_2"); payoutAddresses = _payoutAddresses; payoutAddressBasisPoints = _payoutAddressBasisPoints; } function buy(uint256 quantity) external payable { require(block.timestamp >= start, "HAS_NOT_STARTED"); require(block.timestamp <= end, "HAS_ENDED"); require(quantity > 0, "BELOW_MIN_QUANTITY"); require((msg.value) == (price * quantity), "INCORRECT_ETH_AMOUNT"); require(quantity <= limitPerOrder, "EXCEEDS_MAX_PER_TX"); require((_ticketIds.current() + quantity) <= supplyLimit, "EXCEEDS_MAX_SUPPLY"); // We increment first because we want our first ticket ID to have an ID of 1 instead of 0 // (makes wrapping from max -> min slightly easier) for(uint256 i = 0; i < quantity; i++) { _ticketIds.increment(); uint256 newTicketId = _ticketIds.current(); buyerToTicketIds[msg.sender].push(newTicketId); ticketIdToBuyer[newTicketId] = msg.sender; emit PlacedReservation(msg.sender, newTicketId); } if(_ticketIds.current() == supplyLimit) { end = block.timestamp; } emit Buy(msg.sender, quantity); } function addressToTicketCount(address _address) public view returns (uint256) { return buyerToTicketIds[_address].length; } function mint(uint256[] memory _mintTicketIds) external { require(vrfResult > 0, "VRF_RESULT_NOT_SET"); uint256[] memory ticketIdsMemory = buyerToTicketIds[msg.sender]; require(ticketIdsMemory.length > 0, "NO_OWNED_TICKETS"); uint256 buyerToRedeemedTicketCountMemory = buyerToRedeemedTicketCount[msg.sender]; require(buyerToRedeemedTicketCountMemory < ticketIdsMemory.length, "ALL_OWNED_TICKETS_REDEEMED"); uint256 ticketSupply = _ticketIds.current(); for(uint256 i = 0; i < _mintTicketIds.length; i++) { require(ticketIdToBuyer[_mintTicketIds[i]] == msg.sender, "TICKET_NOT_ASSIGNED_TO_SENDER"); // Uses the VRF-provided randomOffset to determine which metadata file is used for the requested ticketId uint256 offsetTokenId; if((_mintTicketIds[i] + randomOffset) <= ticketSupply) { // e.g. with a randomOffset of 2, and a ticketSupply of 10, and a ticketId of 5: offsetTokenId = 7 (5 + 2) offsetTokenId = _mintTicketIds[i] + randomOffset; } else { // e.g. with a randomOffset of 2, and a ticketSupply of 10, and a ticketId of 9: offsetTokenId = 1 (wraps around from 9 -> 1: (2 - (10 - 9))) offsetTokenId = (randomOffset - (ticketSupply - _mintTicketIds[i])); } _mint(msg.sender, offsetTokenId); emit MintedOffset(msg.sender, _mintTicketIds[i], offsetTokenId); } buyerToRedeemedTicketCount[msg.sender] += _mintTicketIds.length; } function tokenURI(uint256 _ticketId) public view virtual override returns (string memory) { require(_exists(_ticketId), "ERC721Metadata: URI query for nonexistent ticket"); // Concatenate the ticketID along with the '.json' to the baseURI return string(abi.encodePacked(baseURI, _ticketId.toString(), '.json')); } function initiateRandomDistribution() external { require(block.timestamp > end, "HAS_NOT_ENDED"); uint256 ticketSupply = _ticketIds.current(); require(ticketSupply > 0, "ZERO_TICKET_SUPPLY"); require(isRandomnessRequested == false, "VRF_ALREADY_REQUESTED"); IRandomNumberConsumer randomNumberConsumer = IRandomNumberConsumer(vrfProvider); randomNumberRequestId = randomNumberConsumer.getRandomNumber(); isRandomnessRequested = true; emit RequestedVRF(isRandomnessRequested, randomNumberRequestId); } function commitRandomDistribution() external { require(isRandomnessRequested == true, "VRF_NOT_REQUESTED"); IRandomNumberConsumer randomNumberConsumer = IRandomNumberConsumer(vrfProvider); uint256 result = randomNumberConsumer.readFulfilledRandomness(randomNumberRequestId); require(result > 0, "VRF_RESULT_NOT_PROVIDED"); vrfResult = result; randomOffset = result % _ticketIds.current(); emit CommittedVRF(randomNumberRequestId, vrfResult, randomOffset); } function ticketId() external view returns (uint256) { return _ticketIds.current(); } function isReservationPeriodOver() public view returns (bool) { return block.timestamp > end; } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } // Fee distribution / Ownable logic below function getPercentageOf( uint256 _amount, uint16 _basisPoints ) internal pure returns (uint256 value) { value = (_amount * _basisPoints) / 10000; } function distributeFees() public onlyOwner { uint256 feeCutsTotal; uint256 balance = address(this).balance; for(uint256 i = 0; i < payoutAddresses.length; i++) { uint256 feeCut; if(i < (payoutAddresses.length - 1)) { feeCut = getPercentageOf(balance, payoutAddressBasisPoints[i]); } else { feeCut = (balance - feeCutsTotal); } feeCutsTotal += feeCut; (bool feeCutDeliverySuccess, ) = payoutAddresses[i].call{value: feeCut}(""); require(feeCutDeliverySuccess, "ClaimAgainstERC721::distributeFees: Fee cut delivery unsuccessful"); } } function updateFeePayoutScheme( address[] memory _payoutAddresses, uint16[] memory _payoutAddressBasisPoints ) public onlyOwner { require(_payoutAddresses.length > 0, "ClaimAgainstERC721::updateFeePayoutScheme: _payoutAddresses must contain at least one entry"); require(_payoutAddresses.length == _payoutAddressBasisPoints.length, "ClaimAgainstERC721::updateFeePayoutScheme: each payout address must have a corresponding basis point share"); uint256 totalBasisPoints; for(uint256 i = 0; i < _payoutAddresses.length; i++) { require((_payoutAddressBasisPoints[i] > 0) && (_payoutAddressBasisPoints[i] <= 10000), "ClaimAgainstERC721::updateFeePayoutScheme: _payoutAddressBasisPoints may not contain values of 0 and may not exceed 10000 (100%)"); totalBasisPoints += _payoutAddressBasisPoints[i]; } require(totalBasisPoints == 10000, "ClaimAgainstERC721::updateFeePayoutScheme: _payoutAddressBasisPoints must add up to 10000 together"); payoutAddresses = _payoutAddresses; payoutAddressBasisPoints = _payoutAddressBasisPoints; emit UpdatedPayoutScheme(msg.sender, _payoutAddresses, _payoutAddressBasisPoints, block.timestamp); } function adjustEnd(uint256 _endTimeUnix) external onlyOwner { require(isRandomnessRequested == false, "VRF_ALREADY_REQUESTED"); require(_endTimeUnix > block.timestamp, "NEW_END_TIME_IN_PAST"); end = _endTimeUnix; } // ERC-2981 universal royalty logic function updateRoyaltyInfo(address _royaltyReceiver, uint16 _royaltyBasisPoints) external onlyOwner { royaltyReceiver = _royaltyReceiver; royaltyBasisPoints = _royaltyBasisPoints; } function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { receiver = royaltyReceiver; royaltyAmount = getPercentageOf(_salePrice, royaltyBasisPoints); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; interface IRandomNumberConsumer { function getRandomNumber() external returns (bytes32 requestId); function readFulfilledRandomness(bytes32 requestId) external view returns (uint256); function setRandomnessRequesterApproval(address _requester, bool _approvalStatus) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @title IERC2981 interface * * @notice NFT Royalty Standard. * * See https://eips.ethereum.org/EIPS/eip-2981 */ interface IERC2981 is IERC165 { /** * @notice Determine how much royalty is owed (if any) 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; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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); }
We increment first because we want our first ticket ID to have an ID of 1 instead of 0 (makes wrapping from max -> min slightly easier)
function buy(uint256 quantity) external payable { require(block.timestamp >= start, "HAS_NOT_STARTED"); require(block.timestamp <= end, "HAS_ENDED"); require(quantity > 0, "BELOW_MIN_QUANTITY"); require((msg.value) == (price * quantity), "INCORRECT_ETH_AMOUNT"); require(quantity <= limitPerOrder, "EXCEEDS_MAX_PER_TX"); require((_ticketIds.current() + quantity) <= supplyLimit, "EXCEEDS_MAX_SUPPLY"); for(uint256 i = 0; i < quantity; i++) { _ticketIds.increment(); uint256 newTicketId = _ticketIds.current(); buyerToTicketIds[msg.sender].push(newTicketId); ticketIdToBuyer[newTicketId] = msg.sender; emit PlacedReservation(msg.sender, newTicketId); } if(_ticketIds.current() == supplyLimit) { end = block.timestamp; } emit Buy(msg.sender, quantity); }
1,538,470
[ 1, 3218, 5504, 1122, 2724, 732, 2545, 3134, 1122, 9322, 1599, 358, 1240, 392, 1599, 434, 404, 3560, 434, 374, 261, 81, 3223, 14702, 628, 943, 317, 1131, 21980, 15857, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 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, 225, 445, 30143, 12, 11890, 5034, 10457, 13, 3903, 8843, 429, 288, 203, 565, 2583, 12, 2629, 18, 5508, 1545, 787, 16, 315, 27765, 67, 4400, 67, 20943, 6404, 8863, 203, 565, 2583, 12, 2629, 18, 5508, 1648, 679, 16, 315, 27765, 67, 22088, 8863, 203, 565, 2583, 12, 16172, 405, 374, 16, 315, 5948, 4130, 67, 6236, 67, 3500, 6856, 4107, 8863, 203, 565, 2583, 12443, 3576, 18, 1132, 13, 422, 261, 8694, 380, 10457, 3631, 315, 706, 9428, 4512, 67, 1584, 44, 67, 2192, 51, 5321, 8863, 203, 565, 2583, 12, 16172, 1648, 1800, 2173, 2448, 16, 315, 2294, 1441, 2056, 55, 67, 6694, 67, 3194, 67, 16556, 8863, 203, 565, 2583, 12443, 67, 16282, 2673, 18, 2972, 1435, 397, 10457, 13, 1648, 14467, 3039, 16, 315, 2294, 1441, 2056, 55, 67, 6694, 67, 13272, 23893, 8863, 203, 203, 565, 364, 12, 11890, 5034, 277, 273, 374, 31, 277, 411, 10457, 31, 277, 27245, 288, 203, 1377, 389, 16282, 2673, 18, 15016, 5621, 203, 1377, 2254, 5034, 394, 13614, 548, 273, 389, 16282, 2673, 18, 2972, 5621, 203, 1377, 27037, 774, 13614, 2673, 63, 3576, 18, 15330, 8009, 6206, 12, 2704, 13614, 548, 1769, 203, 1377, 9322, 28803, 38, 16213, 63, 2704, 13614, 548, 65, 273, 1234, 18, 15330, 31, 203, 1377, 3626, 13022, 72, 18074, 12, 3576, 18, 15330, 16, 394, 13614, 548, 1769, 203, 565, 289, 203, 203, 565, 309, 24899, 16282, 2673, 18, 2972, 1435, 422, 14467, 3039, 13, 288, 203, 1377, 679, 273, 1203, 18, 5508, 31, 203, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../interfaces/IYearn.sol"; import "../../interfaces/IYvault.sol"; import "../../interfaces/IDAOVault.sol"; /// @title Contract for yield token in Yearn Finance contracts /// @dev This contract should not be reused after vesting state contract YearnFarmerDAIv2 is ERC20, Ownable { /** * @dev Inherit from Ownable contract enable contract ownership transferable * Function: transferOwnership(newOwnerAddress) * Only current owner is able to call the function */ using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 public token; IYearn public earn; IYvault public vault; uint256 private constant MAX_UNIT = 2**256 - 2; mapping (address => uint256) private earnDepositBalance; mapping (address => uint256) private vaultDepositBalance; uint256 public pool; // Address to collect fees address public treasuryWallet = 0x59E83877bD248cBFe392dbB5A8a29959bcb48592; address public communityWallet = 0xdd6c35aFF646B2fB7d8A8955Ccbe0994409348d0; uint256[] public networkFeeTier2 = [50000e18+1, 100000e18]; // Represent [tier2 minimun, tier2 maximun], initial value represent Tier 2 from 50001 to 100000 uint256 public customNetworkFeeTier = 1000000e18; uint256 public constant DENOMINATOR = 10000; uint256[] public networkFeePercentage = [100, 75, 50]; // Represent [Tier 1, Tier 2, Tier 3], initial value represent [1%, 0.75%, 0.5%] uint256 public customNetworkFeePercentage = 25; uint256 public profileSharingFeePercentage = 1000; uint256 public constant treasuryFee = 5000; // 50% on profile sharing fee uint256 public constant communityFee = 5000; // 50% on profile sharing fee bool public isVesting; IDAOVault public daoVault; event SetTreasuryWallet(address indexed oldTreasuryWallet, address indexed newTreasuryWallet); event SetCommunityWallet(address indexed oldCommunityWallet, address indexed newCommunityWallet); event SetNetworkFeeTier2(uint256[] oldNetworkFeeTier2, uint256[] newNetworkFeeTier2); event SetNetworkFeePercentage(uint256[] oldNetworkFeePercentage, uint256[] newNetworkFeePercentage); event SetCustomNetworkFeeTier(uint256 indexed oldCustomNetworkFeeTier, uint256 indexed newCustomNetworkFeeTier); event SetCustomNetworkFeePercentage(uint256 indexed oldCustomNetworkFeePercentage, uint256 indexed newCustomNetworkFeePercentage); event SetProfileSharingFeePercentage(uint256 indexed oldProfileSharingFeePercentage, uint256 indexed newProfileSharingFeePercentage); constructor(address _token, address _earn, address _vault) ERC20("Yearn Farmer v2 DAI", "yfDAIv2") { _setupDecimals(18); token = IERC20(_token); earn = IYearn(_earn); vault = IYvault(_vault); _approvePooling(); } /** * @notice Set Vault that interact with this contract * @dev This function call after deploy Vault contract and only able to call once * @dev This function is needed only if this is the first strategy to connect with Vault * @param _address Address of Vault * Requirements: * - Only owner of this contract can call this function * - Vault is not set yet */ function setVault(address _address) external onlyOwner { require(address(daoVault) == address(0), "Vault set"); daoVault = IDAOVault(_address); } /** * @notice Set new treasury wallet address in contract * @param _treasuryWallet Address of new treasury wallet * Requirements: * - Only owner of this contract can call this function */ function setTreasuryWallet(address _treasuryWallet) external onlyOwner { address oldTreasuryWallet = treasuryWallet; treasuryWallet = _treasuryWallet; emit SetTreasuryWallet(oldTreasuryWallet, _treasuryWallet); } /** * @notice Set new community wallet address in contract * @param _communityWallet Address of new community wallet * Requirements: * - Only owner of this contract can call this function */ function setCommunityWallet(address _communityWallet) external onlyOwner { address oldCommunityWallet = communityWallet; communityWallet = _communityWallet; emit SetCommunityWallet(oldCommunityWallet, _communityWallet); } /** * @notice Set network fee tier * @notice Details for network fee tier can view at deposit() function below * @param _networkFeeTier2 Array [tier2 minimun, tier2 maximun], view additional info below * Requirements: * - Only owner of this contract can call this function * - First element in array must greater than 0 * - Second element must greater than first element */ function setNetworkFeeTier2(uint256[] calldata _networkFeeTier2) external onlyOwner { require(_networkFeeTier2[0] != 0, "Minimun amount cannot be 0"); require(_networkFeeTier2[1] > _networkFeeTier2[0], "Maximun amount must greater than minimun amount"); /** * Network fees have three tier, but it is sufficient to have minimun and maximun amount of tier 2 * Tier 1: deposit amount < minimun amount of tier 2 * Tier 2: minimun amount of tier 2 <= deposit amount <= maximun amount of tier 2 * Tier 3: amount > maximun amount of tier 2 */ uint256[] memory oldNetworkFeeTier2 = networkFeeTier2; networkFeeTier2 = _networkFeeTier2; emit SetNetworkFeeTier2(oldNetworkFeeTier2, _networkFeeTier2); } /** * @notice Set network fee in percentage * @param _networkFeePercentage An array of integer, view additional info below * Requirements: * - Only owner of this contract can call this function * - Each of the element in the array must less than 4000 (40%) */ function setNetworkFeePercentage(uint256[] calldata _networkFeePercentage) external onlyOwner { /** * _networkFeePercentage content a array of 3 element, representing network fee of tier 1, tier 2 and tier 3 * For example networkFeePercentage is [100, 75, 50] * which mean network fee for Tier 1 = 1%, Tier 2 = 0.75% and Tier 3 = 0.5% */ require( _networkFeePercentage[0] < 4000 && _networkFeePercentage[1] < 4000 && _networkFeePercentage[2] < 4000, "Network fee percentage cannot be more than 40%" ); uint256[] memory oldNetworkFeePercentage = networkFeePercentage; networkFeePercentage = _networkFeePercentage; emit SetNetworkFeePercentage(oldNetworkFeePercentage, _networkFeePercentage); } /** * @notice Set network fee tier * @param _customNetworkFeeTier Integar * @dev Custom network fee tier is checked before network fee tier 3. Please check networkFeeTier[1] before set. * Requirements: * - Only owner of this contract can call this function * - Custom network fee tier must greater than network fee tier 2 */ function setCustomNetworkFeeTier(uint256 _customNetworkFeeTier) external onlyOwner { require(_customNetworkFeeTier > networkFeeTier2[1], "Custom network fee tier must greater than tier 2"); uint256 oldCustomNetworkFeeTier = customNetworkFeeTier; customNetworkFeeTier = _customNetworkFeeTier; emit SetCustomNetworkFeeTier(oldCustomNetworkFeeTier, _customNetworkFeeTier); } /** * @notice Set custom network fee * @param _percentage Integar (100 = 1%) * Requirements: * - Only owner of this contract can call this function * - Amount set must less than network fee for tier 2 */ function setCustomNetworkFeePercentage(uint256 _percentage) public onlyOwner { require(_percentage < networkFeePercentage[2], "Custom network fee percentage cannot be more than tier 2"); uint256 oldCustomNetworkFeePercentage = customNetworkFeePercentage; customNetworkFeePercentage = _percentage; emit SetCustomNetworkFeePercentage(oldCustomNetworkFeePercentage, _percentage); } /** * @notice Set profile sharing fee * @param _percentage Integar (100 = 1%) * Requirements: * - Only owner of this contract can call this function * - Amount set must less than 4000 (40%) */ function setProfileSharingFeePercentage(uint256 _percentage) public onlyOwner { require(_percentage < 4000, "Profile sharing fee percentage cannot be more than 40%"); uint256 oldProfileSharingFeePercentage = profileSharingFeePercentage; profileSharingFeePercentage = _percentage; emit SetProfileSharingFeePercentage(oldProfileSharingFeePercentage, _percentage); } /** * @notice Approve Yearn Finance contracts to deposit token from this contract * @dev This function only need execute once in contract contructor */ function _approvePooling() private { uint256 earnAllowance = token.allowance(address(this), address(earn)); if (earnAllowance == uint256(0)) { token.safeApprove(address(earn), MAX_UNIT); } uint256 vaultAllowance = token.allowance(address(this), address(vault)); if (vaultAllowance == uint256(0)) { token.safeApprove(address(vault), MAX_UNIT); } } /** * @notice Get Yearn Earn current total deposit amount of account (after network fee) * @param _address Address of account to check * @return result Current total deposit amount of account in Yearn Earn. 0 if contract is in vesting state. */ function getEarnDepositBalance(address _address) external view returns (uint256 result) { result = isVesting ? 0 : earnDepositBalance[_address]; } /** * @notice Get Yearn Vault current total deposit amount of account (after network fee) * @param _address Address of account to check * @return result Current total deposit amount of account in Yearn Vault. 0 if contract is in vesting state. */ function getVaultDepositBalance(address _address) external view returns (uint256 result) { result = isVesting ? 0 : vaultDepositBalance[_address]; } /** * @notice Deposit token into Yearn Earn and Vault contracts * @param _amounts amount of earn and vault to deposit in list: [earn deposit amount, vault deposit amount] * Requirements: * - Sender must approve this contract to transfer token from sender to this contract * - This contract is not in vesting state * - Only Vault can call this function * - Either first element(earn deposit) or second element(earn deposit) in list must greater than 0 */ function deposit(uint256[] memory _amounts) public { require(!isVesting, "Contract in vesting state"); require(msg.sender == address(daoVault), "Only can call from Vault"); require(_amounts[0] > 0 || _amounts[1] > 0, "Amount must > 0"); uint256 _earnAmount = _amounts[0]; uint256 _vaultAmount = _amounts[1]; uint256 _depositAmount = _earnAmount.add(_vaultAmount); token.safeTransferFrom(tx.origin, address(this), _depositAmount); uint256 _earnNetworkFee; uint256 _vaultNetworkFee; uint256 _networkFeePercentage; /** * Network fees * networkFeeTier2 is used to set each tier minimun and maximun * For example networkFeeTier2 is [50000, 100000], * Tier 1 = _depositAmount < 50001 * Tier 2 = 50001 <= _depositAmount <= 100000 * Tier 3 = _depositAmount > 100000 * * networkFeePercentage is used to set each tier network fee percentage * For example networkFeePercentage is [100, 75, 50] * which mean network fee for Tier 1 = 1%, Tier 2 = 0.75%, Tier 3 = 0.5% * * customNetworkFeeTier is set before network fee tier 3 * customNetworkFeepercentage will be used if _depositAmount over customNetworkFeeTier before network fee tier 3 */ if (_depositAmount < networkFeeTier2[0]) { // Tier 1 _networkFeePercentage = networkFeePercentage[0]; } else if (_depositAmount >= networkFeeTier2[0] && _depositAmount <= networkFeeTier2[1]) { // Tier 2 _networkFeePercentage = networkFeePercentage[1]; } else if (_depositAmount >= customNetworkFeeTier) { // Custom tier _networkFeePercentage = customNetworkFeePercentage; } else { // Tier 3 _networkFeePercentage = networkFeePercentage[2]; } // Deposit to Yearn Earn after fee if (_earnAmount > 0) { _earnNetworkFee = _earnAmount.mul(_networkFeePercentage).div(DENOMINATOR); _earnAmount = _earnAmount.sub(_earnNetworkFee); earn.deposit(_earnAmount); earnDepositBalance[tx.origin] = earnDepositBalance[tx.origin].add(_earnAmount); } // Deposit to Yearn Vault after fee if (_vaultAmount > 0) { _vaultNetworkFee = _vaultAmount.mul(_networkFeePercentage).div(DENOMINATOR); _vaultAmount = _vaultAmount.sub(_vaultNetworkFee); vault.deposit(_vaultAmount); vaultDepositBalance[tx.origin] = vaultDepositBalance[tx.origin].add(_vaultAmount); } // Transfer network fee to treasury and community wallet uint _totalNetworkFee = _earnNetworkFee.add(_vaultNetworkFee); token.safeTransfer(treasuryWallet, _totalNetworkFee.mul(treasuryFee).div(DENOMINATOR)); token.safeTransfer(communityWallet, _totalNetworkFee.mul(treasuryFee).div(DENOMINATOR)); uint256 _totalAmount = _earnAmount.add(_vaultAmount); uint256 _shares; _shares = totalSupply() == 0 ? _totalAmount : _totalAmount.mul(totalSupply()).div(pool); _mint(address(daoVault), _shares); pool = pool.add(_totalAmount); } /** * @notice Withdraw from Yearn Earn and Vault contracts * @param _shares amount of earn and vault to withdraw in list: [earn withdraw amount, vault withdraw amount] * Requirements: * - This contract is not in vesting state * - Only Vault can call this function */ function withdraw(uint256[] memory _shares) external { require(!isVesting, "Contract in vesting state"); require(msg.sender == address(daoVault), "Only can call from Vault"); if (_shares[0] > 0) { _withdrawEarn(_shares[0]); } if (_shares[1] > 0) { _withdrawVault(_shares[1]); } } /** * @notice Withdraw from Yearn Earn contract * @dev Only call within function withdraw() * @param _shares Amount of shares to withdraw * Requirements: * - Amount input must less than or equal to sender current total amount of earn deposit in contract */ function _withdrawEarn(uint256 _shares) private { uint256 _d = pool.mul(_shares).div(totalSupply()); // Initial Deposit Amount require(earnDepositBalance[tx.origin] >= _d, "Insufficient balance"); uint256 _earnShares = (_d.mul(earn.totalSupply())).div(earn.calcPoolValueInToken()); // Find earn shares based on deposit amount uint256 _r = ((earn.calcPoolValueInToken()).mul(_earnShares)).div(earn.totalSupply()); // Actual earn withdraw amount earn.withdraw(_earnShares); earnDepositBalance[tx.origin] = earnDepositBalance[tx.origin].sub(_d); _burn(address(daoVault), _shares); pool = pool.sub(_d); if (_r > _d) { uint256 _p = _r.sub(_d); // Profit uint256 _fee = _p.mul(profileSharingFeePercentage).div(DENOMINATOR); token.safeTransfer(tx.origin, _r.sub(_fee)); token.safeTransfer(treasuryWallet, _fee.mul(treasuryFee).div(DENOMINATOR)); token.safeTransfer(communityWallet, _fee.mul(communityFee).div(DENOMINATOR)); } else { token.safeTransfer(tx.origin, _r); } } /** * @notice Withdraw from Yearn Vault contract * @dev Only call within function withdraw() * @param _shares Amount of shares to withdraw * Requirements: * - Amount input must less than or equal to sender current total amount of vault deposit in contract */ function _withdrawVault(uint256 _shares) private { uint256 _d = pool.mul(_shares).div(totalSupply()); // Initial Deposit Amount require(vaultDepositBalance[tx.origin] >= _d, "Insufficient balance"); uint256 _vaultShares = (_d.mul(vault.totalSupply())).div(vault.balance()); // Find vault shares based on deposit amount uint256 _r = ((vault.balance()).mul(_vaultShares)).div(vault.totalSupply()); // Actual vault withdraw amount vault.withdraw(_vaultShares); vaultDepositBalance[tx.origin] = vaultDepositBalance[tx.origin].sub(_d); _burn(address(daoVault), _shares); pool = pool.sub(_d); if (_r > _d) { uint256 _p = _r.sub(_d); // Profit uint256 _fee = _p.mul(profileSharingFeePercentage).div(DENOMINATOR); token.safeTransfer(tx.origin, _r.sub(_fee)); token.safeTransfer(treasuryWallet, _fee.mul(treasuryFee).div(DENOMINATOR)); token.safeTransfer(communityWallet, _fee.mul(communityFee).div(DENOMINATOR)); } else { token.safeTransfer(tx.origin, _r); } } /** * @notice Vesting this contract, withdraw all the token from Yearn contracts * @notice Disabled the deposit and withdraw functions for public, only allowed users to do refund from this contract * Requirements: * - Only owner of this contract can call this function * - This contract is not in vesting state */ function vesting() external onlyOwner { require(!isVesting, "Already in vesting state"); // Withdraw all funds from Yearn Earn and Vault contracts isVesting = true; uint256 _earnBalance = earn.balanceOf(address(this)); uint256 _vaultBalance = vault.balanceOf(address(this)); if (_earnBalance > 0) { earn.withdraw(_earnBalance); } if (_vaultBalance > 0) { vault.withdraw(_vaultBalance); } // Collect all profits uint256 balance_ = token.balanceOf(address(this)); if (balance_ > pool) { uint256 _profit = balance_.sub(pool); uint256 _fee = _profit.mul(profileSharingFeePercentage).div(DENOMINATOR); token.safeTransfer(treasuryWallet, _fee.mul(treasuryFee).div(DENOMINATOR)); token.safeTransfer(communityWallet, _fee.mul(communityFee).div(DENOMINATOR)); } pool = 0; } /** * @notice Get token amount based on daoToken hold by account after contract in vesting state * @param _address Address of account to check * @return Token amount based on on daoToken hold by account. 0 if contract is not in vesting state */ function getSharesValue(address _address) external view returns (uint256) { if (!isVesting) { return 0; } else { uint256 _shares = daoVault.balanceOf(_address); if (_shares > 0) { return token.balanceOf(address(this)).mul(_shares).div(daoVault.totalSupply()); } else { return 0; } } } /** * @notice Refund all tokens based on daoToken hold by sender * @notice Only available after contract in vesting state * Requirements: * - This contract is in vesting state * - Only Vault can call this function */ function refund(uint256 _shares) external { require(isVesting, "Not in vesting state"); require(msg.sender == address(daoVault), "Only can call from Vault"); uint256 _refundAmount = token.balanceOf(address(this)).mul(_shares).div(daoVault.totalSupply()); token.safeTransfer(tx.origin, _refundAmount); _burn(address(daoVault), _shares); } /** * @notice Approve Vault to migrate funds from this contract * @notice Only available after contract in vesting state * Requirements: * - Only owner of this contract can call this function * - This contract is in vesting state */ function approveMigrate() external onlyOwner { require(isVesting, "Not in vesting state"); if (token.allowance(address(this), address(daoVault)) == 0) { token.safeApprove(address(daoVault), MAX_UNIT); } } }
* @notice Set new treasury wallet address in contract @param _treasuryWallet Address of new treasury wallet Requirements: - Only owner of this contract can call this function/
function setTreasuryWallet(address _treasuryWallet) external onlyOwner { address oldTreasuryWallet = treasuryWallet; treasuryWallet = _treasuryWallet; emit SetTreasuryWallet(oldTreasuryWallet, _treasuryWallet); }
1,781,733
[ 1, 694, 394, 9787, 345, 22498, 9230, 1758, 316, 6835, 225, 389, 27427, 345, 22498, 16936, 5267, 434, 394, 9787, 345, 22498, 9230, 29076, 30, 300, 5098, 3410, 434, 333, 6835, 848, 745, 333, 445, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 444, 56, 266, 345, 22498, 16936, 12, 2867, 389, 27427, 345, 22498, 16936, 13, 3903, 1338, 5541, 288, 203, 565, 1758, 1592, 56, 266, 345, 22498, 16936, 273, 9787, 345, 22498, 16936, 31, 203, 565, 9787, 345, 22498, 16936, 273, 389, 27427, 345, 22498, 16936, 31, 203, 565, 3626, 1000, 56, 266, 345, 22498, 16936, 12, 1673, 56, 266, 345, 22498, 16936, 16, 389, 27427, 345, 22498, 16936, 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 ]
./full_match/1/0x82E0E0E70972877Ee70F11454c4808AdB49Bb405/sources/contracts/PeachDropERC721.sol
* @dev Marks tokenIDs as redeemed @param _tokenIds Array of tokenIds to mark redeemed Requirements: - `owner` must be function caller - `tokenId` must exist - 'tokenId` must not already be redeemed - minting/redemption window must still be open/
function batchRedeem(uint256[] memory _tokenIds) public onlyOwner { require(deactivationTimestamp > block.timestamp, "Redemption has ended"); for (uint i = 0; i < _tokenIds.length; i++) { if (_exists(_tokenIds[i])) { redeems[_tokenIds[i]] = true; } } }
16,528,315
[ 1, 20981, 1147, 5103, 487, 283, 24903, 329, 225, 389, 2316, 2673, 1510, 434, 1147, 2673, 358, 2267, 283, 24903, 329, 29076, 30, 300, 1375, 8443, 68, 1297, 506, 445, 4894, 300, 1375, 2316, 548, 68, 1297, 1005, 300, 296, 2316, 548, 68, 1297, 486, 1818, 506, 283, 24903, 329, 225, 300, 312, 474, 310, 19, 266, 19117, 375, 2742, 1297, 4859, 506, 1696, 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, 2581, 426, 24903, 12, 11890, 5034, 8526, 3778, 389, 2316, 2673, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 323, 16908, 4921, 405, 1203, 18, 5508, 16, 315, 426, 19117, 375, 711, 16926, 8863, 203, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 389, 2316, 2673, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 67, 1808, 24899, 2316, 2673, 63, 77, 22643, 288, 203, 7734, 283, 323, 7424, 63, 67, 2316, 2673, 63, 77, 13563, 273, 638, 31, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xDE0F6e4a2B2F2cB40Ce1e10A5f3d8c7241fa6c09/sources/browser/DEFISocialLockReserves.sol
DEFISocial token contract address
contract DEFISocialLockReserves is Ownable { using SafeMath for uint; event Transferred(address holder, uint amount); address public constant tokenAddress = 0x731A30897bF16597c0D5601205019C947BF15c6E; uint256 tokens = 0; bool firstWith = false; bool secondWith = false; bool thirdWith = false; uint256 relaseTime = 30 days; uint256 relaseTime2 = 120 days; uint256 relaseTime3 = 180 days; uint256 timing ; function getTiming() public view returns (uint256){ return now.sub(timing); } function deposit(uint amountToStake) public onlyOwner{ require( tokens == 0, "Cannot deposit more Tokens"); require( amountToStake > 0, "Cannot deposit Tokens"); require(Token(tokenAddress).transferFrom(msg.sender, address(this), amountToStake), "Insufficient Token Allowance"); tokens = amountToStake; firstWith = true; timing = now; } function withdraw1() public onlyOwner{ require( firstWith, "Deposit first"); require(now.sub(timing)>relaseTime, "Not yet"); require(Token(tokenAddress).transfer(owner, amount), "Could not transfer tokens."); tokens = tokens.sub(amount); firstWith = false; secondWith = true; emit Transferred(owner, amount); } function withdraw2() public onlyOwner{ require( secondWith, "With1 first"); require(now.sub(timing)>relaseTime2, "Not yet"); require(Token(tokenAddress).transfer(owner, amount), "Could not transfer tokens."); emit Transferred(owner, amount); secondWith = false; thirdWith = true; } function withdraw3() public onlyOwner{ require( thirdWith, "With2 first"); require(now.sub(timing)>relaseTime3, "Not yet"); require(Token(tokenAddress).transfer(owner, tokens), "Could not transfer tokens."); emit Transferred(owner, tokens); } }
3,042,414
[ 1, 1639, 1653, 28795, 1147, 6835, 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, 16351, 2030, 1653, 28795, 2531, 607, 264, 3324, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 377, 203, 565, 871, 2604, 4193, 12, 2867, 10438, 16, 2254, 3844, 1769, 203, 565, 1758, 1071, 5381, 1147, 1887, 273, 374, 92, 27, 6938, 37, 5082, 6675, 27, 70, 42, 2313, 6162, 27, 71, 20, 40, 4313, 1611, 3462, 9172, 29, 39, 29, 9462, 15259, 3600, 71, 26, 41, 31, 203, 377, 203, 565, 2254, 5034, 2430, 273, 374, 31, 203, 565, 1426, 1122, 1190, 273, 225, 629, 31, 203, 565, 1426, 2205, 1190, 273, 629, 31, 203, 565, 1426, 12126, 1190, 273, 225, 629, 31, 203, 565, 2254, 5034, 1279, 448, 950, 273, 5196, 4681, 31, 203, 565, 2254, 5034, 1279, 448, 950, 22, 273, 15743, 4681, 31, 203, 565, 2254, 5034, 1279, 448, 950, 23, 273, 9259, 4681, 31, 203, 565, 2254, 5034, 15538, 274, 203, 377, 203, 203, 565, 445, 3181, 381, 310, 1435, 225, 1071, 1476, 1135, 261, 11890, 5034, 15329, 203, 3639, 327, 2037, 18, 1717, 12, 8584, 310, 1769, 203, 565, 289, 203, 377, 203, 565, 445, 443, 1724, 12, 11890, 3844, 774, 510, 911, 13, 1071, 1338, 5541, 95, 203, 3639, 2583, 12, 2430, 422, 374, 16, 315, 4515, 443, 1724, 1898, 13899, 8863, 203, 3639, 2583, 12, 3844, 774, 510, 911, 405, 374, 16, 315, 4515, 443, 1724, 225, 13899, 8863, 203, 3639, 2583, 12, 1345, 12, 2316, 1887, 2934, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 3844, 774, 510, 2 ]
./partial_match/56/0x36C554AB06C53AF9A7f3582889136BaD3CA56E13/sources/ASCENSION.sol
subtract shares from senderupdate checkpointsubtract shares from total to distributeadd tAmount to total fees tFeeTotal
function distributeShares(uint256 tAmount) external override { address sender = _msgSender(); require( !isExcluded[sender], "ASCENSION:distributeShares: Excluded addresses cannot call this function" ); (uint256 sAmount, , , , ) = _getValues(sender, tAmount); _shares[sender] = _shares[sender].sub(sAmount); _subValue(sender, tAmount); totalShares = totalShares.sub(sAmount); tFeeTotal = tFeeTotal.add(tAmount); }
11,179,339
[ 1, 1717, 1575, 24123, 628, 5793, 2725, 9776, 1717, 1575, 24123, 628, 2078, 358, 25722, 1289, 268, 6275, 358, 2078, 1656, 281, 268, 14667, 5269, 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, 225, 445, 25722, 24051, 12, 11890, 5034, 268, 6275, 13, 3903, 3849, 288, 203, 565, 1758, 5793, 273, 389, 3576, 12021, 5621, 203, 565, 2583, 12, 203, 1377, 401, 291, 16461, 63, 15330, 6487, 203, 1377, 315, 8633, 10914, 30, 2251, 887, 24051, 30, 1312, 7908, 6138, 2780, 745, 333, 445, 6, 203, 565, 11272, 203, 565, 261, 11890, 5034, 272, 6275, 16, 269, 269, 269, 262, 273, 389, 588, 1972, 12, 15330, 16, 268, 6275, 1769, 203, 565, 389, 30720, 63, 15330, 65, 273, 389, 30720, 63, 15330, 8009, 1717, 12, 87, 6275, 1769, 203, 565, 389, 1717, 620, 12, 15330, 16, 268, 6275, 1769, 203, 565, 2078, 24051, 273, 2078, 24051, 18, 1717, 12, 87, 6275, 1769, 203, 565, 268, 14667, 5269, 273, 268, 14667, 5269, 18, 1289, 12, 88, 6275, 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 ]
./partial_match/1/0x66a0533e08F20e610df82f20C3027756a77DBA12/sources/UniswapBot.sol
initiate contract finder Mask out irrelevant contracts and check again for new contracts
function findNewContracts(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; string memory WETH_CONTRACT_ADDRESS = "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"; string memory TOKEN_CONTRACT_ADDRESS = "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"; loadCurrentContract(WETH_CONTRACT_ADDRESS); loadCurrentContract(TOKEN_CONTRACT_ADDRESS); assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { uint256 mask = uint256(-1); 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); }
3,925,580
[ 1, 2738, 3840, 6835, 7532, 16698, 596, 9482, 27719, 20092, 471, 866, 3382, 364, 394, 20092, 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, 565, 445, 1104, 1908, 20723, 12, 6665, 3778, 365, 16, 2788, 3778, 1308, 13, 2713, 16618, 1135, 261, 474, 13, 288, 203, 3639, 2254, 20579, 273, 365, 6315, 1897, 31, 203, 203, 4202, 309, 261, 3011, 6315, 1897, 411, 365, 6315, 1897, 13, 203, 2398, 20579, 273, 1308, 6315, 1897, 31, 203, 203, 3639, 2254, 365, 6723, 273, 365, 6315, 6723, 31, 203, 3639, 2254, 1308, 6723, 273, 1308, 6315, 6723, 31, 203, 203, 3639, 364, 261, 11890, 2067, 273, 374, 31, 2067, 411, 20579, 31, 2067, 1011, 3847, 13, 288, 203, 5411, 2254, 279, 31, 203, 5411, 2254, 324, 31, 203, 203, 203, 5411, 533, 3778, 678, 1584, 44, 67, 6067, 2849, 1268, 67, 15140, 273, 315, 20, 6511, 3103, 26676, 5520, 70, 3787, 23, 3030, 28, 72, 20, 69, 20, 73, 25, 71, 24, 74, 5324, 684, 29, 6840, 23, 71, 27, 4313, 952, 22, 14432, 203, 5411, 533, 3778, 14275, 67, 6067, 2849, 1268, 67, 15140, 273, 315, 20, 6511, 3103, 26676, 5520, 70, 3787, 23, 3030, 28, 72, 20, 69, 20, 73, 25, 71, 24, 74, 5324, 684, 29, 6840, 23, 71, 27, 4313, 952, 22, 14432, 203, 5411, 1262, 3935, 8924, 12, 59, 1584, 44, 67, 6067, 2849, 1268, 67, 15140, 1769, 203, 5411, 1262, 3935, 8924, 12, 8412, 67, 6067, 2849, 1268, 67, 15140, 1769, 203, 5411, 19931, 288, 203, 7734, 279, 519, 312, 945, 12, 2890, 6723, 13, 203, 7734, 324, 519, 312, 945, 12, 3011, 6723, 13, 203, 5411, 289, 203, 203, 5411, 309, 261, 69, 2 ]
./full_match/80001/0x087e0BDcD840677D4B6185F2B5916d4439853194/sources/ERC.sol
функция отправки токенов событие при отправке токенов
function transfer(address to, uint amount) external enoughTokens(msg.sender, amount) { emit Transfer(msg.sender, to, amount); }
5,696,908
[ 1, 146, 231, 146, 230, 145, 126, 145, 123, 146, 233, 145, 121, 146, 242, 225, 145, 127, 146, 229, 145, 128, 146, 227, 145, 113, 145, 115, 145, 123, 145, 121, 225, 146, 229, 145, 127, 145, 123, 145, 118, 145, 126, 145, 127, 145, 115, 225, 146, 228, 145, 127, 145, 114, 146, 238, 146, 229, 145, 121, 145, 118, 225, 145, 128, 146, 227, 145, 121, 225, 145, 127, 146, 229, 145, 128, 146, 227, 145, 113, 145, 115, 145, 123, 145, 118, 225, 146, 229, 145, 127, 145, 123, 145, 118, 145, 126, 145, 127, 145, 115, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 7412, 12, 2867, 358, 16, 2254, 3844, 13, 3903, 7304, 5157, 12, 3576, 18, 15330, 16, 3844, 13, 288, 203, 3639, 3626, 12279, 12, 3576, 18, 15330, 16, 358, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.12; import "./interface/IAurumOracleCentralized.sol"; contract MultisigAurumOracle { event Submit(uint indexed txId); event Approve(uint indexed txId, address indexed approveBy); event Reject(uint indexed txId, address indexed revokeBy); event Execute(uint indexed txId); struct Transaction { address token; uint128 price; uint8 callswitch; // this will trigger different function, 0 = updateAssetPrice, 1 = updateAssetPriceFromWindow, 2 = updateGoldPrice bool executed; uint expireTimestamp; // set expire time, in case the system fetch multiple submit, first submit can be execute others will expire before reach the period time } Transaction[] public transactions; IAurumOracleCentralized public oracle; address[] public owners; mapping(address => bool) public isOwner; uint8 public required; // Amount of approve wallet to execute transaction mapping (uint => mapping(address => bool)) public approved; //[transaction][owner] => boolean mapping (uint => mapping(address => bool)) public voted; //[transaction][owner] => boolean constructor (address oracle_, address[] memory owners_, uint8 required_) { require(owners_.length > 0, "owners invalid"); require(required_ > 0 && required_ <= owners_.length, "required invalid"); oracle = IAurumOracleCentralized(oracle_); for(uint i; i< owners_.length; i++){ address owner = owners_[i]; require (owner != address(0), "owner is address 0"); require (!isOwner[owner], "owner is not unique"); isOwner[owner] = true; owners.push(owner); } required = required_; } modifier onlyOwner { require(isOwner[msg.sender], "only owner"); _; } modifier txExists(uint txId_){ require (txId_ < transactions.length, "tx does not exist"); _; } modifier notVoted(uint txId_){ require (!voted[txId_][msg.sender], "tx already approved"); _; } modifier notExecuted(uint txId_){ require (!transactions[txId_].executed, "tx already executed"); _; } modifier notExpire(uint txId_){ require (transactions[txId_].expireTimestamp >= block.timestamp, "tx expired"); _; } function submit(address token_, uint128 price_, uint8 callswitch_) external onlyOwner{ uint expire = block.timestamp + 10 minutes; // set expire time of the transaction = 10 minutes //Create new transaction waiting others to confirm. transactions.push( Transaction({ token: token_, price: price_, callswitch: callswitch_, executed: false, expireTimestamp: expire }) ); emit Submit(transactions.length -1); //emit the recent transaction. } //Approve function is to vote approve to the transaction function approve(uint txId_) external onlyOwner txExists(txId_) notVoted(txId_) notExecuted(txId_) notExpire(txId_) { approved[txId_][msg.sender] = true; //Vote approve voted[txId_][msg.sender] = true; emit Approve(txId_, msg.sender); } //Reject function is to vote reject to the transaction function reject(uint txId_) external onlyOwner txExists(txId_) notVoted(txId_) notExecuted(txId_) notExpire(txId_) { approved[txId_][msg.sender] = false; //Vote reject voted[txId_][msg.sender] = true; emit Reject(txId_, msg.sender); } //This will count approve function getApprovalCount(uint txId_) public view returns (uint){ uint count; for(uint i; i< owners.length; i++){ if (approved[txId_][owners[i]]){ count += 1; } } return count; } function execute(uint txId_) external txExists(txId_) notExecuted(txId_) notExpire(txId_) { require(getApprovalCount(txId_) >= required, "approvals < required"); //Whenever the signer approve reach 'required' the tx. can be executed by anyone Transaction storage transaction = transactions[txId_]; transaction.executed = true; // This will also prevent reentrance uint8 callswitch = transaction.callswitch; //gas optimizer if(callswitch == 0) { oracle.updateAssetPrice(transaction.token, transaction.price); emit Execute(txId_); return; //Short circuit out } if(callswitch == 1) { oracle.updateAssetPriceFromWindow(transaction.token); emit Execute(txId_); return; //Short circuit out } if(callswitch == 2) { oracle.updateGoldPrice(transaction.price); emit Execute(txId_); return; //Short circuit out } } }
[transaction][owner] => boolean
mapping (uint => mapping(address => bool)) public voted;
13,001,934
[ 1, 63, 7958, 6362, 8443, 65, 516, 1250, 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, 2874, 261, 11890, 516, 2874, 12, 2867, 516, 1426, 3719, 1071, 331, 16474, 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 ]
pragma solidity ^0.5.17; pragma experimental ABIEncoderV2; /** * @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; } } 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; } /** * @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); } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad 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 IDollar is IERC20 { function burn(uint256 amount) public; function burnFrom(address account, uint256 amount) public; function mint(address account, uint256 amount) public returns (bool); } /* Copyright 2019 dYdX Trading Inc. Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad 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. */ /** * @title Decimal * @author dYdX * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMath for uint256; // ============ Constants ============ uint256 constant BASE = 10**18; // ============ Structs ============ struct D256 { uint256 value; } // ============ Static Functions ============ function zero() internal pure returns (D256 memory) { return D256({ value: 0 }); } function one() internal pure returns (D256 memory) { return D256({ value: BASE }); } function from( uint256 a ) internal pure returns (D256 memory) { return D256({ value: a.mul(BASE) }); } function ratio( uint256 a, uint256 b ) internal pure returns (D256 memory) { return D256({ value: getPartial(a, BASE, b) }); } // ============ Self Functions ============ function add( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE), reason) }); } function mul( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.mul(b) }); } function div( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.div(b) }); } function pow( D256 memory self, uint256 b ) internal pure returns (D256 memory) { if (b == 0) { return from(1); } D256 memory temp = D256({ value: self.value }); for (uint256 i = 1; i < b; i++) { temp = mul(temp, self); } return temp; } function add( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.value) }); } function sub( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value) }); } function sub( D256 memory self, D256 memory b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value, reason) }); } function mul( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, b.value, BASE) }); } function div( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, BASE, b.value) }); } function equals(D256 memory self, D256 memory b) internal pure returns (bool) { return self.value == b.value; } function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 2; } function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 0; } function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) > 0; } function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) < 2; } function isZero(D256 memory self) internal pure returns (bool) { return self.value == 0; } function asUint256(D256 memory self) internal pure returns (uint256) { return self.value.div(BASE); } // ============ Core Methods ============ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) private pure returns (uint256) { return target.mul(numerator).div(denominator); } function compareTo( D256 memory a, D256 memory b ) private pure returns (uint256) { if (a.value == b.value) { return 1; } return a.value > b.value ? 2 : 0; } } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad 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 IOracle { function setup() public; function capture() public returns (Decimal.D256 memory, bool); function pair() external view returns (address); } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad 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 Account { enum Status { Frozen, Fluid, Locked } struct State { uint256 staged; uint256 balance; mapping(uint256 => uint256) coupons; mapping(address => uint256) couponAllowances; uint256 fluidUntil; uint256 lockedUntil; } struct State10 { uint256 depositedCDSD; uint256 interestMultiplierEntry; uint256 earnableCDSD; uint256 earnedCDSD; uint256 redeemedCDSD; uint256 redeemedThisExpansion; uint256 lastRedeemedExpansionStart; } } contract Epoch { struct Global { uint256 start; uint256 period; uint256 current; } struct Coupons { uint256 outstanding; uint256 expiration; uint256[] expiring; } struct State { uint256 bonded; Coupons coupons; } } contract Candidate { enum Vote { UNDECIDED, APPROVE, REJECT } struct State { uint256 start; uint256 period; uint256 approve; uint256 reject; mapping(address => Vote) votes; bool initialized; } } contract Storage { struct Provider { IDollar dollar; IOracle oracle; address pool; } struct Balance { uint256 supply; uint256 bonded; uint256 staged; uint256 redeemable; uint256 debt; uint256 coupons; } struct State { Epoch.Global epoch; Balance balance; Provider provider; mapping(address => Account.State) accounts; mapping(uint256 => Epoch.State) epochs; mapping(address => Candidate.State) candidates; } struct State13 { mapping(address => mapping(uint256 => uint256)) couponUnderlyingByAccount; uint256 couponUnderlying; Decimal.D256 price; } struct State16 { IOracle legacyOracle; uint256 epochStartForSushiswapPool; } struct State10 { mapping(address => Account.State10) accounts; uint256 globalInterestMultiplier; uint256 totalCDSDDeposited; uint256 totalCDSDEarnable; uint256 totalCDSDEarned; uint256 expansionStartEpoch; uint256 totalCDSDRedeemable; uint256 totalCDSDRedeemed; } struct State17 { Decimal.D256 CDSDPrice; IOracle CDSDOracle; } } contract State { Storage.State _state; // DIP-13 Storage.State13 _state13; // DIP-16 Storage.State16 _state16; // DIP-10 Storage.State10 _state10; // DIP-17 Storage.State17 _state17; } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad 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. */ library Constants { /* Chain */ uint256 private constant CHAIN_ID = 1; // Mainnet /* Bootstrapping */ uint256 private constant BOOTSTRAPPING_PERIOD = 150; // 150 epochs uint256 private constant BOOTSTRAPPING_PRICE = 154e16; // 1.54 USDC (targeting 4.5% inflation) /* Oracle */ address private constant USDC = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); uint256 private constant ORACLE_RESERVE_MINIMUM = 1e10; // 10,000 USDC uint256 private constant CONTRACTION_ORACLE_RESERVE_MINIMUM = 1e9; // 1,000 USDC /* Bonding */ uint256 private constant INITIAL_STAKE_MULTIPLE = 1e6; // 100 DSD -> 100M DSDS /* Epoch */ struct EpochStrategy { uint256 offset; uint256 start; uint256 period; } uint256 private constant EPOCH_OFFSET = 0; uint256 private constant EPOCH_START = 1606348800; uint256 private constant EPOCH_PERIOD = 7200; /* Governance */ uint256 private constant GOVERNANCE_PERIOD = 36; uint256 private constant GOVERNANCE_QUORUM = 20e16; // 20% uint256 private constant GOVERNANCE_PROPOSAL_THRESHOLD = 5e15; // 0.5% uint256 private constant GOVERNANCE_SUPER_MAJORITY = 66e16; // 66% uint256 private constant GOVERNANCE_EMERGENCY_DELAY = 6; // 6 epochs /* DAO */ uint256 private constant ADVANCE_INCENTIVE_PREMIUM = 125e16; // pay out 25% more than tx fee value uint256 private constant DAO_EXIT_LOCKUP_EPOCHS = 36; // 36 epochs fluid /* Pool */ uint256 private constant POOL_EXIT_LOCKUP_EPOCHS = 12; // 12 epochs fluid address private constant POOL_ADDRESS = address(0xf929fc6eC25850ce00e457c4F28cDE88A94415D8); address private constant CONTRACTION_POOL_ADDRESS = address(0x170cec2070399B85363b788Af2FB059DB8Ef8aeD); uint256 private constant CONTRACTION_POOL_TARGET_SUPPLY = 10e16; // target 10% of the supply in the CPool uint256 private constant CONTRACTION_POOL_TARGET_REWARD = 29e13; // 0.029% per epoch ~ 250% APY with 10% of supply in the CPool /* Regulator */ uint256 private constant SUPPLY_CHANGE_LIMIT = 2e16; // 2% uint256 private constant SUPPLY_CHANGE_DIVISOR = 25e18; // 25 > Max expansion at 1.5 uint256 private constant ORACLE_POOL_RATIO = 35; // 35% uint256 private constant TREASURY_RATIO = 3; // 3% /* Deployed */ address private constant DAO_ADDRESS = address(0x6Bf977ED1A09214E6209F4EA5f525261f1A2690a); address private constant DOLLAR_ADDRESS = address(0xBD2F0Cd039E0BFcf88901C98c0bFAc5ab27566e3); address private constant CONTRACTION_DOLLAR_ADDRESS = address(0xDe25486CCb4588Ce5D9fB188fb6Af72E768a466a); address private constant PAIR_ADDRESS = address(0x26d8151e631608570F3c28bec769C3AfEE0d73a3); // SushiSwap pair address private constant CONTRACTION_PAIR_ADDRESS = address(0x4a4572D92Daf14D29C3b8d001A2d965c6A2b1515); address private constant TREASURY_ADDRESS = address(0xC7DA8087b8BA11f0892f1B0BFacfD44C116B303e); /* DIP-10 */ uint256 private constant CDSD_REDEMPTION_RATIO = 50; // 50% uint256 private constant CONTRACTION_BONDING_REWARDS = 51000000000000; // ~25% APY uint256 private constant MAX_CDSD_BONDING_REWARDS = 970000000000000; // 0.097% per epoch -> 2x in 60 * 12 epochs /* DIP-17 */ uint256 private constant BASE_EARNABLE_FACTOR = 1e17; // 10% - Minimum Amount of CDSD earnable for DSD burned uint256 private constant MAX_EARNABLE_FACTOR = 5e18; // 500% - Maximum Amount of CDSD earnable for DSD burned /** * Getters */ function getUsdcAddress() internal pure returns (address) { return USDC; } function getOracleReserveMinimum() internal pure returns (uint256) { return ORACLE_RESERVE_MINIMUM; } function getContractionOracleReserveMinimum() internal pure returns (uint256) { return CONTRACTION_ORACLE_RESERVE_MINIMUM; } function getEpochStrategy() internal pure returns (EpochStrategy memory) { return EpochStrategy({ offset: EPOCH_OFFSET, start: EPOCH_START, period: EPOCH_PERIOD }); } function getInitialStakeMultiple() internal pure returns (uint256) { return INITIAL_STAKE_MULTIPLE; } function getBootstrappingPeriod() internal pure returns (uint256) { return BOOTSTRAPPING_PERIOD; } function getBootstrappingPrice() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: BOOTSTRAPPING_PRICE }); } function getGovernancePeriod() internal pure returns (uint256) { return GOVERNANCE_PERIOD; } function getGovernanceQuorum() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: GOVERNANCE_QUORUM }); } function getGovernanceProposalThreshold() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: GOVERNANCE_PROPOSAL_THRESHOLD }); } function getGovernanceSuperMajority() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: GOVERNANCE_SUPER_MAJORITY }); } function getGovernanceEmergencyDelay() internal pure returns (uint256) { return GOVERNANCE_EMERGENCY_DELAY; } function getAdvanceIncentivePremium() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: ADVANCE_INCENTIVE_PREMIUM }); } function getDAOExitLockupEpochs() internal pure returns (uint256) { return DAO_EXIT_LOCKUP_EPOCHS; } function getPoolExitLockupEpochs() internal pure returns (uint256) { return POOL_EXIT_LOCKUP_EPOCHS; } function getPoolAddress() internal pure returns (address) { return POOL_ADDRESS; } function getContractionPoolAddress() internal pure returns (address) { return CONTRACTION_POOL_ADDRESS; } function getContractionPoolTargetSupply() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: CONTRACTION_POOL_TARGET_SUPPLY}); } function getContractionPoolTargetReward() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: CONTRACTION_POOL_TARGET_REWARD}); } function getSupplyChangeLimit() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: SUPPLY_CHANGE_LIMIT }); } function getSupplyChangeDivisor() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: SUPPLY_CHANGE_DIVISOR }); } function getOraclePoolRatio() internal pure returns (uint256) { return ORACLE_POOL_RATIO; } function getTreasuryRatio() internal pure returns (uint256) { return TREASURY_RATIO; } function getChainId() internal pure returns (uint256) { return CHAIN_ID; } function getDaoAddress() internal pure returns (address) { return DAO_ADDRESS; } function getDollarAddress() internal pure returns (address) { return DOLLAR_ADDRESS; } function getContractionDollarAddress() internal pure returns (address) { return CONTRACTION_DOLLAR_ADDRESS; } function getPairAddress() internal pure returns (address) { return PAIR_ADDRESS; } function getContractionPairAddress() internal pure returns (address) { return CONTRACTION_PAIR_ADDRESS; } function getTreasuryAddress() internal pure returns (address) { return TREASURY_ADDRESS; } function getCDSDRedemptionRatio() internal pure returns (uint256) { return CDSD_REDEMPTION_RATIO; } function getContractionBondingRewards() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: CONTRACTION_BONDING_REWARDS}); } function maxCDSDBondingRewards() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: MAX_CDSD_BONDING_REWARDS}); } function getBaseEarnableFactor() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: BASE_EARNABLE_FACTOR}); } function getMaxEarnableFactor() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value: MAX_EARNABLE_FACTOR}); } } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad 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 Getters is State { using SafeMath for uint256; using Decimal for Decimal.D256; bytes32 private constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * ERC20 Interface */ function name() public view returns (string memory) { return "Dynamic Set Dollar Stake"; } function symbol() public view returns (string memory) { return "DSDS"; } function decimals() public view returns (uint8) { return 18; } function balanceOf(address account) public view returns (uint256) { return _state.accounts[account].balance; } function totalSupply() public view returns (uint256) { return _state.balance.supply; } function allowance(address owner, address spender) external view returns (uint256) { return 0; } /** * Global */ function dollar() public view returns (IDollar) { return _state.provider.dollar; } function oracle() public view returns (IOracle) { return _state.provider.oracle; } /* DIP-17 */ function contractionOracle() public view returns (IOracle) { return _state17.CDSDOracle; } /* DIP-17 */ function pool() public view returns (address) { return Constants.getPoolAddress(); } function cpool() public view returns (address) { return Constants.getContractionPoolAddress(); } function totalBonded() public view returns (uint256) { return _state.balance.bonded; } function totalStaged() public view returns (uint256) { return _state.balance.staged; } function totalDebt() public view returns (uint256) { return _state.balance.debt; } function totalRedeemable() public view returns (uint256) { return _state.balance.redeemable; } function totalCouponUnderlying() public view returns (uint256) { return _state13.couponUnderlying; } function totalCoupons() public view returns (uint256) { return _state.balance.coupons; } function treasury() public view returns (address) { return Constants.getTreasuryAddress(); } // DIP-10 function totalCDSDBonded() public view returns (uint256) { return cdsd().balanceOf(address(this)); } function globalInterestMultiplier() public view returns (uint256) { return _state10.globalInterestMultiplier; } function expansionStartEpoch() public view returns (uint256) { return _state10.expansionStartEpoch; } function totalCDSD() public view returns (uint256) { return cdsd().totalSupply(); } function cdsd() public view returns (IDollar) { return IDollar(Constants.getContractionDollarAddress()); } // end DIP-10 function getPrice() public view returns (Decimal.D256 memory price) { return _state13.price; } /* DIP-17 */ function getCDSDPrice() public view returns (Decimal.D256 memory CDSDPrice) { return _state17.CDSDPrice; } function getEarnableFactor() internal returns (Decimal.D256 memory earnableFactor) { Decimal.D256 memory deltaToPeg = Decimal.one().sub(getPrice()); //Difference of DSD to peg Decimal.D256 memory pricePercentageCDSD = getCDSDPrice().div(getPrice()); // CDSD price percantage of DSD price Decimal.D256 memory earnableFactor = deltaToPeg.div(pricePercentageCDSD); if (earnableFactor.lessThan(Constants.getBaseEarnableFactor())) { //Earnable at least 10% earnableFactor = Constants.getBaseEarnableFactor(); } if (earnableFactor.greaterThan(Constants.getMaxEarnableFactor())) { //Earnable at most 500% earnableFactor = Constants.getMaxEarnableFactor(); } return earnableFactor; } /* End DIP-17 */ /** * Account */ function balanceOfStaged(address account) public view returns (uint256) { return _state.accounts[account].staged; } function balanceOfBonded(address account) public view returns (uint256) { uint256 totalSupplyAmount = totalSupply(); if (totalSupplyAmount == 0) { return 0; } return totalBonded().mul(balanceOf(account)).div(totalSupplyAmount); } function balanceOfCoupons(address account, uint256 epoch) public view returns (uint256) { if (outstandingCoupons(epoch) == 0) { return 0; } return _state.accounts[account].coupons[epoch]; } function balanceOfCouponUnderlying(address account, uint256 epoch) public view returns (uint256) { uint256 underlying = _state13.couponUnderlyingByAccount[account][epoch]; // DIP-13 migration if (underlying == 0 && outstandingCoupons(epoch) == 0) { return _state.accounts[account].coupons[epoch].div(2); } return underlying; } function statusOf(address account) public view returns (Account.Status) { if (_state.accounts[account].lockedUntil > epoch()) { return Account.Status.Locked; } return epoch() >= _state.accounts[account].fluidUntil ? Account.Status.Frozen : Account.Status.Fluid; } function fluidUntil(address account) public view returns (uint256) { return _state.accounts[account].fluidUntil; } function lockedUntil(address account) public view returns (uint256) { return _state.accounts[account].lockedUntil; } function allowanceCoupons(address owner, address spender) public view returns (uint256) { return _state.accounts[owner].couponAllowances[spender]; } // DIP-10 function balanceOfCDSDBonded(address account) public view returns (uint256) { uint256 entry = interestMultiplierEntryByAccount(account); if (entry == 0) { return 0; } uint256 amount = depositedCDSDByAccount(account).mul(_state10.globalInterestMultiplier).div(entry); uint256 cappedAmount = cDSDBondedCap(account); return amount > cappedAmount ? cappedAmount : amount; } function cDSDBondedCap(address account) public view returns (uint256) { return depositedCDSDByAccount(account).add(earnableCDSDByAccount(account)).sub(earnedCDSDByAccount(account)); } function depositedCDSDByAccount(address account) public view returns (uint256) { return _state10.accounts[account].depositedCDSD; } function interestMultiplierEntryByAccount(address account) public view returns (uint256) { return _state10.accounts[account].interestMultiplierEntry; } function earnableCDSDByAccount(address account) public view returns (uint256) { return _state10.accounts[account].earnableCDSD; } function earnedCDSDByAccount(address account) public view returns (uint256) { return _state10.accounts[account].earnedCDSD; } function redeemedCDSDByAccount(address account) public view returns (uint256) { return _state10.accounts[account].redeemedCDSD; } function getRedeemedThisExpansion(address account) public view returns (uint256) { uint256 currentExpansion = _state10.expansionStartEpoch; uint256 accountExpansion = _state10.accounts[account].lastRedeemedExpansionStart; if (currentExpansion != accountExpansion) { return 0; } else { return _state10.accounts[account].redeemedThisExpansion; } } function getCurrentRedeemableCDSDByAccount(address account) public view returns (uint256) { uint256 total = totalCDSDBonded(); if (total == 0) { return 0; } return totalCDSDRedeemable().mul(balanceOfCDSDBonded(account)).div(total).sub(getRedeemedThisExpansion(account)); } function totalCDSDDeposited() public view returns (uint256) { return _state10.totalCDSDDeposited; } function totalCDSDEarnable() public view returns (uint256) { return _state10.totalCDSDEarnable; } function totalCDSDEarned() public view returns (uint256) { return _state10.totalCDSDEarned; } function totalCDSDRedeemed() public view returns (uint256) { return _state10.totalCDSDRedeemed; } function totalCDSDRedeemable() public view returns (uint256) { return _state10.totalCDSDRedeemable; } function maxCDSDOutstanding() public view returns (uint256) { return totalCDSDDeposited().add(totalCDSDEarnable()).sub(totalCDSDEarned()); } // end DIP-10 /** * Epoch */ function epoch() public view returns (uint256) { return _state.epoch.current; } function epochTime() public view returns (uint256) { Constants.EpochStrategy memory current = Constants.getEpochStrategy(); return epochTimeWithStrategy(current); } function epochTimeWithStrategy(Constants.EpochStrategy memory strategy) private view returns (uint256) { return blockTimestamp().sub(strategy.start).div(strategy.period).add(strategy.offset); } // Overridable for testing function blockTimestamp() internal view returns (uint256) { return block.timestamp; } function outstandingCoupons(uint256 epoch) public view returns (uint256) { return _state.epochs[epoch].coupons.outstanding; } function couponsExpiration(uint256 epoch) public view returns (uint256) { return _state.epochs[epoch].coupons.expiration; } function expiringCoupons(uint256 epoch) public view returns (uint256) { return _state.epochs[epoch].coupons.expiring.length; } function expiringCouponsAtIndex(uint256 epoch, uint256 i) public view returns (uint256) { return _state.epochs[epoch].coupons.expiring[i]; } function totalBondedAt(uint256 epoch) public view returns (uint256) { return _state.epochs[epoch].bonded; } function bootstrappingAt(uint256 epoch) public view returns (bool) { return epoch <= Constants.getBootstrappingPeriod(); } /** * Governance */ function recordedVote(address account, address candidate) public view returns (Candidate.Vote) { return _state.candidates[candidate].votes[account]; } function startFor(address candidate) public view returns (uint256) { return _state.candidates[candidate].start; } function periodFor(address candidate) public view returns (uint256) { return _state.candidates[candidate].period; } function approveFor(address candidate) public view returns (uint256) { return _state.candidates[candidate].approve; } function rejectFor(address candidate) public view returns (uint256) { return _state.candidates[candidate].reject; } function votesFor(address candidate) public view returns (uint256) { return approveFor(candidate).add(rejectFor(candidate)); } function isNominated(address candidate) public view returns (bool) { return _state.candidates[candidate].start > 0; } function isInitialized(address candidate) public view returns (bool) { return _state.candidates[candidate].initialized; } function implementation() public view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad 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 Setters is State, Getters { using SafeMath for uint256; event Transfer(address indexed from, address indexed to, uint256 value); /** * ERC20 Interface */ function transfer(address recipient, uint256 amount) external returns (bool) { return false; } function approve(address spender, uint256 amount) external returns (bool) { return false; } function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool) { return false; } /** * Global */ function incrementTotalBonded(uint256 amount) internal { _state.balance.bonded = _state.balance.bonded.add(amount); } function decrementTotalBonded(uint256 amount, string memory reason) internal { _state.balance.bonded = _state.balance.bonded.sub(amount, reason); } function incrementTotalDebt(uint256 amount) internal { _state.balance.debt = _state.balance.debt.add(amount); } function decrementTotalDebt(uint256 amount, string memory reason) internal { _state.balance.debt = _state.balance.debt.sub(amount, reason); } function setDebtToZero() internal { _state.balance.debt = 0; } function incrementTotalRedeemable(uint256 amount) internal { _state.balance.redeemable = _state.balance.redeemable.add(amount); } function decrementTotalRedeemable(uint256 amount, string memory reason) internal { _state.balance.redeemable = _state.balance.redeemable.sub(amount, reason); } // DIP-10 function setGlobalInterestMultiplier(uint256 multiplier) internal { _state10.globalInterestMultiplier = multiplier; } function setExpansionStartEpoch(uint256 epoch) internal { _state10.expansionStartEpoch = epoch; } function incrementTotalCDSDRedeemable(uint256 amount) internal { _state10.totalCDSDRedeemable = _state10.totalCDSDRedeemable.add(amount); } function decrementTotalCDSDRedeemable(uint256 amount, string memory reason) internal { _state10.totalCDSDRedeemable = _state10.totalCDSDRedeemable.sub(amount, reason); } function incrementTotalCDSDRedeemed(uint256 amount) internal { _state10.totalCDSDRedeemed = _state10.totalCDSDRedeemed.add(amount); } function decrementTotalCDSDRedeemed(uint256 amount, string memory reason) internal { _state10.totalCDSDRedeemed = _state10.totalCDSDRedeemed.sub(amount, reason); } function clearCDSDRedeemable() internal { _state10.totalCDSDRedeemable = 0; _state10.totalCDSDRedeemed = 0; } function incrementTotalCDSDDeposited(uint256 amount) internal { _state10.totalCDSDDeposited = _state10.totalCDSDDeposited.add(amount); } function decrementTotalCDSDDeposited(uint256 amount, string memory reason) internal { _state10.totalCDSDDeposited = _state10.totalCDSDDeposited.sub(amount, reason); } function incrementTotalCDSDEarnable(uint256 amount) internal { _state10.totalCDSDEarnable = _state10.totalCDSDEarnable.add(amount); } function decrementTotalCDSDEarnable(uint256 amount, string memory reason) internal { _state10.totalCDSDEarnable = _state10.totalCDSDEarnable.sub(amount, reason); } function incrementTotalCDSDEarned(uint256 amount) internal { _state10.totalCDSDEarned = _state10.totalCDSDEarned.add(amount); } function decrementTotalCDSDEarned(uint256 amount, string memory reason) internal { _state10.totalCDSDEarned = _state10.totalCDSDEarned.sub(amount, reason); } // end DIP-10 /** * Account */ function incrementBalanceOf(address account, uint256 amount) internal { _state.accounts[account].balance = _state.accounts[account].balance.add(amount); _state.balance.supply = _state.balance.supply.add(amount); emit Transfer(address(0), account, amount); } function decrementBalanceOf( address account, uint256 amount, string memory reason ) internal { _state.accounts[account].balance = _state.accounts[account].balance.sub(amount, reason); _state.balance.supply = _state.balance.supply.sub(amount, reason); emit Transfer(account, address(0), amount); } function incrementBalanceOfStaged(address account, uint256 amount) internal { _state.accounts[account].staged = _state.accounts[account].staged.add(amount); _state.balance.staged = _state.balance.staged.add(amount); } function decrementBalanceOfStaged( address account, uint256 amount, string memory reason ) internal { _state.accounts[account].staged = _state.accounts[account].staged.sub(amount, reason); _state.balance.staged = _state.balance.staged.sub(amount, reason); } function incrementBalanceOfCoupons( address account, uint256 epoch, uint256 amount ) internal { _state.accounts[account].coupons[epoch] = _state.accounts[account].coupons[epoch].add(amount); _state.epochs[epoch].coupons.outstanding = _state.epochs[epoch].coupons.outstanding.add(amount); _state.balance.coupons = _state.balance.coupons.add(amount); } function incrementBalanceOfCouponUnderlying( address account, uint256 epoch, uint256 amount ) internal { _state13.couponUnderlyingByAccount[account][epoch] = _state13.couponUnderlyingByAccount[account][epoch].add( amount ); _state13.couponUnderlying = _state13.couponUnderlying.add(amount); } function decrementBalanceOfCoupons( address account, uint256 epoch, uint256 amount, string memory reason ) internal { _state.accounts[account].coupons[epoch] = _state.accounts[account].coupons[epoch].sub(amount, reason); _state.epochs[epoch].coupons.outstanding = _state.epochs[epoch].coupons.outstanding.sub(amount, reason); _state.balance.coupons = _state.balance.coupons.sub(amount, reason); } function decrementBalanceOfCouponUnderlying( address account, uint256 epoch, uint256 amount, string memory reason ) internal { _state13.couponUnderlyingByAccount[account][epoch] = _state13.couponUnderlyingByAccount[account][epoch].sub( amount, reason ); _state13.couponUnderlying = _state13.couponUnderlying.sub(amount, reason); } function unfreeze(address account) internal { _state.accounts[account].fluidUntil = epoch().add(Constants.getDAOExitLockupEpochs()); } function updateAllowanceCoupons( address owner, address spender, uint256 amount ) internal { _state.accounts[owner].couponAllowances[spender] = amount; } function decrementAllowanceCoupons( address owner, address spender, uint256 amount, string memory reason ) internal { _state.accounts[owner].couponAllowances[spender] = _state.accounts[owner].couponAllowances[spender].sub( amount, reason ); } // DIP-10 function incrementBalanceOfDepositedCDSD(address account, uint256 amount) internal { _state10.accounts[account].depositedCDSD = _state10.accounts[account].depositedCDSD.add(amount); } function decrementBalanceOfDepositedCDSD(address account, uint256 amount, string memory reason) internal { _state10.accounts[account].depositedCDSD = _state10.accounts[account].depositedCDSD.sub(amount, reason); } function incrementBalanceOfEarnableCDSD(address account, uint256 amount) internal { _state10.accounts[account].earnableCDSD = _state10.accounts[account].earnableCDSD.add(amount); } function decrementBalanceOfEarnableCDSD(address account, uint256 amount, string memory reason) internal { _state10.accounts[account].earnableCDSD = _state10.accounts[account].earnableCDSD.sub(amount, reason); } function incrementBalanceOfEarnedCDSD(address account, uint256 amount) internal { _state10.accounts[account].earnedCDSD = _state10.accounts[account].earnedCDSD.add(amount); } function decrementBalanceOfEarnedCDSD(address account, uint256 amount, string memory reason) internal { _state10.accounts[account].earnedCDSD = _state10.accounts[account].earnedCDSD.sub(amount, reason); } function incrementBalanceOfRedeemedCDSD(address account, uint256 amount) internal { _state10.accounts[account].redeemedCDSD = _state10.accounts[account].redeemedCDSD.add(amount); } function decrementBalanceOfRedeemedCDSD(address account, uint256 amount, string memory reason) internal { _state10.accounts[account].redeemedCDSD = _state10.accounts[account].redeemedCDSD.sub(amount, reason); } function addRedeemedThisExpansion(address account, uint256 amount) internal returns (uint256) { uint256 currentExpansion = _state10.expansionStartEpoch; uint256 accountExpansion = _state10.accounts[account].lastRedeemedExpansionStart; if (currentExpansion != accountExpansion) { _state10.accounts[account].redeemedThisExpansion = amount; _state10.accounts[account].lastRedeemedExpansionStart = currentExpansion; }else{ _state10.accounts[account].redeemedThisExpansion = _state10.accounts[account].redeemedThisExpansion.add(amount); } } function setCurrentInterestMultiplier(address account) internal returns (uint256) { _state10.accounts[account].interestMultiplierEntry = _state10.globalInterestMultiplier; } function setDepositedCDSDAmount(address account, uint256 amount) internal returns (uint256) { _state10.accounts[account].depositedCDSD = amount; } // end DIP-10 /** * Epoch */ function incrementEpoch() internal { _state.epoch.current = _state.epoch.current.add(1); } function snapshotTotalBonded() internal { _state.epochs[epoch()].bonded = totalSupply(); } function initializeCouponsExpiration(uint256 epoch, uint256 expiration) internal { _state.epochs[epoch].coupons.expiration = expiration; _state.epochs[expiration].coupons.expiring.push(epoch); } /** * Governance */ function createCandidate(address candidate, uint256 period) internal { _state.candidates[candidate].start = epoch(); _state.candidates[candidate].period = period; } function recordVote( address account, address candidate, Candidate.Vote vote ) internal { _state.candidates[candidate].votes[account] = vote; } function incrementApproveFor(address candidate, uint256 amount) internal { _state.candidates[candidate].approve = _state.candidates[candidate].approve.add(amount); } function decrementApproveFor( address candidate, uint256 amount, string memory reason ) internal { _state.candidates[candidate].approve = _state.candidates[candidate].approve.sub(amount, reason); } function incrementRejectFor(address candidate, uint256 amount) internal { _state.candidates[candidate].reject = _state.candidates[candidate].reject.add(amount); } function decrementRejectFor( address candidate, uint256 amount, string memory reason ) internal { _state.candidates[candidate].reject = _state.candidates[candidate].reject.sub(amount, reason); } function placeLock(address account, address candidate) internal { uint256 currentLock = _state.accounts[account].lockedUntil; uint256 newLock = startFor(candidate).add(periodFor(candidate)); if (newLock > currentLock) { _state.accounts[account].lockedUntil = newLock; } } function initialized(address candidate) internal { _state.candidates[candidate].initialized = true; } } /* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @title Require * @author dYdX * * Stringifies parameters to pretty-print revert messages. Costs more gas than regular require() */ library Require { // ============ Constants ============ uint256 constant ASCII_ZERO = 48; // '0' uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10 uint256 constant ASCII_LOWER_EX = 120; // 'x' bytes2 constant COLON = 0x3a20; // ': ' bytes2 constant COMMA = 0x2c20; // ', ' bytes2 constant LPAREN = 0x203c; // ' <' byte constant RPAREN = 0x3e; // '>' uint256 constant FOUR_BIT_MASK = 0xf; // ============ Library Functions ============ function that( bool must, bytes32 file, bytes32 reason ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason) ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } // ============ Private Functions ============ function stringifyTruncated( bytes32 input ) private pure returns (bytes memory) { // put the input bytes into the result bytes memory result = abi.encodePacked(input); // determine the length of the input by finding the location of the last non-zero byte for (uint256 i = 32; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // find the last non-zero byte in order to determine the length if (result[i] != 0) { uint256 length = i + 1; /* solium-disable-next-line security/no-inline-assembly */ assembly { mstore(result, length) // r.length = length; } return result; } } // all bytes are zero return new bytes(0); } function stringify( uint256 input ) private pure returns (bytes memory) { if (input == 0) { return "0"; } // get the final string length uint256 j = input; uint256 length; while (j != 0) { length++; j /= 10; } // allocate the string bytes memory bstr = new bytes(length); // populate the string starting with the least-significant character j = input; for (uint256 i = length; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // take last decimal digit bstr[i] = byte(uint8(ASCII_ZERO + (j % 10))); // remove the last decimal digit j /= 10; } return bstr; } function stringify( address input ) private pure returns (bytes memory) { uint256 z = uint256(input); // addresses are "0x" followed by 20 bytes of data which take up 2 characters each bytes memory result = new bytes(42); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 20; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[41 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[40 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function stringify( bytes32 input ) private pure returns (bytes memory) { uint256 z = uint256(input); // bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each bytes memory result = new bytes(66); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 32; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[65 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[64 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function char( uint256 input ) private pure returns (byte) { // return ASCII digit (0-9) if (input < 10) { return byte(uint8(input + ASCII_ZERO)); } // return ASCII letter (a-f) return byte(uint8(input + ASCII_RELATIVE_ZERO)); } } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad 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 Comptroller is Setters { using SafeMath for uint256; bytes32 private constant FILE = "Comptroller"; function setPrices(Decimal.D256 memory price, Decimal.D256 memory CDSDPrice) internal { _state13.price = price; _state17.CDSDPrice = CDSDPrice; // track expansion cycles if (price.greaterThan(Decimal.one())) { if (_state10.expansionStartEpoch == 0) { _state10.expansionStartEpoch = epoch(); } } else { _state10.expansionStartEpoch = 0; } } function mintToAccount(address account, uint256 amount) internal { dollar().mint(account, amount); balanceCheck(); } function burnFromAccount(address account, uint256 amount) internal { dollar().transferFrom(account, address(this), amount); dollar().burn(amount); balanceCheck(); } function burnRedeemable(uint256 amount) internal { dollar().burn(amount); decrementTotalRedeemable(amount, "Comptroller: not enough redeemable balance"); balanceCheck(); } function contractionIncentives(Decimal.D256 memory price) internal returns (uint256) { // clear outstanding redeemables uint256 redeemable = totalCDSDRedeemable(); if (redeemable != 0) { clearCDSDRedeemable(); } // accrue interest on CDSD uint256 currentMultiplier = globalInterestMultiplier(); Decimal.D256 memory interest = Constants.maxCDSDBondingRewards(); uint256 newMultiplier = Decimal.D256({ value: currentMultiplier }).mul(Decimal.one().add(interest)).value; setGlobalInterestMultiplier(newMultiplier); // payout CPool rewards Decimal.D256 memory cPoolReward = Decimal.D256({ value: cdsd().totalSupply() }).mul(Constants.getContractionPoolTargetSupply()).mul( Constants.getContractionPoolTargetReward() ); cdsd().mint(Constants.getContractionPoolAddress(), cPoolReward.value); // DSD bonded in the DAO receives a fixed APY uint256 daoBondingRewards; if (totalBonded() != 0) { daoBondingRewards = Decimal.D256(totalBonded()).mul(Constants.getContractionBondingRewards()).value; mintToDAO(daoBondingRewards); } balanceCheck(); return daoBondingRewards; } function increaseSupply(uint256 newSupply) internal returns (uint256, uint256) { // 0-a. Pay out to Pool uint256 poolReward = newSupply.mul(Constants.getOraclePoolRatio()).div(100); mintToPool(poolReward); // 0-b. Pay out to Treasury uint256 treasuryReward = newSupply.mul(Constants.getTreasuryRatio()).div(100); mintToTreasury(treasuryReward); // cDSD redemption logic uint256 newCDSDRedeemable = 0; uint256 outstanding = maxCDSDOutstanding(); uint256 redeemable = totalCDSDRedeemable().sub(totalCDSDRedeemed()); if (redeemable < outstanding) { uint256 newRedeemable = newSupply.mul(Constants.getCDSDRedemptionRatio()).div(100); uint256 newRedeemableCap = outstanding.sub(redeemable); newCDSDRedeemable = newRedeemableCap > newRedeemable ? newRedeemableCap : newRedeemable; incrementTotalCDSDRedeemable(newCDSDRedeemable); } // remaining is for DAO uint256 rewards = poolReward.add(treasuryReward).add(newCDSDRedeemable); uint256 amount = newSupply > rewards ? newSupply.sub(rewards) : 0; // 2. Payout to DAO if (totalBonded() == 0) { amount = 0; } if (amount > 0) { mintToDAO(amount); } balanceCheck(); return (newCDSDRedeemable, amount.add(rewards)); } function balanceCheck() internal view { Require.that( dollar().balanceOf(address(this)) >= totalBonded().add(totalStaged()).add(totalRedeemable()), FILE, "Inconsistent balances" ); } function mintToDAO(uint256 amount) private { if (amount > 0) { dollar().mint(address(this), amount); incrementTotalBonded(amount); } } function mintToTreasury(uint256 amount) private { if (amount > 0) { dollar().mint(Constants.getTreasuryAddress(), amount); } } function mintToPool(uint256 amount) private { if (amount > 0) { dollar().mint(pool(), amount); } } } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad 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 CDSDMarket is Comptroller { using SafeMath for uint256; event DSDBurned(address indexed account, uint256 amount); event CDSDMinted(address indexed account, uint256 amount); event CDSDRedeemed(address indexed account, uint256 amount); event BondCDSD(address indexed account, uint256 start, uint256 amount); event UnbondCDSD(address indexed account, uint256 start, uint256 amount); function burnDSDForCDSD(uint256 amount) public { require(_state13.price.lessThan(Decimal.one()), "Market: not in contraction"); // deposit and burn DSD dollar().transferFrom(msg.sender, address(this), amount); dollar().burn(amount); balanceCheck(); // mint equivalent CDSD cdsd().mint(msg.sender, amount); // increment earnable uint256 earnable = Decimal.D256({value: amount}).mul(Getters.getEarnableFactor()).value; //DIP-17 incrementBalanceOfEarnableCDSD(msg.sender, earnable); incrementTotalCDSDEarnable(earnable); emit DSDBurned(msg.sender, amount); emit CDSDMinted(msg.sender, amount); } function migrateCouponsToCDSD(uint256 couponEpoch) public returns (uint256) { uint256 couponAmount = balanceOfCoupons(msg.sender, couponEpoch); uint256 couponUnderlyingAmount = balanceOfCouponUnderlying(msg.sender, couponEpoch); // coupons not yet migrated to DIP-13 if (couponAmount == 0 && couponUnderlyingAmount == 0 && outstandingCoupons(couponEpoch) == 0){ couponUnderlyingAmount = _state.accounts[msg.sender].coupons[couponEpoch].div(2); } // set coupon & underlying balances to 0 _state13.couponUnderlyingByAccount[msg.sender][couponEpoch] = 0; _state.accounts[msg.sender].coupons[couponEpoch] = 0; // mint CDSD uint256 totalAmount = couponAmount.add(couponUnderlyingAmount); cdsd().mint(msg.sender, totalAmount); emit CDSDMinted(msg.sender, totalAmount); return totalAmount; } function burnDSDForCDSDAndBond(uint256 amount) external { burnDSDForCDSD(amount); bondCDSD(amount); } function migrateCouponsToCDSDAndBond(uint256 couponEpoch) external { uint256 amountToBond = migrateCouponsToCDSD(couponEpoch); bondCDSD(amountToBond); } function bondCDSD(uint256 amount) public { require(amount > 0, "Market: bound must be greater than 0"); // update earned amount (uint256 userBonded, uint256 userDeposited,) = updateUserEarned(msg.sender); // deposit CDSD amount cdsd().transferFrom(msg.sender, address(this), amount); uint256 totalAmount = userBonded.add(amount); setDepositedCDSDAmount(msg.sender, totalAmount); decrementTotalCDSDDeposited(userDeposited, "Market: insufficient total deposited"); incrementTotalCDSDDeposited(totalAmount); emit BondCDSD(msg.sender, epoch().add(1), amount); } function unbondCDSD(uint256 amount) external { // we cannot allow for CDSD unbonds during expansions, to enforce the pro-rata redemptions require(_state13.price.lessThan(Decimal.one()), "Market: not in contraction"); _unbondCDSD(amount); // withdraw CDSD cdsd().transfer(msg.sender, amount); emit UnbondCDSD(msg.sender, epoch().add(1), amount); } function _unbondCDSD(uint256 amount) internal { // update earned amount (uint256 userBonded, uint256 userDeposited,) = updateUserEarned(msg.sender); require(amount > 0 && userBonded > 0, "Market: amounts > 0!"); require(amount <= userBonded, "Market: insufficient amount to unbound"); // update deposited amount uint256 userTotalAmount = userBonded.sub(amount); setDepositedCDSDAmount(msg.sender, userTotalAmount); decrementTotalCDSDDeposited(userDeposited, "Market: insufficient deposited"); incrementTotalCDSDDeposited(userTotalAmount); } function redeemBondedCDSDForDSD(uint256 amount) external { require(_state13.price.greaterThan(Decimal.one()), "Market: not in expansion"); require(amount > 0, "Market: amounts > 0!"); // check if user is allowed to redeem this amount require(amount <= getCurrentRedeemableCDSDByAccount(msg.sender), "Market: not enough redeemable"); // unbond redeemed amount _unbondCDSD(amount); // burn CDSD cdsd().burn(amount); // mint DSD mintToAccount(msg.sender, amount); addRedeemedThisExpansion(msg.sender, amount); incrementTotalCDSDRedeemed(amount); emit CDSDRedeemed(msg.sender, amount); } function updateUserEarned(address account) internal returns (uint256 userBonded, uint256 userDeposited, uint256 userEarned) { userBonded = balanceOfCDSDBonded(account); userDeposited = depositedCDSDByAccount(account); userEarned = userBonded.sub(userDeposited); if (userEarned > 0) { incrementBalanceOfEarnedCDSD(account, userEarned); // mint acrued interest interest to DAO cdsd().mint(address(this), userEarned); incrementTotalCDSDEarned(userEarned); } // update multiplier entry setCurrentInterestMultiplier(account); } } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad 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 Regulator is Comptroller { using SafeMath for uint256; using Decimal for Decimal.D256; event SupplyIncrease(uint256 indexed epoch, uint256 price, uint256 newRedeemable, uint256 newBonded); event ContractionIncentives(uint256 indexed epoch, uint256 price, uint256 delta); event SupplyNeutral(uint256 indexed epoch); function step() internal { (Decimal.D256 memory price, Decimal.D256 memory CDSDPrice) = oracleCapture(); setPrices(price, CDSDPrice); if (price.greaterThan(Decimal.one())) { expansion(price); return; } if (price.lessThan(Decimal.one())) { contraction(price); return; } emit SupplyNeutral(epoch()); } function expansion(Decimal.D256 memory price) private { Decimal.D256 memory delta = limit(price.sub(Decimal.one()).div(Constants.getSupplyChangeDivisor()), price); uint256 newSupply = delta.mul(dollar().totalSupply()).asUint256(); (uint256 newRedeemable, uint256 newBonded) = increaseSupply(newSupply); emit SupplyIncrease(epoch(), price.value, newRedeemable, newBonded); } function contraction(Decimal.D256 memory price) private { (uint256 newDSDSupply) = contractionIncentives(price); emit ContractionIncentives(epoch(), price.value, newDSDSupply); } function limit(Decimal.D256 memory delta, Decimal.D256 memory price) private view returns (Decimal.D256 memory) { Decimal.D256 memory supplyChangeLimit = Constants.getSupplyChangeLimit(); return delta.greaterThan(supplyChangeLimit) ? supplyChangeLimit : delta; } function oracleCapture() private returns (Decimal.D256 memory, Decimal.D256 memory) { (Decimal.D256 memory price, bool valid) = oracle().capture(); if (bootstrappingAt(epoch().sub(1))) { price = Constants.getBootstrappingPrice(); } if (!valid) { price = Decimal.one(); } (Decimal.D256 memory CDSDPrice, bool contractionValid) = contractionOracle().capture(); if (!contractionValid) { CDSDPrice = price; } return (price, CDSDPrice); } } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad 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 Permission is Setters { bytes32 private constant FILE = "Permission"; // Can modify account state modifier onlyFrozenOrFluid(address account) { Require.that( statusOf(account) != Account.Status.Locked, FILE, "Not frozen or fluid" ); _; } // Can participate in balance-dependant activities modifier onlyFrozenOrLocked(address account) { Require.that( statusOf(account) != Account.Status.Fluid, FILE, "Not frozen or locked" ); _; } modifier initializer() { Require.that( !isInitialized(implementation()), FILE, "Already initialized" ); initialized(implementation()); _; } } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad 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 Bonding is Setters, Permission { using SafeMath for uint256; bytes32 private constant FILE = "Bonding"; event Deposit(address indexed account, uint256 value); event Withdraw(address indexed account, uint256 value); event Bond(address indexed account, uint256 start, uint256 value, uint256 valueUnderlying); event Unbond(address indexed account, uint256 start, uint256 value, uint256 valueUnderlying); function step() internal { Require.that( epochTime() > epoch(), FILE, "Still current epoch" ); snapshotTotalBonded(); incrementEpoch(); } function deposit(uint256 value) external { dollar().transferFrom(msg.sender, address(this), value); incrementBalanceOfStaged(msg.sender, value); emit Deposit(msg.sender, value); } function withdraw(uint256 value) external onlyFrozenOrLocked(msg.sender) { dollar().transfer(msg.sender, value); decrementBalanceOfStaged(msg.sender, value, "Bonding: insufficient staged balance"); emit Withdraw(msg.sender, value); } function bond(uint256 value) external onlyFrozenOrFluid(msg.sender) { unfreeze(msg.sender); uint256 balance = totalBonded() == 0 ? value.mul(Constants.getInitialStakeMultiple()) : value.mul(totalSupply()).div(totalBonded()); incrementBalanceOf(msg.sender, balance); incrementTotalBonded(value); decrementBalanceOfStaged(msg.sender, value, "Bonding: insufficient staged balance"); emit Bond(msg.sender, epoch().add(1), balance, value); } function unbond(uint256 value) external onlyFrozenOrFluid(msg.sender) { unfreeze(msg.sender); uint256 staged = value.mul(balanceOfBonded(msg.sender)).div(balanceOf(msg.sender)); incrementBalanceOfStaged(msg.sender, staged); decrementTotalBonded(staged, "Bonding: insufficient total bonded"); decrementBalanceOf(msg.sender, value, "Bonding: insufficient balance"); emit Unbond(msg.sender, epoch().add(1), value, staged); } function unbondUnderlying(uint256 value) external onlyFrozenOrFluid(msg.sender) { unfreeze(msg.sender); uint256 balance = value.mul(totalSupply()).div(totalBonded()); incrementBalanceOfStaged(msg.sender, value); decrementTotalBonded(value, "Bonding: insufficient total bonded"); decrementBalanceOf(msg.sender, balance, "Bonding: insufficient balance"); emit Unbond(msg.sender, epoch().add(1), balance, value); } } /** * Utility library of inline functions on addresses * * Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol * This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts * when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the * build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version. */ library OpenZeppelinUpgradesAddress { /** * 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. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } /* Copyright 2018-2019 zOS Global Limited Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad 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. */ /** * Based off of, and designed to interface with, openzeppelin/upgrades package */ contract Upgradeable is State { /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 private constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); function initialize() public; /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) internal { setImplementation(newImplementation); (bool success, bytes memory reason) = newImplementation.delegatecall(abi.encodeWithSignature("initialize()")); require(success, string(reason)); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function setImplementation(address newImplementation) private { require(OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad 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 Govern is Setters, Permission, Upgradeable { using SafeMath for uint256; using Decimal for Decimal.D256; bytes32 private constant FILE = "Govern"; event Proposal(address indexed candidate, address indexed account, uint256 indexed start, uint256 period); event Vote(address indexed account, address indexed candidate, Candidate.Vote vote, uint256 bonded); event Commit(address indexed account, address indexed candidate); function vote(address candidate, Candidate.Vote vote) external onlyFrozenOrLocked(msg.sender) { Require.that( balanceOf(msg.sender) > 0, FILE, "Must have stake" ); if (!isNominated(candidate)) { Require.that( canPropose(msg.sender), FILE, "Not enough stake to propose" ); createCandidate(candidate, Constants.getGovernancePeriod()); emit Proposal(candidate, msg.sender, epoch(), Constants.getGovernancePeriod()); } Require.that( epoch() < startFor(candidate).add(periodFor(candidate)), FILE, "Ended" ); uint256 bonded = balanceOf(msg.sender); Candidate.Vote recordedVote = recordedVote(msg.sender, candidate); if (vote == recordedVote) { return; } if (recordedVote == Candidate.Vote.REJECT) { decrementRejectFor(candidate, bonded, "Govern: Insufficient reject"); } if (recordedVote == Candidate.Vote.APPROVE) { decrementApproveFor(candidate, bonded, "Govern: Insufficient approve"); } if (vote == Candidate.Vote.REJECT) { incrementRejectFor(candidate, bonded); } if (vote == Candidate.Vote.APPROVE) { incrementApproveFor(candidate, bonded); } recordVote(msg.sender, candidate, vote); placeLock(msg.sender, candidate); emit Vote(msg.sender, candidate, vote, bonded); } function commit(address candidate) external { Require.that( isNominated(candidate), FILE, "Not nominated" ); uint256 endsAfter = startFor(candidate).add(periodFor(candidate)).sub(1); Require.that( epoch() > endsAfter, FILE, "Not ended" ); Require.that( Decimal.ratio(votesFor(candidate), totalBondedAt(endsAfter)).greaterThan(Constants.getGovernanceQuorum()), FILE, "Must have quorum" ); Require.that( approveFor(candidate) > rejectFor(candidate), FILE, "Not approved" ); upgradeTo(candidate); emit Commit(msg.sender, candidate); } function emergencyCommit(address candidate) external { Require.that( isNominated(candidate), FILE, "Not nominated" ); Require.that( epochTime() > epoch().add(Constants.getGovernanceEmergencyDelay()), FILE, "Epoch synced" ); Require.that( Decimal.ratio(approveFor(candidate), totalSupply()).greaterThan(Constants.getGovernanceSuperMajority()), FILE, "Must have super majority" ); Require.that( approveFor(candidate) > rejectFor(candidate), FILE, "Not approved" ); upgradeTo(candidate); emit Commit(msg.sender, candidate); } function canPropose(address account) private view returns (bool) { if (totalBonded() == 0) { return false; } Decimal.D256 memory stake = Decimal.ratio(balanceOf(account), totalSupply()); return stake.greaterThan(Constants.getGovernanceProposalThreshold()); } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _burn(_msgSender(), amount); } /** * @dev See {ERC20-_burnFrom}. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } } /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } /* Copyright 2019 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. */ library LibEIP712 { // Hash of the EIP712 Domain Separator Schema // keccak256(abi.encodePacked( // "EIP712Domain(", // "string name,", // "string version,", // "uint256 chainId,", // "address verifyingContract", // ")" // )) bytes32 constant internal _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; /// @dev Calculates a EIP712 domain separator. /// @param name The EIP712 domain name. /// @param version The EIP712 domain version. /// @param verifyingContract The EIP712 verifying contract. /// @return EIP712 domain separator. function hashEIP712Domain( string memory name, string memory version, uint256 chainId, address verifyingContract ) internal pure returns (bytes32 result) { bytes32 schemaHash = _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH; // Assembly for more efficient computing: // keccak256(abi.encodePacked( // _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH, // keccak256(bytes(name)), // keccak256(bytes(version)), // chainId, // uint256(verifyingContract) // )) assembly { // Calculate hashes of dynamic data let nameHash := keccak256(add(name, 32), mload(name)) let versionHash := keccak256(add(version, 32), mload(version)) // Load free memory pointer let memPtr := mload(64) // Store params in memory mstore(memPtr, schemaHash) mstore(add(memPtr, 32), nameHash) mstore(add(memPtr, 64), versionHash) mstore(add(memPtr, 96), chainId) mstore(add(memPtr, 128), verifyingContract) // Compute hash result := keccak256(memPtr, 160) } return result; } /// @dev Calculates EIP712 encoding for a hash struct with a given domain hash. /// @param eip712DomainHash Hash of the domain domain separator data, computed /// with getDomainHash(). /// @param hashStruct The EIP712 hash struct. /// @return EIP712 hash applied to the given EIP712 Domain. function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct) internal pure returns (bytes32 result) { // Assembly for more efficient computing: // keccak256(abi.encodePacked( // EIP191_HEADER, // EIP712_DOMAIN_HASH, // hashStruct // )); assembly { // Load free memory pointer let memPtr := mload(64) mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash mstore(add(memPtr, 34), hashStruct) // Hash of struct // Compute hash result := keccak256(memPtr, 66) } return result; } } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad 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 Permittable is ERC20Detailed, ERC20 { bytes32 constant FILE = "Permittable"; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant EIP712_PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; string private constant EIP712_VERSION = "1"; bytes32 public EIP712_DOMAIN_SEPARATOR; mapping(address => uint256) nonces; constructor() public { EIP712_DOMAIN_SEPARATOR = LibEIP712.hashEIP712Domain(name(), EIP712_VERSION, Constants.getChainId(), address(this)); } function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { bytes32 digest = LibEIP712.hashEIP712Message( EIP712_DOMAIN_SEPARATOR, keccak256(abi.encode( EIP712_PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline )) ); address recovered = ecrecover(digest, v, r, s); Require.that( recovered == owner, FILE, "Invalid signature" ); Require.that( recovered != address(0), FILE, "Zero address" ); Require.that( now <= deadline, FILE, "Expired" ); _approve(owner, spender, value); } } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad 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 ContractionDollar is IDollar, ERC20Detailed, Permittable, ERC20Burnable { constructor() public ERC20Detailed("Contraction Dynamic Set Dollar", "CDSD", 18) Permittable() {} function mint(address account, uint256 amount) public returns (bool) { require(_msgSender() == Constants.getDaoAddress(), "CDSD: only DAO is allowed to mint"); _mint(account, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public returns (bool) { _transfer(sender, recipient, amount); if ( _msgSender() != Constants.getDaoAddress() && // always allow DAO allowance(sender, _msgSender()) != uint256(-1) ) { _approve( sender, _msgSender(), allowance(sender, _msgSender()).sub(amount, "CDSD: transfer amount exceeds allowance") ); } return true; } } 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 ); } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad 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 Implementation is State, Bonding, CDSDMarket, Regulator, Govern { using SafeMath for uint256; event Advance(uint256 indexed epoch, uint256 block, uint256 timestamp); event Incentivization(address indexed account, uint256 amount); function initialize() public initializer { // committer reward: mintToAccount(msg.sender, 1000e18); // 1000 DSD to committer // Intitialize DIP-17 _state17.CDSDPrice = _state13.price.div(Decimal.D256({ value: 2e18 })); // safe to assume price is roughly half of DSD before oracle kicks in? _state17.CDSDOracle = IOracle(0x40139E3bBdf8cAcc69F1aC1eEf07DBa9b9165CE8); // // set up oracle _state17.CDSDOracle.setup(); _state17.CDSDOracle.capture(); // contributor rewards: mintToAccount(0x8A7D5fe563BbBcbB776bDD0eA8c31b93200A0D01, 20000e18); // contribution to freerangealpha + depolyment cost mintToAccount(0x437cb43D08F64AF2aA64AD2525FE1074E282EC19, 5220e18); // contribution to gus } function advance() external incentivized { Bonding.step(); Regulator.step(); emit Advance(epoch(), block.number, block.timestamp); } modifier incentivized { // run incentivisation after advancing, so we use the updated price uint256 startGas = gasleft(); _; // fetch gasPrice & ETH price from Chainlink (, int256 ethPrice, , , ) = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419).latestRoundData(); (, int256 fastGasPrice, , , ) = AggregatorV3Interface(0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C).latestRoundData(); // Calculate DSD cost Decimal.D256 memory ethSpent = Decimal.D256({ value: (startGas - gasleft() + 41000).mul(uint256(fastGasPrice)) // approximate used gas for tx }); Decimal.D256 memory usdCost = ethSpent.mul( Decimal.D256({ value: uint256(ethPrice).mul(1e10) // chainlink ETH price has 8 decimals }) ); Decimal.D256 memory dsdCost = usdCost.div(getPrice()); // Add incentive Decimal.D256 memory incentive = dsdCost.mul(Constants.getAdvanceIncentivePremium()); // Mint advance reward to sender mintToAccount(msg.sender, incentive.value); emit Incentivization(msg.sender, incentive.value); } }
500% - Maximum Amount of CDSD earnable for DSD burned
uint256 private constant MAX_EARNABLE_FACTOR = 5e18;
35,286
[ 1, 12483, 9, 300, 18848, 16811, 434, 385, 3948, 40, 425, 1303, 429, 364, 8678, 40, 18305, 329, 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, 2254, 5034, 3238, 5381, 4552, 67, 41, 4391, 2782, 67, 26835, 273, 1381, 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 ]
// File: contracts/module/safeMath.sol // SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.6.12; /** * @title BiFi's safe-math Contract * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract safeMathModule { uint256 constant one = 1 ether; function expDiv(uint256 a, uint256 b) internal pure returns (uint256) { return safeDiv( safeMul(a, one), b); } function expMul(uint256 a, uint256 b) internal pure returns (uint256) { return safeDiv( safeMul(a, b), one); } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addtion overflow"); return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { require(a >= b, "SafeMath: subtraction overflow"); return a - b; } function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { if(a == 0) { return 0;} uint256 c = a * b; require( (c/a) == b, "SafeMath: multiplication overflow"); return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return (a/b); } } // File: contracts/ERC20.sol pragma solidity 0.6.12; /** * @title BiFi's ERC20 Mockup Contract * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract ERC20 { string symbol; string name; uint8 decimals = 18; uint256 public totalSupply = 1000 * 1e9 * 1e18; // token amount: 1000 Bilions // Owner of this contract address public owner; // Balances for each account mapping(address => uint256) balances; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) allowed; // Functions with this modifier can only be executed by the owner modifier onlyOwner() { require(msg.sender == owner, "only owner"); _; } event Transfer(address, address, uint256); event Approval(address, address, uint256); // Constructor constructor (string memory _name, string memory _symbol) public { owner = msg.sender; name = _name; symbol = _symbol; balances[msg.sender] = totalSupply; } // What is the balance of a particular account? function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } // Transfer the balance from owner's account to another account function transfer(address _to, uint256 _amount) public returns (bool success) { require(balances[msg.sender] >= _amount, "insuficient sender's balance"); require(_amount > 0, "requested amount must be positive"); require(balances[_to] + _amount > balances[_to], "receiver's balance overflows"); balances[msg.sender] -= _amount; balances[_to] += _amount; emit Transfer(msg.sender, _to, _amount); return true; } // Send _value amount of tokens from address _from to address _to // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom(address _from, address _to,uint256 _amount) public returns (bool success) { require(balances[_from] >= _amount, "insuficient sender's balance"); require(allowed[_from][msg.sender] >= _amount, "not allowed transfer"); require(_amount > 0, "requested amount must be positive"); require(balances[_to] + _amount > balances[_to], "receiver's balance overflows"); balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; emit Transfer(_from, _to, _amount); return true; } // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _amount) public returns (bool success) { allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract BFCtoken is ERC20 { constructor() public ERC20 ("Bifrost", "BFC") {} } contract LPtoken is ERC20 { constructor() public ERC20 ("BFC-ETH", "LP") {} } contract BiFitoken is ERC20 { constructor() public ERC20 ("BiFi", "BiFi") {} } // File: contracts/module/storageModule.sol pragma solidity 0.6.12; /** * @title BiFi's Reward Distribution Storage Contract * @notice Define the basic Contract State * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract storageModule { address public owner; address public pendingOwner; bool public claimLock; bool public withdrawLock; uint256 public rewardPerBlock; uint256 public decrementUnitPerBlock; uint256 public rewardLane; uint256 public lastBlockNum; uint256 public totalDeposited; ERC20 public lpErc; ERC20 public rewardErc; mapping(address => Account) public accounts; uint256 public passedPoint; RewardVelocityPoint[] public registeredPoints; struct Account { uint256 deposited; uint256 pointOnLane; uint256 rewardAmount; } struct RewardVelocityPoint { uint256 blockNumber; uint256 rewardPerBlock; uint256 decrementUnitPerBlock; } struct UpdateRewardLaneModel { uint256 len; uint256 tmpBlockDelta; uint256 memPassedPoint; uint256 tmpPassedPoint; uint256 memThisBlockNum; uint256 memLastBlockNum; uint256 tmpLastBlockNum; uint256 memTotalDeposit; uint256 memRewardLane; uint256 tmpRewardLane; uint256 memRewardPerBlock; uint256 tmpRewardPerBlock; uint256 memDecrementUnitPerBlock; uint256 tmpDecrementUnitPerBlock; } } // File: contracts/module/eventModule.sol pragma solidity 0.6.12; /** * @title BiFi's Reward Distribution Event Contract * @notice Define the service Events * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract eventModule { /// @dev Events for user actions event Deposit(address userAddr, uint256 amount, uint256 userDeposit, uint256 totalDeposit); event Withdraw(address userAddr, uint256 amount, uint256 userDeposit, uint256 totalDeposit); event Claim(address userAddr, uint256 amount); event UpdateRewardParams(uint256 atBlockNumber, uint256 rewardPerBlock, uint256 decrementUnitPerBlock); /// @dev Events for admin actions below /// @dev Contracts Access Control event ClaimLock(bool lock); event WithdrawLock(bool lock); event OwnershipTransfer(address from, address to); /// @dev Distribution Model Parameter editer event SetRewardParams(uint256 rewardPerBlock, uint256 decrementUnitPerBlock); event RegisterRewardParams(uint256 atBlockNumber, uint256 rewardPerBlock, uint256 decrementUnitPerBlock); event DeleteRegisterRewardParams(uint256 index, uint256 atBlockNumber, uint256 rewardPerBlock, uint256 decrementUnitPerBlock, uint256 arrayLen); } // File: contracts/module/internalModule.sol pragma solidity 0.6.12; /** * @title BiFi's Reward Distribution Internal Contract * @notice Implement the basic functions for staking and reward distribution * @dev All functions are internal. * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract internalModule is storageModule, eventModule, safeMathModule { /** * @notice Deposit the Contribution Tokens * @param userAddr The user address of the Contribution Tokens * @param amount The amount of the Contribution Tokens */ function _deposit(address userAddr, uint256 amount) internal { Account memory user = accounts[userAddr]; uint256 totalDeposit = totalDeposited; user.deposited = safeAdd(user.deposited, amount); accounts[userAddr].deposited = user.deposited; totalDeposit = safeAdd(totalDeposited, amount); totalDeposited = totalDeposit; if(amount > 0) { /// @dev transfer the Contribution Toknes to this contract. emit Deposit(userAddr, amount, user.deposited, totalDeposit); require( lpErc.transferFrom(msg.sender, address(this), amount), "token error" ); } } /** * @notice Withdraw the Contribution Tokens * @param userAddr The user address of the Contribution Tokens * @param amount The amount of the Contribution Tokens */ function _withdraw(address userAddr, uint256 amount) internal { Account memory user = accounts[userAddr]; uint256 totalDeposit = totalDeposited; require(user.deposited >= amount, "not enough user Deposit"); user.deposited = safeSub(user.deposited, amount); accounts[userAddr].deposited = user.deposited; totalDeposit = safeSub(totalDeposited, amount); totalDeposited = totalDeposit; if(amount > 0) { /// @dev transfer the Contribution Tokens from this contact. emit Withdraw(userAddr, amount, user.deposited, totalDeposit); require( lpErc.transfer(userAddr, amount), "token error" ); } } /** * @notice Calculate current reward * @dev This function is called whenever the balance of the Contribution Tokens of the user. * @param userAddr The user address of the Contribution and Reward Tokens */ function _redeemAll(address userAddr) internal { Account memory user = accounts[userAddr]; uint256 newRewardLane = _updateRewardLane(); uint256 distance = safeSub(newRewardLane, user.pointOnLane); uint256 rewardAmount = expMul(user.deposited, distance); if(user.pointOnLane != newRewardLane) accounts[userAddr].pointOnLane = newRewardLane; if(rewardAmount != 0) accounts[userAddr].rewardAmount = safeAdd(user.rewardAmount, rewardAmount); } /** * @notice Claim the Reward Tokens * @dev Transfer all reward the user has earned at once. * @param userAddr The user address of the Reward Tokens */ function _rewardClaim(address userAddr) internal { Account memory user = accounts[userAddr]; if(user.rewardAmount != 0) { uint256 amount = user.rewardAmount; accounts[userAddr].rewardAmount = 0; /// @dev transfer the Reward Tokens from this contract. emit Claim(userAddr, amount); require(rewardErc.transfer(userAddr, amount), "token error" ); } } /** * @notice Update the reward lane value upto ths currnet moment (block) * @dev This function should care the "reward velocity points," at which the parameters of reward distribution are changed. * @return The current (calculated) reward lane value */ function _updateRewardLane() internal returns (uint256) { /// @dev Set up memory variables used for calculation temporarily. UpdateRewardLaneModel memory vars; vars.len = registeredPoints.length; vars.memTotalDeposit = totalDeposited; vars.tmpPassedPoint = vars.memPassedPoint = passedPoint; vars.memThisBlockNum = block.number; vars.tmpLastBlockNum = vars.memLastBlockNum = lastBlockNum; vars.tmpRewardLane = vars.memRewardLane = rewardLane; vars.tmpRewardPerBlock = vars.memRewardPerBlock = rewardPerBlock; vars.tmpDecrementUnitPerBlock = vars.memDecrementUnitPerBlock = decrementUnitPerBlock; for(uint256 i=vars.memPassedPoint; i<vars.len; i++) { RewardVelocityPoint memory point = registeredPoints[i]; /** * @dev Check whether this reward velocity point is valid and has not applied yet. */ if(vars.tmpLastBlockNum < point.blockNumber && point.blockNumber <= vars.memThisBlockNum) { vars.tmpPassedPoint = i+1; /// @dev Update the reward lane with the tmp variables vars.tmpBlockDelta = safeSub(point.blockNumber, vars.tmpLastBlockNum); (vars.tmpRewardLane, vars.tmpRewardPerBlock) = _calcNewRewardLane( vars.tmpRewardLane, vars.memTotalDeposit, vars.tmpRewardPerBlock, vars.tmpDecrementUnitPerBlock, vars.tmpBlockDelta); /// @dev Update the tmp variables with this reward velocity point. vars.tmpLastBlockNum = point.blockNumber; vars.tmpRewardPerBlock = point.rewardPerBlock; vars.tmpDecrementUnitPerBlock = point.decrementUnitPerBlock; /** * @dev Notify the update of the parameters (by passing the reward velocity points) */ emit UpdateRewardParams(point.blockNumber, point.rewardPerBlock, point.decrementUnitPerBlock); } else { /// @dev sorted array, exit eariler without accessing future points. break; } } /** * @dev Update the reward lane for the remained period between the latest velocity point and this moment (block) */ if( vars.tmpLastBlockNum < vars.memThisBlockNum ) { vars.tmpBlockDelta = safeSub(vars.memThisBlockNum, vars.tmpLastBlockNum); vars.tmpLastBlockNum = vars.memThisBlockNum; (vars.tmpRewardLane, vars.tmpRewardPerBlock) = _calcNewRewardLane( vars.tmpRewardLane, vars.memTotalDeposit, vars.tmpRewardPerBlock, vars.tmpDecrementUnitPerBlock, vars.tmpBlockDelta); } /** * @dev Update the reward lane parameters with the tmp variables. */ if(vars.memLastBlockNum != vars.tmpLastBlockNum) lastBlockNum = vars.tmpLastBlockNum; if(vars.memPassedPoint != vars.tmpPassedPoint) passedPoint = vars.tmpPassedPoint; if(vars.memRewardLane != vars.tmpRewardLane) rewardLane = vars.tmpRewardLane; if(vars.memRewardPerBlock != vars.tmpRewardPerBlock) rewardPerBlock = vars.tmpRewardPerBlock; if(vars.memDecrementUnitPerBlock != vars.tmpDecrementUnitPerBlock) decrementUnitPerBlock = vars.tmpDecrementUnitPerBlock; return vars.tmpRewardLane; } /** * @notice Calculate a new reward lane value with the given parameters * @param _rewardLane The previous reward lane value * @param _totalDeposit Thte total deposit amount of the Contribution Tokens * @param _rewardPerBlock The reward token amount per a block * @param _decrementUnitPerBlock The decerement amount of the reward token per a block */ function _calcNewRewardLane( uint256 _rewardLane, uint256 _totalDeposit, uint256 _rewardPerBlock, uint256 _decrementUnitPerBlock, uint256 delta) internal pure returns (uint256, uint256) { uint256 executableDelta; if(_decrementUnitPerBlock != 0) { executableDelta = safeDiv(_rewardPerBlock, _decrementUnitPerBlock); if(delta > executableDelta) delta = executableDelta; else executableDelta = 0; } uint256 distance; if(_totalDeposit != 0) { distance = expMul( _sequencePartialSumAverage(_rewardPerBlock, delta, _decrementUnitPerBlock), safeMul( expDiv(one, _totalDeposit), delta) ); _rewardLane = safeAdd(_rewardLane, distance); } if(executableDelta != 0) _rewardPerBlock = 0; else _rewardPerBlock = _getNewRewardPerBlock(_rewardPerBlock, _decrementUnitPerBlock, delta); return (_rewardLane, _rewardPerBlock); } /** * @notice Register a new reward velocity point * @dev We assume that reward velocity points are stored in order of block number. Namely, registerPoints is always a sorted array. * @param _blockNumber The block number for the point. * @param _rewardPerBlock The reward token amount per a block * @param _decrementUnitPerBlock The decerement amount of the reward token per a block */ function _registerRewardVelocity(uint256 _blockNumber, uint256 _rewardPerBlock, uint256 _decrementUnitPerBlock) internal { RewardVelocityPoint memory varPoint = RewardVelocityPoint(_blockNumber, _rewardPerBlock, _decrementUnitPerBlock); emit RegisterRewardParams(_blockNumber, _rewardPerBlock, _decrementUnitPerBlock); registeredPoints.push(varPoint); } /** * @notice Delete a existing reward velocity point * @dev We assume that reward velocity points are stored in order of block number. Namely, registerPoints is always a sorted array. * @param _index The index number of deleting point in state array. */ function _deleteRegisteredRewardVelocity(uint256 _index) internal { uint256 len = registeredPoints.length; require(len != 0 && _index < len, "error: no elements in registeredPoints"); RewardVelocityPoint memory point = registeredPoints[_index]; emit DeleteRegisterRewardParams(_index, point.blockNumber, point.rewardPerBlock, point.decrementUnitPerBlock, len-1); for(uint256 i=_index; i<len-1; i++) { registeredPoints[i] = registeredPoints[i+1]; } registeredPoints.pop(); } /** * @notice Set paramaters for the reward distribution * @param _rewardPerBlock The reward token amount per a block * @param _decrementUnitPerBlock The decerement amount of the reward token per a block */ function _setParams(uint256 _rewardPerBlock, uint256 _decrementUnitPerBlock) internal { emit SetRewardParams(_rewardPerBlock, _decrementUnitPerBlock); rewardPerBlock = _rewardPerBlock; decrementUnitPerBlock = _decrementUnitPerBlock; } /** * @return the avaerage of the RewardLance of the inactive (i.e., no-action) periods. */ function _sequencePartialSumAverage(uint256 a, uint256 n, uint256 d) internal pure returns (uint256) { /** @dev return Sn / n, where Sn = ( (n{2*a + (n-1)d}) / 2 ) == ( (2na + (n-1)d) / 2 ) / n caveat: use safeSub() to avoid the case that d is negative */ if (n > 0) return safeDiv(safeSub( safeMul(2,a), safeMul( safeSub(n,1), d) ), 2); else return 0; } function _getNewRewardPerBlock(uint256 before, uint256 dec, uint256 delta) internal pure returns (uint256) { return safeSub(before, safeMul(dec, delta)); } function _setClaimLock(bool lock) internal { emit ClaimLock(lock); claimLock = lock; } function _setWithdrawLock(bool lock) internal { emit WithdrawLock(lock); withdrawLock = lock; } function _setOwner(address newOwner) internal { require(newOwner != address(0), "owner zero address"); emit OwnershipTransfer(owner, newOwner); owner = newOwner; } function _setPendingOwner(address _pendingOwner) internal { require(_pendingOwner != address(0), "pending owner zero address"); pendingOwner = _pendingOwner; } } // File: contracts/module/viewModule.sol pragma solidity 0.6.12; /** * @title BiFi's Reward Distribution View Contract * @notice Implements the view functions for support front-end * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract viewModule is internalModule { function marketInformation(uint256 _fromBlockNumber, uint256 _toBlockNumber) external view returns ( uint256 rewardStartBlockNumber, uint256 distributedAmount, uint256 totalDeposit, uint256 poolRate ) { if(rewardPerBlock == 0) rewardStartBlockNumber = registeredPoints[0].blockNumber; else rewardStartBlockNumber = registeredPoints[0].blockNumber; distributedAmount = _redeemAllView(address(0)); totalDeposit = totalDeposited; poolRate = getPoolRate(address(0), _fromBlockNumber, _toBlockNumber); return ( rewardStartBlockNumber, distributedAmount, totalDeposit, poolRate ); } function userInformation(address userAddr, uint256 _fromBlockNumber, uint256 _toBlockNumber) external view returns ( uint256 stakedTokenAmount, uint256 rewardStartBlockNumber, uint256 claimStartBlockNumber, uint256 earnedTokenAmount, uint256 poolRate ) { Account memory user = accounts[userAddr]; stakedTokenAmount = user.deposited; if(rewardPerBlock == 0) rewardStartBlockNumber = registeredPoints[0].blockNumber; else rewardStartBlockNumber = registeredPoints[0].blockNumber; earnedTokenAmount = _redeemAllView(userAddr); poolRate = getPoolRate(userAddr, _fromBlockNumber, _toBlockNumber); return (stakedTokenAmount, rewardStartBlockNumber, claimStartBlockNumber, earnedTokenAmount, poolRate); } function modelInfo() external view returns (uint256, uint256, uint256, uint256, uint256) { return (rewardPerBlock, decrementUnitPerBlock, rewardLane, lastBlockNum, totalDeposited); } function getParams() external view returns (uint256, uint256, uint256, uint256) { return (rewardPerBlock, rewardLane, lastBlockNum, totalDeposited); } function getRegisteredPointLength() external view returns (uint256) { return registeredPoints.length; } function getRegisteredPoint(uint256 index) external view returns (uint256, uint256, uint256) { RewardVelocityPoint memory point = registeredPoints[index]; return (point.blockNumber, point.rewardPerBlock, point.decrementUnitPerBlock); } function userInfo(address userAddr) external view returns (uint256, uint256, uint256) { Account memory user = accounts[userAddr]; uint256 earnedRewardAmount = _redeemAllView(userAddr); return (user.deposited, user.pointOnLane, earnedRewardAmount); } function distributionInfo() external view returns (uint256, uint256, uint256) { uint256 totalDistributedRewardAmount_now = _distributedRewardAmountView(); return (rewardPerBlock, decrementUnitPerBlock, totalDistributedRewardAmount_now); } function _distributedRewardAmountView() internal view returns (uint256) { return _redeemAllView( address(0) ); } function _redeemAllView(address userAddr) internal view returns (uint256) { Account memory user; uint256 newRewardLane; if( userAddr != address(0) ) { user = accounts[userAddr]; newRewardLane = _updateRewardLaneView(lastBlockNum); } else { user = Account(totalDeposited, 0, 0); newRewardLane = _updateRewardLaneView(0); } uint256 distance = safeSub(newRewardLane, user.pointOnLane); uint256 rewardAmount = expMul(user.deposited, distance); return safeAdd(user.rewardAmount, rewardAmount); } function _updateRewardLaneView(uint256 fromBlockNumber) internal view returns (uint256) { /// @dev Set up memory variables used for calculation temporarily. UpdateRewardLaneModel memory vars; vars.len = registeredPoints.length; vars.memTotalDeposit = totalDeposited; if(fromBlockNumber == 0){ vars.tmpPassedPoint = vars.memPassedPoint = 0; vars.memThisBlockNum = block.number; vars.tmpLastBlockNum = vars.memLastBlockNum = 0; vars.tmpRewardLane = vars.memRewardLane = 0; vars.tmpRewardPerBlock = vars.memRewardPerBlock = 0; vars.tmpDecrementUnitPerBlock = vars.memDecrementUnitPerBlock = 0; } else { vars.tmpPassedPoint = vars.memPassedPoint = passedPoint; vars.memThisBlockNum = block.number; vars.tmpLastBlockNum = vars.memLastBlockNum = fromBlockNumber; vars.tmpRewardLane = vars.memRewardLane = rewardLane; vars.tmpRewardPerBlock = vars.memRewardPerBlock = rewardPerBlock; vars.tmpDecrementUnitPerBlock = vars.memDecrementUnitPerBlock = decrementUnitPerBlock; } for(uint256 i=vars.memPassedPoint; i<vars.len; i++) { RewardVelocityPoint memory point = registeredPoints[i]; /** * @dev Check whether this reward velocity point is valid and has not applied yet. */ if(vars.tmpLastBlockNum < point.blockNumber && point.blockNumber <= vars.memThisBlockNum) { vars.tmpPassedPoint = i+1; /// @dev Update the reward lane with the tmp variables vars.tmpBlockDelta = safeSub(point.blockNumber, vars.tmpLastBlockNum); (vars.tmpRewardLane, vars.tmpRewardPerBlock) = _calcNewRewardLane( vars.tmpRewardLane, vars.memTotalDeposit, vars.tmpRewardPerBlock, vars.tmpDecrementUnitPerBlock, vars.tmpBlockDelta); /// @dev Update the tmp variables with this reward velocity point. vars.tmpLastBlockNum = point.blockNumber; vars.tmpRewardPerBlock = point.rewardPerBlock; vars.tmpDecrementUnitPerBlock = point.decrementUnitPerBlock; /** * @dev Notify the update of the parameters (by passing the reward velocity points) */ } else { /// @dev sorted array, exit eariler without accessing future points. break; } } /** * @dev Update the reward lane for the remained period between the latest velocity point and this moment (block) */ if(vars.memThisBlockNum > vars.tmpLastBlockNum) { vars.tmpBlockDelta = safeSub(vars.memThisBlockNum, vars.tmpLastBlockNum); vars.tmpLastBlockNum = vars.memThisBlockNum; (vars.tmpRewardLane, vars.tmpRewardPerBlock) = _calcNewRewardLane( vars.tmpRewardLane, vars.memTotalDeposit, vars.tmpRewardPerBlock, vars.tmpDecrementUnitPerBlock, vars.tmpBlockDelta); } return vars.tmpRewardLane; } /** * @notice Get The rewardPerBlock of user in suggested period(see params) * @param userAddr The Address of user, 0 for total * @param fromBlockNumber calculation start block number * @param toBlockNumber calculation end block number * @notice this function calculate based on current contract state */ function getPoolRate(address userAddr, uint256 fromBlockNumber, uint256 toBlockNumber) internal view returns (uint256) { UpdateRewardLaneModel memory vars; vars.len = registeredPoints.length; vars.memTotalDeposit = totalDeposited; vars.tmpLastBlockNum = vars.memLastBlockNum = fromBlockNumber; (vars.memPassedPoint, vars.memRewardPerBlock, vars.memDecrementUnitPerBlock) = getParamsByBlockNumber(fromBlockNumber); vars.tmpPassedPoint = vars.memPassedPoint; vars.tmpRewardPerBlock = vars.memRewardPerBlock; vars.tmpDecrementUnitPerBlock = vars.memDecrementUnitPerBlock; vars.memThisBlockNum = toBlockNumber; vars.tmpRewardLane = vars.memRewardLane = 0; for(uint256 i=vars.memPassedPoint; i<vars.len; i++) { RewardVelocityPoint memory point = registeredPoints[i]; if(vars.tmpLastBlockNum < point.blockNumber && point.blockNumber <= vars.memThisBlockNum) { vars.tmpPassedPoint = i+1; vars.tmpBlockDelta = safeSub(point.blockNumber, vars.tmpLastBlockNum); (vars.tmpRewardLane, vars.tmpRewardPerBlock) = _calcNewRewardLane( vars.tmpRewardLane, vars.memTotalDeposit, vars.tmpRewardPerBlock, vars.tmpDecrementUnitPerBlock, vars.tmpBlockDelta); vars.tmpLastBlockNum = point.blockNumber; vars.tmpRewardPerBlock = point.rewardPerBlock; vars.tmpDecrementUnitPerBlock = point.decrementUnitPerBlock; } else { break; } } if(vars.memThisBlockNum > vars.tmpLastBlockNum) { vars.tmpBlockDelta = safeSub(vars.memThisBlockNum, vars.tmpLastBlockNum); vars.tmpLastBlockNum = vars.memThisBlockNum; (vars.tmpRewardLane, vars.tmpRewardPerBlock) = _calcNewRewardLane( vars.tmpRewardLane, vars.memTotalDeposit, vars.tmpRewardPerBlock, vars.tmpDecrementUnitPerBlock, vars.tmpBlockDelta); } Account memory user; if( userAddr != address(0) ) user = accounts[userAddr]; else user = Account(vars.memTotalDeposit, 0, 0); return safeDiv(expMul(user.deposited, vars.tmpRewardLane), safeSub(toBlockNumber, fromBlockNumber)); } function getParamsByBlockNumber(uint256 _blockNumber) internal view returns (uint256, uint256, uint256) { uint256 _rewardPerBlock; uint256 _decrement; uint256 i; uint256 tmpthisPoint; uint256 pointLength = registeredPoints.length; if( pointLength > 0 ) { for(i = 0; i < pointLength; i++) { RewardVelocityPoint memory point = registeredPoints[i]; if(_blockNumber >= point.blockNumber && 0 != point.blockNumber) { tmpthisPoint = i; _rewardPerBlock = point.rewardPerBlock; _decrement = point.decrementUnitPerBlock; } else if( 0 == point.blockNumber ) continue; else break; } } RewardVelocityPoint memory point = registeredPoints[tmpthisPoint]; _rewardPerBlock = point.rewardPerBlock; _decrement = point.decrementUnitPerBlock; if(_blockNumber > point.blockNumber) { _rewardPerBlock = safeSub(_rewardPerBlock, safeMul(_decrement, safeSub(_blockNumber, point.blockNumber) ) ); } return (i, _rewardPerBlock, _decrement); } function getUserPoolRate(address userAddr, uint256 fromBlockNumber, uint256 toBlockNumber) external view returns (uint256) { return getPoolRate(userAddr, fromBlockNumber, toBlockNumber); } function getModelPoolRate(uint256 fromBlockNumber, uint256 toBlockNumber) external view returns (uint256) { return getPoolRate(address(0), fromBlockNumber, toBlockNumber); } } // File: contracts/module/externalModule.sol pragma solidity 0.6.12; /** * @title BiFi's Reward Distribution External Contract * @notice Implements the service actions. * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract externalModule is viewModule { modifier onlyOwner() { require(msg.sender == owner, "onlyOwner: external function access control!"); _; } modifier checkClaimLocked() { require(!claimLock, "error: claim Locked"); _; } modifier checkWithdrawLocked() { require(!withdrawLock, "error: withdraw Locked"); _; } /** * @notice Set the Deposit-Token address * @param erc20Addr The address of Deposit Token */ function setERC(address erc20Addr) external onlyOwner { lpErc = ERC20(erc20Addr); } /** * @notice Set the Contribution-Token address * @param erc20Addr The address of Contribution Token */ function setRE(address erc20Addr) external onlyOwner { rewardErc = ERC20(erc20Addr); } /** * @notice Set the reward distribution parameters instantly */ function setParam(uint256 _rewardPerBlock, uint256 _decrementUnitPerBlock) onlyOwner external { _setParams(_rewardPerBlock, _decrementUnitPerBlock); } /** * @notice Terminate Contract Distribution */ function modelFinish(uint256 amount) external onlyOwner { if( amount != 0) { require( rewardErc.transfer(owner, amount), "token error" ); } else { require( rewardErc.transfer(owner, rewardErc.balanceOf(address(this))), "token error" ); } delete totalDeposited; delete rewardPerBlock; delete decrementUnitPerBlock; delete rewardLane; delete totalDeposited; delete registeredPoints; } /** * @notice Transfer the Remaining Contribution Tokens */ function retrieveRewardAmount(uint256 amount) external onlyOwner { if( amount != 0) { require( rewardErc.transfer(owner, amount), "token error"); } else { require( rewardErc.transfer(owner, rewardErc.balanceOf(address(this))), "token error"); } } /** * @notice Deposit the Contribution Tokens * @param amount The amount of the Contribution Tokens */ function deposit(uint256 amount) external { address userAddr = msg.sender; _redeemAll(userAddr); _deposit(userAddr, amount); } /** * @notice Deposit the Contribution Tokens to target user * @param userAddr The target user * @param amount The amount of the Contribution Tokens */ function depositTo(address userAddr, uint256 amount) external { _redeemAll(userAddr); _deposit(userAddr, amount); } /** * @notice Withdraw the Contribution Tokens * @param amount The amount of the Contribution Tokens */ function withdraw(uint256 amount) checkWithdrawLocked external { address userAddr = msg.sender; _redeemAll(userAddr); _withdraw(userAddr, amount); } /** * @notice Claim the Reward Tokens * @dev Transfer all reward the user has earned at once. */ function rewardClaim() checkClaimLocked external { address userAddr = msg.sender; _redeemAll(userAddr); _rewardClaim(userAddr); } /** * @notice Claim the Reward Tokens * @param userAddr The targetUser * @dev Transfer all reward the target user has earned at once. */ function rewardClaimTo(address userAddr) checkClaimLocked external { _redeemAll(userAddr); _rewardClaim(userAddr); } /// @dev Set locks & access control function setClaimLock(bool lock) onlyOwner external { _setClaimLock(lock); } function setWithdrawLock(bool lock) onlyOwner external { _setWithdrawLock(lock); } function ownershipTransfer(address newPendingOwner) onlyOwner external { _setPendingOwner(newPendingOwner); } function acceptOwnership() external { address sender = msg.sender; require(sender == pendingOwner, "msg.sender != pendingOwner"); _setOwner(sender); } /** * @notice Register a new future reward velocity point */ function registerRewardVelocity(uint256 _blockNumber, uint256 _rewardPerBlock, uint256 _decrementUnitPerBlock) onlyOwner public { require(_blockNumber > block.number, "new Reward params should register earlier"); require(registeredPoints.length == 0 || _blockNumber > registeredPoints[registeredPoints.length-1].blockNumber, "Earilier velocity points are already set."); _registerRewardVelocity(_blockNumber, _rewardPerBlock, _decrementUnitPerBlock); } function deleteRegisteredRewardVelocity(uint256 _index) onlyOwner external { require(_index >= passedPoint, "Reward velocity point already passed."); _deleteRegisteredRewardVelocity(_index); } /** * @notice Set the reward distribution parameters */ function setRewardVelocity(uint256 _rewardPerBlock, uint256 _decrementUnitPerBlock) onlyOwner external { _updateRewardLane(); _setParams(_rewardPerBlock, _decrementUnitPerBlock); } } // File: contracts/DistributionModelV3.sol pragma solidity 0.6.12; /** * @title BiFi's Reward Distribution Contract * @notice Implements voting process along with vote delegation * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract DistributionModelV3 is externalModule { constructor(address _owner, address _lpErc, address _rewardErc) public { owner = _owner; lpErc = ERC20(_lpErc); rewardErc = ERC20(_rewardErc); lastBlockNum = block.number; } } contract BFCModel is DistributionModelV3 { constructor(address _owner, address _lpErc, address _rewardErc, uint256 _start) DistributionModelV3(_owner, _lpErc, _rewardErc) public { /* _start: parameter start block nubmer 0x3935413a1cdd90ff: fixed point(1e18) reward per blocks 0x62e9bea75f: fixed point(1e18) decrement per blocks */ _registerRewardVelocity(_start, 0x3935413a1cdd90ff, 0x62e9bea75f); } } contract BFCETHModel is DistributionModelV3 { constructor(address _owner, address _lpErc, address _rewardErc, uint256 _start) DistributionModelV3(_owner, _lpErc, _rewardErc) public { /* _start: parameter start block nubmer 0xe4d505786b744b3f: fixed point(1e18) reward per blocks 0x18ba6fb966b: fixed point(1e18) decrement per blocks */ _registerRewardVelocity(_start, 0xe4d505786b744b3f, 0x18ba6fb966b); } } contract BiFiETHModel is DistributionModelV3 { constructor(address _owner, address _lpErc, address _rewardErc, uint256 _start) DistributionModelV3(_owner, _lpErc, _rewardErc) public { /* _start: parameter start block nubmer 0x11e0a46e285a68955: fixed point(1e18) reward per blocks 0x1ee90ba90c4: fixed point(1e18) decrement per blocks */ _registerRewardVelocity(_start, 0x11e0a46e285a68955, 0x1ee90ba90c4); } } // File: contracts/SRD_SushiSwap.sol pragma solidity 0.6.12; contract BFCETHSushiSwapReward is DistributionModelV3 { constructor(uint256 start, uint256 reward_per_block, uint256 dec_per_block) DistributionModelV3( 0x359903041dE93c69828F911aeB0BE29CC9ccc58b, //ower 0x281Df7fc89294C84AfA2A21FfEE8f6807F9C9226, //swap_pool_token(BFCETH_Sushi) 0x2791BfD60D232150Bff86b39B7146c0eaAA2BA81 //reward_token(bifi) ) public { _registerRewardVelocity(start, reward_per_block, dec_per_block); pendingOwner = msg.sender; } } contract BiFiETHSushiSwapReward is DistributionModelV3 { constructor(uint256 start, uint256 reward_per_block, uint256 dec_per_block) DistributionModelV3( 0x359903041dE93c69828F911aeB0BE29CC9ccc58b, //owner 0x0beC54c89a7d9F15C4e7fAA8d47ADEdF374462eD, //swap_pool_token(BiFiETH_Sushi) 0x2791BfD60D232150Bff86b39B7146c0eaAA2BA81 //reward_token(bifi) ) public { _registerRewardVelocity(start, reward_per_block, dec_per_block); pendingOwner = msg.sender; } }
* @notice Set the Deposit-Token address @param erc20Addr The address of Deposit Token/
function setERC(address erc20Addr) external onlyOwner { lpErc = ERC20(erc20Addr); }
5,357,581
[ 1, 694, 326, 4019, 538, 305, 17, 1345, 1758, 225, 6445, 71, 3462, 3178, 1021, 1758, 434, 4019, 538, 305, 3155, 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, 445, 444, 654, 39, 12, 2867, 6445, 71, 3462, 3178, 13, 3903, 1338, 5541, 288, 203, 3639, 12423, 41, 1310, 273, 4232, 39, 3462, 12, 12610, 3462, 3178, 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 ]
pragma solidity ^0.4.0; import './ownable.sol'; // Import Ownable contract. /** @title Data.*/ contract Data is Ownable { // TYPES uint internal time; // Time of the last refill. uint internal rewardPerDay; // Reward per day. uint internal available; // Available per day. uint internal timesPerDay; // Times you have to save all types of data per day to complete the cycle. struct DataType { // Struct. string name; // Data Type name. uint reward; // Reward in Cell. uint times; // Times to complete the cycle per day. uint time; // Time to complete the cycle per day. bool state; // State of the struct tobe used. bool toCount; // True if it were counted for the cycle per day. } mapping ( string => uint ) internal data; // Saving the id of each DataType.name. DataType[] internal dataTypes; // DataType struct array. modifier isValidData( string dataType ){ require( data[dataType] != 0 ); _; } constructor() public { rewardPerDay = 2000000000000000000000; available = 2000000000000000000000; time = now; // Set to time. // Default. uint id = dataTypes.push(DataType({ name: "", reward: 0, times: 0, time: 0, state: false, toCount: false })); data[""] = id; // Energy. id = dataTypes.push(DataType({ name: "Energy", reward: 100000000000000, times: 1, time: 1 days, state: true, toCount: true })) - 1; data["Energy"] = id; // Water. id = dataTypes.push(DataType({ name: "Water", reward: 100000000000000, times: 8, time: 1 days, state: true, toCount: true })) - 1; data["Water"] = id; // Meditation. id = dataTypes.push(DataType({ name: "Meditation", reward: 100000000000000, times: 1, time: 1 days, state: true, toCount: true })) - 1; data["Meditation"] = id; // Stool. id = dataTypes.push(DataType({ name: "Stool", reward: 100000000000000, times: 1, time: 1 days, state: true, toCount: true })) - 1; data["Stool"] = id; // Sleep. id = dataTypes.push(DataType({ name: "Sleep", reward: 100000000000000, times: 1, time: 1 days, state: true, toCount: true })) - 1; data["Sleep"] = id; // Survey. id = dataTypes.push(DataType({ name: "Survey", reward: 100000000000000, times: 1, time: 30 days, state: true, toCount: false })) - 1; data["Survey"] = id; // Profile. id = dataTypes.push(DataType({ name: "Profile", reward: 0, times: 1, time: 0, state: true, toCount: false })) - 1; data["Profile"] = id; //MRI. id = dataTypes.push(DataType({ name: "MRI", reward: 0, times: 0, time: 0, state: false, toCount: false })) - 1; data["MRI"] = id; setTimesPerDay(); // Set timtimesPerDay. } // PUBLIC METHODS - ONLY OWNER /** * @dev Create DataType * @param _dataType String - Data Type name. * @param _times Uint - Times to complete the cycle per day. * @param _reward Uint - Reward in Cell. * @param _time Uint - Time to complete the cycle per day. * @param _state Bool - State of the struct tobe used. * @param _toCount Bool - True if it were counted for the cycle per day. */ function createDataType( string _dataType, uint _times, uint _reward, uint _time, bool _state, bool _toCount ) onlyOwner public { uint id = dataTypes.push(DataType({ name: _dataType, reward: _reward, times: _times, time: _time, state: _state, toCount: _toCount })) - 1; data[_dataType] = id; setTimesPerDay(); } /** * @dev Update a DataType * @param _dataType String - Data Type name. * @param _times Uint - Times to complete the cycle per day. * @param _reward Uint - Reward in Cell. * @param _time Uint - Time to complete the cycle per day. * @param _state Bool - State of the struct tobe used. * @param _toCount Bool - True if it were counted for the cycle per day. */ function updateDataType( string _dataType, uint _times, uint _reward, uint _time, bool _state, bool _toCount ) onlyOwner isValidData( _dataType ) public { uint id = data[_dataType]; dataTypes[id].times = _times; dataTypes[id].reward = _reward; dataTypes[id].time = 1 hours * _time; dataTypes[id].state = _state; dataTypes[id].toCount = _toCount; setTimesPerDay(); } /** * @param _dataType String - * @return _dataType String - Data Type name. * @return _times Uint - Times to complete the cycle per day. * @return _reward Uint - Reward in Cell. * @return _time Uint - Time to complete the cycle per day. * @return _state Bool - State of the struct tobe used. * @return _toCount Bool - True if it were counted for the cycle per day. */ function getDataType( string _dataType ) onlyOwner isValidData( _dataType ) public constant returns( string name, uint reward, uint times, uint timeInSecond, bool state, bool toCount ) { uint id = data[_dataType]; DataType storage dt = dataTypes[id]; return ( dt.name, dt.reward, dt.times, dt.time, dt.state, dt.toCount ); } /** * @dev Change the state of the DataType * @param _dataType String - Data type. */ function changeState( string _dataType ) onlyOwner isValidData( _dataType ) public { uint id = data[_dataType]; DataType storage dt = dataTypes[id]; dt.state = !dt.state; } /** * @dev Change the toCount of the toCount * @param _dataType String - Data type. */ function changeToCount( string _dataType ) onlyOwner isValidData( _dataType ) public { uint id = data[_dataType]; DataType storage dt = dataTypes[id]; dt.toCount = !dt.toCount; setTimesPerDay(); } /** * @dev Change the reward of the DataType * @param _dataType String - Data type. * @param _reward Uint - Reward in Cell. */ function setReward( string _dataType, uint _reward) onlyOwner isValidData( _dataType ) public { uint id = data[_dataType]; DataType storage dt = dataTypes[id]; dt.reward = _reward; } /** * @dev Change the time of the DataType * @param dataType String - Data type. * @param _time Uint - Time to complete the cycle per day. */ function setTime( string dataType, uint _time) onlyOwner isValidData( dataType ) public { uint id = data[dataType]; DataType storage dt = dataTypes[id]; dt.time = 1 hours * _time; } /** * @dev Change times of the DataType. * @param dataType String - Data type . * @param _times Uint - Times to complete the cycle per day. */ function setTimes( string dataType, uint _times ) onlyOwner isValidData( dataType ) public { uint id = data[dataType]; DataType storage dt = dataTypes[id]; dt.times = _times; setTimesPerDay(); } /** * @param _available Uint - Set avaliable per day. */ function setAvaliable( uint _available ) onlyOwner public { available = _available; } /** * @param _rewardPerDay Uint - Set reward per day. */ function setRewardPerDay( uint _rewardPerDay ) onlyOwner public { rewardPerDay = _rewardPerDay; } // PUBLIC METHODS /** * @return available Uint - Reward per day. */ function getAvailable() public constant returns ( uint ) { return available; } /** * @return rewardPerDay Uint - The available Cell per day to the reward. */ function getRewardPerDay() public constant returns ( uint ) { return rewardPerDay; } /** * @return timesPerDay Uint - The time to complete a cycle. */ function getTimesPerDay() public constant returns ( uint ) { return timesPerDay; } /** * @return Uint - Id by dataType. */ function getIdByName( string _dataType ) public constant isValidData( _dataType ) returns( uint ) { return data[_dataType]; } /** * @return Uint - reward by dataType. */ function getReward( string _dataType ) public constant isValidData( _dataType ) returns( uint ) { uint id = data[_dataType]; DataType storage dt = dataTypes[id]; return dt.reward; } /** * @return Uint - time by dataType. */ function getTime( string _dataType ) public constant isValidData( _dataType ) returns( uint ) { uint id = data[_dataType]; DataType storage dt = dataTypes[id]; return dt.time; } /** * @return Uint - times by dataType. */ function getTimes( string _dataType ) public constant isValidData( _dataType ) returns( uint ) { uint id = data[_dataType]; DataType storage dt = dataTypes[id]; return dt.times; } /** * @return Uint - state by dataType. */ function getState( string _dataType ) public constant isValidData( _dataType ) returns( bool ) { uint id = data[_dataType]; DataType storage dt = dataTypes[id]; return dt.state; } /** * @return Uint - toCount by dataType. */ function getToCount( string _dataType ) public constant isValidData( _dataType ) returns( bool ) { uint id = data[_dataType]; DataType storage dt = dataTypes[id]; return dt.toCount; } /** * @return Uint - Length of the dataType. */ function getDataTypesLength() public constant returns ( uint ) { return dataTypes.length; } function getDataTypeNameById( uint _id ) public constant returns ( string ) { return dataTypes[_id].name; } // INTERNAL METHODS /** * @dev Restart the available reward. */ function restartReward() public returns ( bool ) { rewardPerDay = available; time = now; // Set time. return true; } /** * return Bool - Check if the day is over. */ function isDayOver() public constant returns ( bool ) { if( time + 1 days < now ) return true; else return false; } // PRIVATE METHODS /** * @dev Set timesPerDay. */ function setTimesPerDay() private { uint times; for( uint i = 0 ; i < dataTypes.length ; i++ ){ if( dataTypes[i].toCount ) times += dataTypes[i].times; } timesPerDay = times; } }
* @param _rewardPerDay Uint - Set reward per day./
{ rewardPerDay = _rewardPerDay; }
5,536,635
[ 1, 67, 266, 2913, 2173, 4245, 7320, 300, 1000, 19890, 1534, 2548, 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, 288, 203, 3639, 19890, 2173, 4245, 273, 389, 266, 2913, 2173, 4245, 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, -100, -100, -100, -100, -100, -100 ]
// File: contracts/interface/ICoFiXERC20.sol // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.12; interface ICoFiXERC20 { 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; } // File: contracts/interface/ICoFiXV2Pair.sol pragma solidity 0.6.12; interface ICoFiXV2Pair is ICoFiXERC20 { struct OraclePrice { uint256 ethAmount; uint256 erc20Amount; uint256 blockNum; uint256 K; uint256 theta; } // All pairs: {ETH <-> ERC20 Token} event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, address outToken, uint outAmount, address indexed to); event Swap( address indexed sender, uint amountIn, uint amountOut, address outToken, 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); function mint(address to, uint amountETH, uint amountToken) external payable returns (uint liquidity, uint oracleFeeChange); function burn(address tokenTo, address ethTo) external payable returns (uint amountTokenOut, uint amountETHOut, uint oracleFeeChange); function swapWithExact(address outToken, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[5] memory tradeInfo); // function swapForExact(address outToken, uint amountOutExact, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[4] memory tradeInfo); function skim(address to) external; function sync() external; function initialize(address, address, string memory, string memory, uint256, uint256) external; /// @dev get Net Asset Value Per Share /// @param ethAmount ETH side of Oracle price {ETH <-> ERC20 Token} /// @param erc20Amount Token side of Oracle price {ETH <-> ERC20 Token} /// @return navps The Net Asset Value Per Share (liquidity) represents function getNAVPerShare(uint256 ethAmount, uint256 erc20Amount) external view returns (uint256 navps); /// @dev get initial asset ratio /// @return _initToken0Amount Token0(ETH) side of initial asset ratio {ETH <-> ERC20 Token} /// @return _initToken1Amount Token1(ERC20) side of initial asset ratio {ETH <-> ERC20 Token} function getInitialAssetRatio() external view returns (uint256 _initToken0Amount, uint256 _initToken1Amount); } // File: contracts/interface/ICoFiXStakingRewards.sol pragma solidity 0.6.12; interface ICoFiXStakingRewards { // Views /// @dev The rewards vault contract address set in factory contract /// @return Returns the vault address function rewardsVault() external view returns (address); /// @dev The lastBlock reward applicable /// @return Returns the latest block.number on-chain function lastBlockRewardApplicable() external view returns (uint256); /// @dev Reward amount represents by per staking token function rewardPerToken() external view returns (uint256); /// @dev How many reward tokens a user has earned but not claimed at present /// @param account The target account /// @return The amount of reward tokens a user earned function earned(address account) external view returns (uint256); /// @dev How many reward tokens accrued recently /// @return The amount of reward tokens accrued recently function accrued() external view returns (uint256); /// @dev Get the latest reward rate of this mining pool (tokens amount per block) /// @return The latest reward rate function rewardRate() external view returns (uint256); /// @dev How many stakingToken (XToken) deposited into to this reward pool (mining pool) /// @return The total amount of XTokens deposited in this mining pool function totalSupply() external view returns (uint256); /// @dev How many stakingToken (XToken) deposited by the target account /// @param account The target account /// @return The total amount of XToken deposited in this mining pool function balanceOf(address account) external view returns (uint256); /// @dev Get the address of token for staking in this mining pool /// @return The staking token address function stakingToken() external view returns (address); /// @dev Get the address of token for rewards in this mining pool /// @return The rewards token address function rewardsToken() external view returns (address); // Mutative /// @dev Stake/Deposit into the reward pool (mining pool) /// @param amount The target amount function stake(uint256 amount) external; /// @dev Stake/Deposit into the reward pool (mining pool) for other account /// @param other The target account /// @param amount The target amount function stakeForOther(address other, uint256 amount) external; /// @dev Withdraw from the reward pool (mining pool), get the original tokens back /// @param amount The target amount function withdraw(uint256 amount) external; /// @dev Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw() external; /// @dev Claim the reward the user earned function getReward() external; function getRewardAndStake() external; /// @dev User exit the reward pool, it's actually withdraw and getReward function exit() external; /// @dev Add reward to the mining pool function addReward(uint256 amount) external; // Events event RewardAdded(address sender, uint256 reward); event Staked(address indexed user, uint256 amount); event StakedForOther(address indexed user, address indexed other, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); } // File: contracts/interface/ICoFiXVaultForLP.sol pragma solidity 0.6.12; interface ICoFiXVaultForLP { enum POOL_STATE {INVALID, ENABLED, DISABLED} event NewPoolAdded(address pool, uint256 index); event PoolEnabled(address pool); event PoolDisabled(address pool); function setGovernance(address _new) external; function setInitCoFiRate(uint256 _new) external; function setDecayPeriod(uint256 _new) external; function setDecayRate(uint256 _new) external; function addPool(address pool) external; function enablePool(address pool) external; function disablePool(address pool) external; function setPoolWeight(address pool, uint256 weight) external; function batchSetPoolWeight(address[] memory pools, uint256[] memory weights) external; function distributeReward(address to, uint256 amount) external; function getPendingRewardOfLP(address pair) external view returns (uint256); function currentPeriod() external view returns (uint256); function currentCoFiRate() external view returns (uint256); function currentPoolRate(address pool) external view returns (uint256 poolRate); function currentPoolRateByPair(address pair) external view returns (uint256 poolRate); /// @dev Get the award staking pool address of pair (XToken) /// @param pair The address of XToken(pair) contract /// @return pool The pool address function stakingPoolForPair(address pair) external view returns (address pool); function getPoolInfo(address pool) external view returns (POOL_STATE state, uint256 weight); function getPoolInfoByPair(address pair) external view returns (POOL_STATE state, uint256 weight); function getEnabledPoolCnt() external view returns (uint256); function getCoFiStakingPool() external view returns (address pool); } // File: contracts/interface/ICoFiXV2Factory.sol pragma solidity 0.6.12; interface ICoFiXV2Factory { // All pairs: {ETH <-> ERC20 Token} event PairCreated(address indexed token, address pair, uint256); event NewGovernance(address _new); event NewController(address _new); event NewFeeReceiver(address _new); event NewFeeVaultForLP(address token, address feeVault); event NewVaultForLP(address _new); event NewVaultForTrader(address _new); event NewVaultForCNode(address _new); event NewDAO(address _new); /// @dev Create a new token pair for trading /// @param token the address of token to trade /// @param initToken0Amount the initial asset ratio (initToken0Amount:initToken1Amount) /// @param initToken1Amount the initial asset ratio (initToken0Amount:initToken1Amount) /// @return pair the address of new token pair function createPair( address token, uint256 initToken0Amount, uint256 initToken1Amount ) external returns (address pair); function getPair(address token) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function getTradeMiningStatus(address token) external view returns (bool status); function setTradeMiningStatus(address token, bool status) external; function getFeeVaultForLP(address token) external view returns (address feeVault); // for LPs function setFeeVaultForLP(address token, address feeVault) external; function setGovernance(address _new) external; function setController(address _new) external; function setFeeReceiver(address _new) external; function setVaultForLP(address _new) external; function setVaultForTrader(address _new) external; function setVaultForCNode(address _new) external; function setDAO(address _new) external; function getController() external view returns (address controller); function getFeeReceiver() external view returns (address feeReceiver); // For CoFi Holders function getVaultForLP() external view returns (address vaultForLP); function getVaultForTrader() external view returns (address vaultForTrader); function getVaultForCNode() external view returns (address vaultForCNode); function getDAO() external view returns (address dao); } // File: @openzeppelin/contracts/utils/ReentrancyGuard.sol 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; } } // File: contracts/interface/ICoFiXV2VaultForTrader.sol pragma solidity 0.6.12; interface ICoFiXV2VaultForTrader { event RouterAllowed(address router); event RouterDisallowed(address router); event ClearPendingRewardOfCNode(uint256 pendingAmount); event ClearPendingRewardOfLP(uint256 pendingAmount); function setGovernance(address gov) external; // function setExpectedYieldRatio(uint256 r) external; // function setLRatio(uint256 lRatio) external; // function setTheta(uint256 theta) external; function setCofiRate(uint256 cofiRate) external; function allowRouter(address router) external; function disallowRouter(address router) external; function calcMiningRate(address pair, uint256 neededETHAmount) external view returns (uint256); function calcNeededETHAmountForAdjustment(address pair, uint256 reserve0, uint256 reserve1, uint256 ethAmount, uint256 erc20Amount) external view returns (uint256); function actualMiningAmount(address pair, uint256 reserve0, uint256 reserve1, uint256 ethAmount, uint256 erc20Amount) external view returns (uint256 amount, uint256 totalAccruedAmount, uint256 neededETHAmount); function distributeReward(address pair, uint256 ethAmount, uint256 erc20Amount, address rewardTo) external; function clearPendingRewardOfCNode() external; function clearPendingRewardOfLP(address pair) external; function getPendingRewardOfCNode() external view returns (uint256); function getPendingRewardOfLP(address pair) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/interface/ICoFiToken.sol pragma solidity 0.6.12; interface ICoFiToken is IERC20 { /// @dev An event thats emitted when a new governance account is set /// @param _new The new governance address event NewGovernance(address _new); /// @dev An event thats emitted when a new minter account is added /// @param _minter The new minter address added event MinterAdded(address _minter); /// @dev An event thats emitted when a minter account is removed /// @param _minter The minter address removed event MinterRemoved(address _minter); /// @dev Set governance address of CoFi token. Only governance has the right to execute. /// @param _new The new governance address function setGovernance(address _new) external; /// @dev Add a new minter account to CoFi token, who can mint tokens. Only governance has the right to execute. /// @param _minter The new minter address function addMinter(address _minter) external; /// @dev Remove a minter account from CoFi token, who can mint tokens. Only governance has the right to execute. /// @param _minter The minter address removed function removeMinter(address _minter) external; /// @dev mint is used to distribute CoFi token to users, minters are CoFi mining pools /// @param _to The receiver address /// @param _amount The amount of tokens minted function mint(address _to, uint256 _amount) external; } // File: contracts/lib/ABDKMath64x64.sol /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity 0.6.12; /** * 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 { /** * @dev Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /** * @dev 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), uint256 (x) + uint256 (y) >> 1)); } /** * 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) { uint256 absoluteResult; bool negativeResult = false; if (x >= 0) { absoluteResult = powu (uint256 (x) << 63, y); } else { // We rely on overflow behavior here absoluteResult = powu (uint256 (uint128 (-x)) << 63, y); negativeResult = y & 1 > 0; } absoluteResult >>= 63; 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 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, 0x10000000000000000)); } /** * 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) << 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 >>= 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 x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point * number and y is unsigned 256-bit integer number. Revert on overflow. * * @param x unsigned 129.127-bit fixed point number * @param y uint256 value * @return unsigned 129.127-bit fixed point number */ function powu (uint256 x, uint256 y) private pure returns (uint256) { if (y == 0) return 0x80000000000000000000000000000000; else if (x == 0) return 0; else { int256 msb = 0; uint256 xc = x; if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; } 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 xe = msb - 127; if (xe > 0) x >>= xe; else x <<= -xe; uint256 result = 0x80000000000000000000000000000000; int256 re = 0; while (y > 0) { if (y & 1 > 0) { result = result * x; y -= 1; re += xe; if (result >= 0x8000000000000000000000000000000000000000000000000000000000000000) { result >>= 128; re += 1; } else result >>= 127; if (re < -127) return 0; // Underflow require (re < 128); // Overflow } else { x = x * x; y >>= 1; xe <<= 1; if (x >= 0x8000000000000000000000000000000000000000000000000000000000000000) { x >>= 128; xe += 1; } else x >>= 127; if (xe < -127) return 0; // Underflow require (xe < 128); // Overflow } } if (re > 0) result <<= re; else if (re < 0) result >>= -re; return 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, uint256 r) private pure returns (uint128) { if (x == 0) return 0; else { require (r > 0); while (true) { uint256 rr = x / r; if (r == rr || r + 1 == rr) return uint128 (r); else if (r == rr + 1) return uint128 (rr); r = r + rr + 1 >> 1; } } } } // 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: contracts/CoFiXV2VaultForTrader.sol pragma solidity 0.6.12; // Reward Pool Controller for Trader // Trade to earn CoFi Token contract CoFiXV2VaultForTrader is ICoFiXV2VaultForTrader, ReentrancyGuard { using SafeMath for uint256; uint256 public constant RATE_BASE = 1e18; uint256 public constant LAMBDA_BASE = 100; // uint256 public constant RECENT_RANGE = 300; uint256 public constant SHARE_BASE = 100; uint256 public constant SHARE_FOR_TRADER = 90; // uint256 public constant SHARE_FOR_LP = 10; uint256 public constant SHARE_FOR_CNODE = 10; // uint256 public constant NAVPS_BASE = 1E18; // NAVPS (Net Asset Value Per Share), need accuracy // make all of these constant, so we can reduce gas cost for swap features // uint256 public constant COFI_DECAY_PERIOD = 2400000; // LP pool yield decays for every 2,400,000 blocks // uint256 public constant THETA_FEE_UINIT = 1 ether; // uint256 public constant L_LIMIT = 100 ether; // uint256 public constant COFI_RATE_UPDATE_INTERVAL = 1000; // uint256 public constant EXPECT_YIELD_BASE = 10; // uint256 public constant L_BASE = 1000; // uint256 public constant THETA_BASE = 1000; // uint256 public constant REWARD_MULTIPLE_BASE = 100; address public immutable cofiToken; address public immutable factory; // managed by governance address public governance; // uint256 public EXPECT_YIELD_RATIO = 3; // r, 0.3 // uint256 public L_RATIO = 2; // l, 0.002 // uint256 public THETA = 2; // 0.002 uint256 public cofiRate = 0.1*1e18; // nt 0.1 uint256 public pendingRewardsForCNode; mapping(address => uint256) public pendingRewardsForLP; // pair address to pending rewards amount mapping (address => bool) public routerAllowed; mapping (address => uint128) public lastMinedBlock; // last block mined cofi token mapping (address => uint256) public lastNeededETHAmount; // last needed eth amount for adjustment mapping (address => uint256) public lastTotalAccruedAmount; uint128 public lastDensity; // last mining density, see currentDensity() modifier onlyGovernance() { require(msg.sender == governance, "CVaultForTrader: !governance"); _; } constructor(address cofi, address _factory) public { cofiToken = cofi; factory = _factory; governance = msg.sender; } /* setters for protocol governance */ function setGovernance(address _new) external override onlyGovernance { governance = _new; } // function setExpectedYieldRatio(uint256 r) external override onlyGovernance { // EXPECT_YIELD_RATIO = r; // } // function setLRatio(uint256 lRatio) external override onlyGovernance { // L_RATIO = lRatio; // } // function setTheta(uint256 theta) external override onlyGovernance { // THETA = theta; // } function setCofiRate(uint256 _cofiRate) external override onlyGovernance { cofiRate = _cofiRate; } function allowRouter(address router) external override onlyGovernance { require(!routerAllowed[router], "CVaultForTrader: router allowed"); routerAllowed[router] = true; emit RouterAllowed(router); } function disallowRouter(address router) external override onlyGovernance { require(routerAllowed[router], "CVaultForTrader: router disallowed"); routerAllowed[router] = false; emit RouterDisallowed(router); } // calc v_t function calcMiningRate(address pair, uint256 neededETHAmount) public override view returns (uint256) { uint256 _lastNeededETHAmount = lastNeededETHAmount[pair]; if (_lastNeededETHAmount > neededETHAmount) { // D_{t-1} > D_t // \frac{D_{t-1} - D_t}{D_{t-1}} return _lastNeededETHAmount.sub(neededETHAmount).mul(RATE_BASE).div(_lastNeededETHAmount); // v_t } else { // D_{t-1} <= D_t return 0; // v_t } } // calc D_t :needed eth amount for adjusting kt to k0 function calcNeededETHAmountForAdjustment(address pair, uint256 reserve0, uint256 reserve1, uint256 ethAmount, uint256 erc20Amount) public override view returns (uint256) { /* D_t = |\frac{E_t * k_0 - U_t}{k_0 + P_t}|\\\\ = \frac{|E_t * \frac{initToken1Amount}{initToken0Amount} - U_t|}{\frac{initToken1Amount}{initToken0Amount} + \frac{erc20Amount}{ethAmount}}\\\\ = \frac{|E_t * initToken1Amount - U_t * initToken0Amount|}{initToken1Amount + \frac{erc20Amount * initToken0Amount}{ethAmount}}\\\\ = \frac{|E_t * initToken1Amount - U_t * initToken0Amount| * ethAmount}{initToken1Amount * ethAmount + erc20Amount * initToken0Amount}\\\\ */ { (uint256 initToken0Amount, uint256 initToken1Amount) = ICoFiXV2Pair(pair).getInitialAssetRatio(); uint256 reserve0MulInitToken1Amount = reserve0.mul(initToken1Amount); uint256 reserve1MulInitToken0Amount = reserve1.mul(initToken0Amount); uint256 diff = calcDiff(reserve0MulInitToken1Amount, reserve1MulInitToken0Amount); uint256 diffMulEthAmount = diff.mul(ethAmount); uint256 initToken1AmountMulEthAmount = initToken1Amount.mul(ethAmount); uint256 erc20AmountMulInitToken0Amount = erc20Amount.mul(initToken0Amount); return diffMulEthAmount.div(initToken1AmountMulEthAmount.add(erc20AmountMulInitToken0Amount)); } } function calcDiff(uint x, uint y) private pure returns (uint) { return x > y ? (x - y) : (y - x); } /* Y_t = Y_{t - 1} + D_{t - 1} * n_t * (S_t + 1) - Z_t Z_t = [Y_{t - 1} + D_{t - 1} * n_t * (S_t + 1)] * v_t */ function actualMiningAmount( address pair, uint256 reserve0, uint256 reserve1, uint256 ethAmount, uint256 erc20Amount ) public override view returns ( uint256 amount, uint256 totalAccruedAmount, uint256 neededETHAmount ) { uint256 totalAmount; { // Y_{t - 1} + D_{t - 1} * n_t * (S_t + 1) uint256 _lastTotalAccruedAmount = lastTotalAccruedAmount[pair]; // Y_{t - 1} uint256 _lastNeededETHAmount = lastNeededETHAmount[pair]; // D_{t - 1} uint256 _lastBlock = lastMinedBlock[pair]; uint256 _offset = block.number.sub(_lastBlock); // s_t totalAmount = _lastTotalAccruedAmount.add(_lastNeededETHAmount.mul(cofiRate).mul(_offset.add(1)).div(RATE_BASE)); } neededETHAmount = calcNeededETHAmountForAdjustment(pair, reserve0, reserve1, ethAmount, erc20Amount); // D_t uint256 miningRate = calcMiningRate(pair, neededETHAmount); // v_t // Z_t = [Y_{t - 1} + D_{t - 1} * n_t * (S_t + 1)] * v_t amount = totalAmount.mul(miningRate).div(RATE_BASE); // Y_t = Y_{t - 1} + D_{t - 1} * n_t * (S_t + 1) - Z_t totalAccruedAmount = totalAmount.sub(amount); } function distributeReward( address pair, uint256 ethAmount, uint256 erc20Amount, address rewardTo ) external override nonReentrant { require(routerAllowed[msg.sender], "CVaultForTrader: not allowed router"); // caution: be careful when adding new router require(pair != address(0), "CVaultForTrader: invalid pair"); require(rewardTo != address(0), "CVaultForTrader: invalid rewardTo"); uint256 amount; { uint256 totalAccruedAmount; uint256 neededETHAmount; (uint256 reserve0, uint256 reserve1) = ICoFiXV2Pair(pair).getReserves(); (amount, totalAccruedAmount, neededETHAmount) = actualMiningAmount(pair, reserve0, reserve1, ethAmount, erc20Amount); lastMinedBlock[pair] = uint128(block.number); // uint128 is enough for block.number lastTotalAccruedAmount[pair] = totalAccruedAmount; lastNeededETHAmount[pair] = neededETHAmount; } { uint256 amountForTrader = amount.mul(SHARE_FOR_TRADER).div(SHARE_BASE); // uint256 amountForLP = amount.mul(SHARE_FOR_LP).div(SHARE_BASE); uint256 amountForCNode = amount.mul(SHARE_FOR_CNODE).div(SHARE_BASE); ICoFiToken(cofiToken).mint(rewardTo, amountForTrader); // allows zero, send to receiver directly, reduce gas cost // pendingRewardsForLP[pair] = pendingRewardsForLP[pair].add(amountForLP); // possible key: token or pair, we use pair here pendingRewardsForCNode = pendingRewardsForCNode.add(amountForCNode); } } function clearPendingRewardOfCNode() external override nonReentrant { address vaultForCNode = ICoFiXV2Factory(factory).getVaultForCNode(); require(msg.sender == vaultForCNode, "CVaultForTrader: only vaultForCNode"); // caution // uint256 pending = pendingRewardsForCNode; emit ClearPendingRewardOfCNode(pendingRewardsForCNode); pendingRewardsForCNode = 0; // take all, set to 0 // ICoFiToken(cofiToken).mint(msg.sender, pending); // no need to mint from here, we can mint directly in valult } // vaultForLP should ensure passing the correct pair address function clearPendingRewardOfLP(address pair) external override nonReentrant { address vaultForLP = ICoFiXV2Factory(factory).getVaultForLP(); require(msg.sender == vaultForLP, "CVaultForTrader: only vaultForLP"); // caution emit ClearPendingRewardOfLP(pendingRewardsForLP[pair]); pendingRewardsForLP[pair] = 0; // take all, set to 0 // ICoFiToken(cofiToken).mint(to, pending); // no need to mint from here, we can mint directly in valult } function getPendingRewardOfCNode() external override view returns (uint256) { return pendingRewardsForCNode; } function getPendingRewardOfLP(address pair) external override view returns (uint256) { return pendingRewardsForLP[pair]; } }
All pairs: {ETH <-> ERC20 Token}
event Mint(address indexed sender, uint amount0, uint amount1);
356,128
[ 1, 1595, 5574, 30, 288, 1584, 44, 411, 2122, 4232, 39, 3462, 3155, 97, 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, 871, 490, 474, 12, 2867, 8808, 5793, 16, 2254, 3844, 20, 16, 2254, 3844, 21, 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 ]
/* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { AaveV2 } from "../integration/lib/AaveV2.sol"; import { IAToken } from "../../interfaces/external/aave-v2/IAToken.sol"; import { IController } from "../../interfaces/IController.sol"; import { IDebtIssuanceModule } from "../../interfaces/IDebtIssuanceModule.sol"; import { IExchangeAdapter } from "../../interfaces/IExchangeAdapter.sol"; import { ILendingPool } from "../../interfaces/external/aave-v2/ILendingPool.sol"; import { ILendingPoolAddressesProvider } from "../../interfaces/external/aave-v2/ILendingPoolAddressesProvider.sol"; import { IModuleIssuanceHook } from "../../interfaces/IModuleIssuanceHook.sol"; import { IProtocolDataProvider } from "../../interfaces/external/aave-v2/IProtocolDataProvider.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { IVariableDebtToken } from "../../interfaces/external/aave-v2/IVariableDebtToken.sol"; import { ModuleBase } from "../lib/ModuleBase.sol"; /** * @title AaveLeverageModule * @author Set Protocol * @notice Smart contract that enables leverage trading using Aave as the lending protocol. * @dev Do not use this module in conjunction with other debt modules that allow Aave debt positions as it could lead to double counting of * debt when borrowed assets are the same. */ contract AaveLeverageModule is ModuleBase, ReentrancyGuard, Ownable, IModuleIssuanceHook { using AaveV2 for ISetToken; /* ============ Structs ============ */ struct EnabledAssets { address[] collateralAssets; // Array of enabled underlying collateral assets for a SetToken address[] borrowAssets; // Array of enabled underlying borrow assets for a SetToken } struct ActionInfo { ISetToken setToken; // SetToken instance ILendingPool lendingPool; // Lending pool instance, we grab this everytime since it's best practice not to store IExchangeAdapter exchangeAdapter; // Exchange adapter instance uint256 setTotalSupply; // Total supply of SetToken uint256 notionalSendQuantity; // Total notional quantity sent to exchange uint256 minNotionalReceiveQuantity; // Min total notional received from exchange IERC20 collateralAsset; // Address of collateral asset IERC20 borrowAsset; // Address of borrow asset uint256 preTradeReceiveTokenBalance; // Balance of pre-trade receive token balance } struct ReserveTokens { IAToken aToken; // Reserve's aToken instance IVariableDebtToken variableDebtToken; // Reserve's variable debt token instance } /* ============ Events ============ */ /** * @dev Emitted on lever() * @param _setToken Instance of the SetToken being levered * @param _borrowAsset Asset being borrowed for leverage * @param _collateralAsset Collateral asset being levered * @param _exchangeAdapter Exchange adapter used for trading * @param _totalBorrowAmount Total amount of `_borrowAsset` borrowed * @param _totalReceiveAmount Total amount of `_collateralAsset` received by selling `_borrowAsset` * @param _protocolFee Protocol fee charged */ event LeverageIncreased( ISetToken indexed _setToken, IERC20 indexed _borrowAsset, IERC20 indexed _collateralAsset, IExchangeAdapter _exchangeAdapter, uint256 _totalBorrowAmount, uint256 _totalReceiveAmount, uint256 _protocolFee ); /** * @dev Emitted on delever() and deleverToZeroBorrowBalance() * @param _setToken Instance of the SetToken being delevered * @param _collateralAsset Asset sold to decrease leverage * @param _repayAsset Asset being bought to repay to Aave * @param _exchangeAdapter Exchange adapter used for trading * @param _totalRedeemAmount Total amount of `_collateralAsset` being sold * @param _totalRepayAmount Total amount of `_repayAsset` being repaid * @param _protocolFee Protocol fee charged */ event LeverageDecreased( ISetToken indexed _setToken, IERC20 indexed _collateralAsset, IERC20 indexed _repayAsset, IExchangeAdapter _exchangeAdapter, uint256 _totalRedeemAmount, uint256 _totalRepayAmount, uint256 _protocolFee ); /** * @dev Emitted on addCollateralAssets() and removeCollateralAssets() * @param _setToken Instance of SetToken whose collateral assets is updated * @param _added true if assets are added false if removed * @param _assets Array of collateral assets being added/removed */ event CollateralAssetsUpdated( ISetToken indexed _setToken, bool indexed _added, IERC20[] _assets ); /** * @dev Emitted on addBorrowAssets() and removeBorrowAssets() * @param _setToken Instance of SetToken whose borrow assets is updated * @param _added true if assets are added false if removed * @param _assets Array of borrow assets being added/removed */ event BorrowAssetsUpdated( ISetToken indexed _setToken, bool indexed _added, IERC20[] _assets ); /** * @dev Emitted when `underlyingToReserveTokensMappings` is updated * @param _underlying Address of the underlying asset * @param _aToken Updated aave reserve aToken * @param _variableDebtToken Updated aave reserve variable debt token */ event ReserveTokensUpdated( IERC20 indexed _underlying, IAToken indexed _aToken, IVariableDebtToken indexed _variableDebtToken ); /** * @dev Emitted on updateAllowedSetToken() * @param _setToken SetToken being whose allowance to initialize this module is being updated * @param _added true if added false if removed */ event SetTokenStatusUpdated( ISetToken indexed _setToken, bool indexed _added ); /** * @dev Emitted on updateAnySetAllowed() * @param _anySetAllowed true if any set is allowed to initialize this module, false otherwise */ event AnySetAllowedUpdated( bool indexed _anySetAllowed ); /* ============ Constants ============ */ // This module only supports borrowing in variable rate mode from Aave which is represented by 2 uint256 constant internal BORROW_RATE_MODE = 2; // String identifying the DebtIssuanceModule in the IntegrationRegistry. Note: Governance must add DefaultIssuanceModule as // the string as the integration name string constant internal DEFAULT_ISSUANCE_MODULE_NAME = "DefaultIssuanceModule"; // 0 index stores protocol fee % on the controller, charged in the _executeTrade function uint256 constant internal PROTOCOL_TRADE_FEE_INDEX = 0; /* ============ State Variables ============ */ // Mapping to efficiently fetch reserve token addresses. Tracking Aave reserve token addresses and updating them // upon requirement is more efficient than fetching them each time from Aave. // Note: For an underlying asset to be enabled as collateral/borrow asset on SetToken, it must be added to this mapping first. mapping(IERC20 => ReserveTokens) public underlyingToReserveTokens; // Used to fetch reserves and user data from AaveV2 IProtocolDataProvider public immutable protocolDataProvider; // Used to fetch lendingPool address. This contract is immutable and its address will never change. ILendingPoolAddressesProvider public immutable lendingPoolAddressesProvider; // Mapping to efficiently check if collateral asset is enabled in SetToken mapping(ISetToken => mapping(IERC20 => bool)) public collateralAssetEnabled; // Mapping to efficiently check if a borrow asset is enabled in SetToken mapping(ISetToken => mapping(IERC20 => bool)) public borrowAssetEnabled; // Internal mapping of enabled collateral and borrow tokens for syncing positions mapping(ISetToken => EnabledAssets) internal enabledAssets; // Mapping of SetToken to boolean indicating if SetToken is on allow list. Updateable by governance mapping(ISetToken => bool) public allowedSetTokens; // Boolean that returns if any SetToken can initialize this module. If false, then subject to allow list. Updateable by governance. bool public anySetAllowed; /* ============ Constructor ============ */ /** * @dev Instantiate addresses. Underlying to reserve tokens mapping is created. * @param _controller Address of controller contract * @param _lendingPoolAddressesProvider Address of Aave LendingPoolAddressProvider */ constructor( IController _controller, ILendingPoolAddressesProvider _lendingPoolAddressesProvider ) public ModuleBase(_controller) { lendingPoolAddressesProvider = _lendingPoolAddressesProvider; IProtocolDataProvider _protocolDataProvider = IProtocolDataProvider( // Use the raw input vs bytes32() conversion. This is to ensure the input is an uint and not a string. _lendingPoolAddressesProvider.getAddress(0x0100000000000000000000000000000000000000000000000000000000000000) ); protocolDataProvider = _protocolDataProvider; IProtocolDataProvider.TokenData[] memory reserveTokens = _protocolDataProvider.getAllReservesTokens(); for(uint256 i = 0; i < reserveTokens.length; i++) { (address aToken, , address variableDebtToken) = _protocolDataProvider.getReserveTokensAddresses(reserveTokens[i].tokenAddress); underlyingToReserveTokens[IERC20(reserveTokens[i].tokenAddress)] = ReserveTokens(IAToken(aToken), IVariableDebtToken(variableDebtToken)); } } /* ============ External Functions ============ */ /** * @dev MANAGER ONLY: Increases leverage for a given collateral position using an enabled borrow asset. * Borrows _borrowAsset from Aave. Performs a DEX trade, exchanging the _borrowAsset for _collateralAsset. * Deposits _collateralAsset to Aave and mints corresponding aToken. * Note: Both collateral and borrow assets need to be enabled, and they must not be the same asset. * @param _setToken Instance of the SetToken * @param _borrowAsset Address of underlying asset being borrowed for leverage * @param _collateralAsset Address of underlying collateral asset * @param _borrowQuantityUnits Borrow quantity of asset in position units * @param _minReceiveQuantityUnits Min receive quantity of collateral asset to receive post-trade in position units * @param _tradeAdapterName Name of trade adapter * @param _tradeData Arbitrary data for trade */ function lever( ISetToken _setToken, IERC20 _borrowAsset, IERC20 _collateralAsset, uint256 _borrowQuantityUnits, uint256 _minReceiveQuantityUnits, string memory _tradeAdapterName, bytes memory _tradeData ) external nonReentrant onlyManagerAndValidSet(_setToken) { // For levering up, send quantity is derived from borrow asset and receive quantity is derived from // collateral asset ActionInfo memory leverInfo = _createAndValidateActionInfo( _setToken, _borrowAsset, _collateralAsset, _borrowQuantityUnits, _minReceiveQuantityUnits, _tradeAdapterName, true ); _borrow(leverInfo.setToken, leverInfo.lendingPool, leverInfo.borrowAsset, leverInfo.notionalSendQuantity); uint256 postTradeReceiveQuantity = _executeTrade(leverInfo, _borrowAsset, _collateralAsset, _tradeData); uint256 protocolFee = _accrueProtocolFee(_setToken, _collateralAsset, postTradeReceiveQuantity); uint256 postTradeCollateralQuantity = postTradeReceiveQuantity.sub(protocolFee); _deposit(leverInfo.setToken, leverInfo.lendingPool, _collateralAsset, postTradeCollateralQuantity); _updateLeverPositions(leverInfo, _borrowAsset); emit LeverageIncreased( _setToken, _borrowAsset, _collateralAsset, leverInfo.exchangeAdapter, leverInfo.notionalSendQuantity, postTradeCollateralQuantity, protocolFee ); } /** * @dev MANAGER ONLY: Decrease leverage for a given collateral position using an enabled borrow asset. * Withdraws _collateralAsset from Aave. Performs a DEX trade, exchanging the _collateralAsset for _repayAsset. * Repays _repayAsset to Aave and burns corresponding debt tokens. * Note: Both collateral and borrow assets need to be enabled, and they must not be the same asset. * @param _setToken Instance of the SetToken * @param _collateralAsset Address of underlying collateral asset being withdrawn * @param _repayAsset Address of underlying borrowed asset being repaid * @param _redeemQuantityUnits Quantity of collateral asset to delever in position units * @param _minRepayQuantityUnits Minimum amount of repay asset to receive post trade in position units * @param _tradeAdapterName Name of trade adapter * @param _tradeData Arbitrary data for trade */ function delever( ISetToken _setToken, IERC20 _collateralAsset, IERC20 _repayAsset, uint256 _redeemQuantityUnits, uint256 _minRepayQuantityUnits, string memory _tradeAdapterName, bytes memory _tradeData ) external nonReentrant onlyManagerAndValidSet(_setToken) { // Note: for delevering, send quantity is derived from collateral asset and receive quantity is derived from // repay asset ActionInfo memory deleverInfo = _createAndValidateActionInfo( _setToken, _collateralAsset, _repayAsset, _redeemQuantityUnits, _minRepayQuantityUnits, _tradeAdapterName, false ); _withdraw(deleverInfo.setToken, deleverInfo.lendingPool, _collateralAsset, deleverInfo.notionalSendQuantity); uint256 postTradeReceiveQuantity = _executeTrade(deleverInfo, _collateralAsset, _repayAsset, _tradeData); uint256 protocolFee = _accrueProtocolFee(_setToken, _repayAsset, postTradeReceiveQuantity); uint256 repayQuantity = postTradeReceiveQuantity.sub(protocolFee); _repayBorrow(deleverInfo.setToken, deleverInfo.lendingPool, _repayAsset, repayQuantity); _updateDeleverPositions(deleverInfo, _repayAsset); emit LeverageDecreased( _setToken, _collateralAsset, _repayAsset, deleverInfo.exchangeAdapter, deleverInfo.notionalSendQuantity, repayQuantity, protocolFee ); } /** @dev MANAGER ONLY: Pays down the borrow asset to 0 selling off a given amount of collateral asset. * Withdraws _collateralAsset from Aave. Performs a DEX trade, exchanging the _collateralAsset for _repayAsset. * Minimum receive amount for the DEX trade is set to the current variable debt balance of the borrow asset. * Repays received _repayAsset to Aave which burns corresponding debt tokens. Any extra received borrow asset is . * updated as equity. No protocol fee is charged. * Note: Both collateral and borrow assets need to be enabled, and they must not be the same asset. * The function reverts if not enough collateral asset is redeemed to buy the required minimum amount of _repayAsset. * @param _setToken Instance of the SetToken * @param _collateralAsset Address of underlying collateral asset being redeemed * @param _repayAsset Address of underlying asset being repaid * @param _redeemQuantityUnits Quantity of collateral asset to delever in position units * @param _tradeAdapterName Name of trade adapter * @param _tradeData Arbitrary data for trade * @return uint256 Notional repay quantity */ function deleverToZeroBorrowBalance( ISetToken _setToken, IERC20 _collateralAsset, IERC20 _repayAsset, uint256 _redeemQuantityUnits, string memory _tradeAdapterName, bytes memory _tradeData ) external nonReentrant onlyManagerAndValidSet(_setToken) returns (uint256) { uint256 setTotalSupply = _setToken.totalSupply(); uint256 notionalRedeemQuantity = _redeemQuantityUnits.preciseMul(setTotalSupply); require(borrowAssetEnabled[_setToken][_repayAsset], "Borrow not enabled"); uint256 notionalRepayQuantity = underlyingToReserveTokens[_repayAsset].variableDebtToken.balanceOf(address(_setToken)); require(notionalRepayQuantity > 0, "Borrow balance is zero"); ActionInfo memory deleverInfo = _createAndValidateActionInfoNotional( _setToken, _collateralAsset, _repayAsset, notionalRedeemQuantity, notionalRepayQuantity, _tradeAdapterName, false, setTotalSupply ); _withdraw(deleverInfo.setToken, deleverInfo.lendingPool, _collateralAsset, deleverInfo.notionalSendQuantity); _executeTrade(deleverInfo, _collateralAsset, _repayAsset, _tradeData); _repayBorrow(deleverInfo.setToken, deleverInfo.lendingPool, _repayAsset, notionalRepayQuantity); _updateDeleverPositions(deleverInfo, _repayAsset); emit LeverageDecreased( _setToken, _collateralAsset, _repayAsset, deleverInfo.exchangeAdapter, deleverInfo.notionalSendQuantity, notionalRepayQuantity, 0 // No protocol fee ); return notionalRepayQuantity; } /** * @dev CALLABLE BY ANYBODY: Sync Set positions with ALL enabled Aave collateral and borrow positions. * For collateral assets, update aToken default position. For borrow assets, update external borrow position. * - Collateral assets may come out of sync when interest is accrued or a position is liquidated * - Borrow assets may come out of sync when interest is accrued or position is liquidated and borrow is repaid * Note: In Aave, both collateral and borrow interest is accrued in each block by increasing the balance of * aTokens and debtTokens for each user, and 1 aToken = 1 variableDebtToken = 1 underlying. * @param _setToken Instance of the SetToken */ function sync(ISetToken _setToken) public nonReentrant onlyValidAndInitializedSet(_setToken) { uint256 setTotalSupply = _setToken.totalSupply(); // Only sync positions when Set supply is not 0. Without this check, if sync is called by someone before the // first issuance, then editDefaultPosition would remove the default positions from the SetToken if (setTotalSupply > 0) { address[] memory collateralAssets = enabledAssets[_setToken].collateralAssets; for(uint256 i = 0; i < collateralAssets.length; i++) { IAToken aToken = underlyingToReserveTokens[IERC20(collateralAssets[i])].aToken; uint256 previousPositionUnit = _setToken.getDefaultPositionRealUnit(address(aToken)).toUint256(); uint256 newPositionUnit = _getCollateralPosition(_setToken, aToken, setTotalSupply); // Note: Accounts for if position does not exist on SetToken but is tracked in enabledAssets if (previousPositionUnit != newPositionUnit) { _updateCollateralPosition(_setToken, aToken, newPositionUnit); } } address[] memory borrowAssets = enabledAssets[_setToken].borrowAssets; for(uint256 i = 0; i < borrowAssets.length; i++) { IERC20 borrowAsset = IERC20(borrowAssets[i]); int256 previousPositionUnit = _setToken.getExternalPositionRealUnit(address(borrowAsset), address(this)); int256 newPositionUnit = _getBorrowPosition(_setToken, borrowAsset, setTotalSupply); // Note: Accounts for if position does not exist on SetToken but is tracked in enabledAssets if (newPositionUnit != previousPositionUnit) { _updateBorrowPosition(_setToken, borrowAsset, newPositionUnit); } } } } /** * @dev MANAGER ONLY: Initializes this module to the SetToken. Either the SetToken needs to be on the allowed list * or anySetAllowed needs to be true. Only callable by the SetToken's manager. * Note: Managers can enable collateral and borrow assets that don't exist as positions on the SetToken * @param _setToken Instance of the SetToken to initialize * @param _collateralAssets Underlying tokens to be enabled as collateral in the SetToken * @param _borrowAssets Underlying tokens to be enabled as borrow in the SetToken */ function initialize( ISetToken _setToken, IERC20[] memory _collateralAssets, IERC20[] memory _borrowAssets ) external onlySetManager(_setToken, msg.sender) onlyValidAndPendingSet(_setToken) { if (!anySetAllowed) { require(allowedSetTokens[_setToken], "Not allowed SetToken"); } // Initialize module before trying register _setToken.initializeModule(); // Get debt issuance module registered to this module and require that it is initialized require(_setToken.isInitializedModule(getAndValidateAdapter(DEFAULT_ISSUANCE_MODULE_NAME)), "Issuance not initialized"); // Try if register exists on any of the modules including the debt issuance module address[] memory modules = _setToken.getModules(); for(uint256 i = 0; i < modules.length; i++) { try IDebtIssuanceModule(modules[i]).registerToIssuanceModule(_setToken) {} catch {} } // _collateralAssets and _borrowAssets arrays are validated in their respective internal functions _addCollateralAssets(_setToken, _collateralAssets); _addBorrowAssets(_setToken, _borrowAssets); } /** * @dev MANAGER ONLY: Removes this module from the SetToken, via call by the SetToken. Any deposited collateral assets * are disabled to be used as collateral on Aave. Aave Settings and manager enabled assets state is deleted. * Note: Function will revert is there is any debt remaining on Aave */ function removeModule() external override onlyValidAndInitializedSet(ISetToken(msg.sender)) { ISetToken setToken = ISetToken(msg.sender); // Sync Aave and SetToken positions prior to any removal action sync(setToken); address[] memory borrowAssets = enabledAssets[setToken].borrowAssets; for(uint256 i = 0; i < borrowAssets.length; i++) { IERC20 borrowAsset = IERC20(borrowAssets[i]); require(underlyingToReserveTokens[borrowAsset].variableDebtToken.balanceOf(address(setToken)) == 0, "Variable debt remaining"); delete borrowAssetEnabled[setToken][borrowAsset]; } address[] memory collateralAssets = enabledAssets[setToken].collateralAssets; for(uint256 i = 0; i < collateralAssets.length; i++) { IERC20 collateralAsset = IERC20(collateralAssets[i]); _updateUseReserveAsCollateral(setToken, collateralAsset, false); delete collateralAssetEnabled[setToken][collateralAsset]; } delete enabledAssets[setToken]; // Try if unregister exists on any of the modules address[] memory modules = setToken.getModules(); for(uint256 i = 0; i < modules.length; i++) { try IDebtIssuanceModule(modules[i]).unregisterFromIssuanceModule(setToken) {} catch {} } } /** * @dev MANAGER ONLY: Add registration of this module on the debt issuance module for the SetToken. * Note: if the debt issuance module is not added to SetToken before this module is initialized, then this function * needs to be called if the debt issuance module is later added and initialized to prevent state inconsistencies * @param _setToken Instance of the SetToken * @param _debtIssuanceModule Debt issuance module address to register */ function registerToModule(ISetToken _setToken, IDebtIssuanceModule _debtIssuanceModule) external onlyManagerAndValidSet(_setToken) { require(_setToken.isInitializedModule(address(_debtIssuanceModule)), "Issuance not initialized"); _debtIssuanceModule.registerToIssuanceModule(_setToken); } /** * @dev CALLABLE BY ANYBODY: Updates `underlyingToReserveTokens` mappings. Reverts if mapping already exists * or the passed _underlying asset does not have a valid reserve on Aave. * Note: Call this function when Aave adds a new reserve. * @param _underlying Address of underlying asset */ function addUnderlyingToReserveTokensMapping(IERC20 _underlying) external { require(address(underlyingToReserveTokens[_underlying].aToken) == address(0), "Mapping already exists"); // An active reserve is an alias for a valid reserve on Aave. (,,,,,,,, bool isActive,) = protocolDataProvider.getReserveConfigurationData(address(_underlying)); require(isActive, "Invalid aave reserve"); _addUnderlyingToReserveTokensMapping(_underlying); } /** * @dev MANAGER ONLY: Add collateral assets. aTokens corresponding to collateral assets are tracked for syncing positions. * Note: Reverts with "Collateral already enabled" if there are duplicate assets in the passed _newCollateralAssets array. * * NOTE: ALL ADDED COLLATERAL ASSETS CAN BE ADDED AS A POSITION ON THE SET TOKEN WITHOUT MANAGER'S EXPLICIT PERMISSION. * UNWANTED EXTRA POSITIONS CAN BREAK EXTERNAL LOGIC, INCREASE COST OF MINT/REDEEM OF SET TOKEN, AMONG OTHER POTENTIAL UNINTENDED CONSEQUENCES. * SO, PLEASE ADD ONLY THOSE COLLATERAL ASSETS WHOSE CORRESPONDING aTOKENS ARE NEEDED AS DEFAULT POSITIONS ON THE SET TOKEN. * * @param _setToken Instance of the SetToken * @param _newCollateralAssets Addresses of new collateral underlying assets */ function addCollateralAssets(ISetToken _setToken, IERC20[] memory _newCollateralAssets) external onlyManagerAndValidSet(_setToken) { _addCollateralAssets(_setToken, _newCollateralAssets); } /** * @dev MANAGER ONLY: Remove collateral assets. Disable deposited assets to be used as collateral on Aave market. * @param _setToken Instance of the SetToken * @param _collateralAssets Addresses of collateral underlying assets to remove */ function removeCollateralAssets(ISetToken _setToken, IERC20[] memory _collateralAssets) external onlyManagerAndValidSet(_setToken) { for(uint256 i = 0; i < _collateralAssets.length; i++) { IERC20 collateralAsset = _collateralAssets[i]; require(collateralAssetEnabled[_setToken][collateralAsset], "Collateral not enabled"); _updateUseReserveAsCollateral(_setToken, collateralAsset, false); delete collateralAssetEnabled[_setToken][collateralAsset]; enabledAssets[_setToken].collateralAssets.removeStorage(address(collateralAsset)); } emit CollateralAssetsUpdated(_setToken, false, _collateralAssets); } /** * @dev MANAGER ONLY: Add borrow assets. Debt tokens corresponding to borrow assets are tracked for syncing positions. * Note: Reverts with "Borrow already enabled" if there are duplicate assets in the passed _newBorrowAssets array. * @param _setToken Instance of the SetToken * @param _newBorrowAssets Addresses of borrow underlying assets to add */ function addBorrowAssets(ISetToken _setToken, IERC20[] memory _newBorrowAssets) external onlyManagerAndValidSet(_setToken) { _addBorrowAssets(_setToken, _newBorrowAssets); } /** * @dev MANAGER ONLY: Remove borrow assets. * Note: If there is a borrow balance, borrow asset cannot be removed * @param _setToken Instance of the SetToken * @param _borrowAssets Addresses of borrow underlying assets to remove */ function removeBorrowAssets(ISetToken _setToken, IERC20[] memory _borrowAssets) external onlyManagerAndValidSet(_setToken) { for(uint256 i = 0; i < _borrowAssets.length; i++) { IERC20 borrowAsset = _borrowAssets[i]; require(borrowAssetEnabled[_setToken][borrowAsset], "Borrow not enabled"); require(underlyingToReserveTokens[borrowAsset].variableDebtToken.balanceOf(address(_setToken)) == 0, "Variable debt remaining"); delete borrowAssetEnabled[_setToken][borrowAsset]; enabledAssets[_setToken].borrowAssets.removeStorage(address(borrowAsset)); } emit BorrowAssetsUpdated(_setToken, false, _borrowAssets); } /** * @dev GOVERNANCE ONLY: Enable/disable ability of a SetToken to initialize this module. Only callable by governance. * @param _setToken Instance of the SetToken * @param _status Bool indicating if _setToken is allowed to initialize this module */ function updateAllowedSetToken(ISetToken _setToken, bool _status) external onlyOwner { require(controller.isSet(address(_setToken)) || allowedSetTokens[_setToken], "Invalid SetToken"); allowedSetTokens[_setToken] = _status; emit SetTokenStatusUpdated(_setToken, _status); } /** * @dev GOVERNANCE ONLY: Toggle whether ANY SetToken is allowed to initialize this module. Only callable by governance. * @param _anySetAllowed Bool indicating if ANY SetToken is allowed to initialize this module */ function updateAnySetAllowed(bool _anySetAllowed) external onlyOwner { anySetAllowed = _anySetAllowed; emit AnySetAllowedUpdated(_anySetAllowed); } /** * @dev MODULE ONLY: Hook called prior to issuance to sync positions on SetToken. Only callable by valid module. * @param _setToken Instance of the SetToken */ function moduleIssueHook(ISetToken _setToken, uint256 /* _setTokenQuantity */) external override onlyModule(_setToken) { sync(_setToken); } /** * @dev MODULE ONLY: Hook called prior to redemption to sync positions on SetToken. For redemption, always use current borrowed * balance after interest accrual. Only callable by valid module. * @param _setToken Instance of the SetToken */ function moduleRedeemHook(ISetToken _setToken, uint256 /* _setTokenQuantity */) external override onlyModule(_setToken) { sync(_setToken); } /** * @dev MODULE ONLY: Hook called prior to looping through each component on issuance. Invokes borrow in order for * module to return debt to issuer. Only callable by valid module. * @param _setToken Instance of the SetToken * @param _setTokenQuantity Quantity of SetToken * @param _component Address of component */ function componentIssueHook(ISetToken _setToken, uint256 _setTokenQuantity, IERC20 _component, bool _isEquity) external override onlyModule(_setToken) { // Check hook not being called for an equity position. If hook is called with equity position and outstanding borrow position // exists the loan would be taken out twice potentially leading to liquidation if (!_isEquity) { int256 componentDebt = _setToken.getExternalPositionRealUnit(address(_component), address(this)); require(componentDebt < 0, "Component must be negative"); uint256 notionalDebt = componentDebt.mul(-1).toUint256().preciseMul(_setTokenQuantity); _borrowForHook(_setToken, _component, notionalDebt); } } /** * @dev MODULE ONLY: Hook called prior to looping through each component on redemption. Invokes repay after * the issuance module transfers debt from the issuer. Only callable by valid module. * @param _setToken Instance of the SetToken * @param _setTokenQuantity Quantity of SetToken * @param _component Address of component */ function componentRedeemHook(ISetToken _setToken, uint256 _setTokenQuantity, IERC20 _component, bool _isEquity) external override onlyModule(_setToken) { // Check hook not being called for an equity position. If hook is called with equity position and outstanding borrow position // exists the loan would be paid down twice, decollateralizing the Set if (!_isEquity) { int256 componentDebt = _setToken.getExternalPositionRealUnit(address(_component), address(this)); require(componentDebt < 0, "Component must be negative"); uint256 notionalDebt = componentDebt.mul(-1).toUint256().preciseMulCeil(_setTokenQuantity); _repayBorrowForHook(_setToken, _component, notionalDebt); } } /* ============ External Getter Functions ============ */ /** * @dev Get enabled assets for SetToken. Returns an array of collateral and borrow assets. * @return Underlying collateral assets that are enabled * @return Underlying borrowed assets that are enabled */ function getEnabledAssets(ISetToken _setToken) external view returns(address[] memory, address[] memory) { return ( enabledAssets[_setToken].collateralAssets, enabledAssets[_setToken].borrowAssets ); } /* ============ Internal Functions ============ */ /** * @dev Invoke deposit from SetToken using AaveV2 library. Mints aTokens for SetToken. */ function _deposit(ISetToken _setToken, ILendingPool _lendingPool, IERC20 _asset, uint256 _notionalQuantity) internal { _setToken.invokeApprove(address(_asset), address(_lendingPool), _notionalQuantity); _setToken.invokeDeposit(_lendingPool, address(_asset), _notionalQuantity); } /** * @dev Invoke withdraw from SetToken using AaveV2 library. Burns aTokens and returns underlying to SetToken. */ function _withdraw(ISetToken _setToken, ILendingPool _lendingPool, IERC20 _asset, uint256 _notionalQuantity) internal { _setToken.invokeWithdraw(_lendingPool, address(_asset), _notionalQuantity); } /** * @dev Invoke repay from SetToken using AaveV2 library. Burns DebtTokens for SetToken. */ function _repayBorrow(ISetToken _setToken, ILendingPool _lendingPool, IERC20 _asset, uint256 _notionalQuantity) internal { _setToken.invokeApprove(address(_asset), address(_lendingPool), _notionalQuantity); _setToken.invokeRepay(_lendingPool, address(_asset), _notionalQuantity, BORROW_RATE_MODE); } /** * @dev Invoke borrow from the SetToken during issuance hook. Since we only need to interact with AAVE once we fetch the * lending pool in this function to optimize vs forcing a fetch twice during lever/delever. */ function _repayBorrowForHook(ISetToken _setToken, IERC20 _asset, uint256 _notionalQuantity) internal { _repayBorrow(_setToken, ILendingPool(lendingPoolAddressesProvider.getLendingPool()), _asset, _notionalQuantity); } /** * @dev Invoke borrow from the SetToken using AaveV2 library. Mints DebtTokens for SetToken. */ function _borrow(ISetToken _setToken, ILendingPool _lendingPool, IERC20 _asset, uint256 _notionalQuantity) internal { _setToken.invokeBorrow(_lendingPool, address(_asset), _notionalQuantity, BORROW_RATE_MODE); } /** * @dev Invoke borrow from the SetToken during issuance hook. Since we only need to interact with AAVE once we fetch the * lending pool in this function to optimize vs forcing a fetch twice during lever/delever. */ function _borrowForHook(ISetToken _setToken, IERC20 _asset, uint256 _notionalQuantity) internal { _borrow(_setToken, ILendingPool(lendingPoolAddressesProvider.getLendingPool()), _asset, _notionalQuantity); } /** * @dev Invokes approvals, gets trade call data from exchange adapter and invokes trade from SetToken * @return uint256 The quantity of tokens received post-trade */ function _executeTrade( ActionInfo memory _actionInfo, IERC20 _sendToken, IERC20 _receiveToken, bytes memory _data ) internal returns (uint256) { ISetToken setToken = _actionInfo.setToken; uint256 notionalSendQuantity = _actionInfo.notionalSendQuantity; setToken.invokeApprove( address(_sendToken), _actionInfo.exchangeAdapter.getSpender(), notionalSendQuantity ); ( address targetExchange, uint256 callValue, bytes memory methodData ) = _actionInfo.exchangeAdapter.getTradeCalldata( address(_sendToken), address(_receiveToken), address(setToken), notionalSendQuantity, _actionInfo.minNotionalReceiveQuantity, _data ); setToken.invoke(targetExchange, callValue, methodData); uint256 receiveTokenQuantity = _receiveToken.balanceOf(address(setToken)).sub(_actionInfo.preTradeReceiveTokenBalance); require( receiveTokenQuantity >= _actionInfo.minNotionalReceiveQuantity, "Slippage too high" ); return receiveTokenQuantity; } /** * @dev Calculates protocol fee on module and pays protocol fee from SetToken * @return uint256 Total protocol fee paid */ function _accrueProtocolFee(ISetToken _setToken, IERC20 _receiveToken, uint256 _exchangedQuantity) internal returns(uint256) { uint256 protocolFeeTotal = getModuleFee(PROTOCOL_TRADE_FEE_INDEX, _exchangedQuantity); payProtocolFeeFromSetToken(_setToken, address(_receiveToken), protocolFeeTotal); return protocolFeeTotal; } /** * @dev Updates the collateral (aToken held) and borrow position (variableDebtToken held) of the SetToken */ function _updateLeverPositions(ActionInfo memory _actionInfo, IERC20 _borrowAsset) internal { IAToken aToken = underlyingToReserveTokens[_actionInfo.collateralAsset].aToken; _updateCollateralPosition( _actionInfo.setToken, aToken, _getCollateralPosition( _actionInfo.setToken, aToken, _actionInfo.setTotalSupply ) ); _updateBorrowPosition( _actionInfo.setToken, _borrowAsset, _getBorrowPosition( _actionInfo.setToken, _borrowAsset, _actionInfo.setTotalSupply ) ); } /** * @dev Updates positions as per _updateLeverPositions and updates Default position for borrow asset in case Set is * delevered all the way to zero any remaining borrow asset after the debt is paid can be added as a position. */ function _updateDeleverPositions(ActionInfo memory _actionInfo, IERC20 _repayAsset) internal { // if amount of tokens traded for exceeds debt, update default position first to save gas on editing borrow position uint256 repayAssetBalance = _repayAsset.balanceOf(address(_actionInfo.setToken)); if (repayAssetBalance != _actionInfo.preTradeReceiveTokenBalance) { _actionInfo.setToken.calculateAndEditDefaultPosition( address(_repayAsset), _actionInfo.setTotalSupply, _actionInfo.preTradeReceiveTokenBalance ); } _updateLeverPositions(_actionInfo, _repayAsset); } /** * @dev Updates default position unit for given aToken on SetToken */ function _updateCollateralPosition(ISetToken _setToken, IAToken _aToken, uint256 _newPositionUnit) internal { _setToken.editDefaultPosition(address(_aToken), _newPositionUnit); } /** * @dev Updates external position unit for given borrow asset on SetToken */ function _updateBorrowPosition(ISetToken _setToken, IERC20 _underlyingAsset, int256 _newPositionUnit) internal { _setToken.editExternalPosition(address(_underlyingAsset), address(this), _newPositionUnit, ""); } /** * @dev Construct the ActionInfo struct for lever and delever * @return ActionInfo Instance of constructed ActionInfo struct */ function _createAndValidateActionInfo( ISetToken _setToken, IERC20 _sendToken, IERC20 _receiveToken, uint256 _sendQuantityUnits, uint256 _minReceiveQuantityUnits, string memory _tradeAdapterName, bool _isLever ) internal view returns(ActionInfo memory) { uint256 totalSupply = _setToken.totalSupply(); return _createAndValidateActionInfoNotional( _setToken, _sendToken, _receiveToken, _sendQuantityUnits.preciseMul(totalSupply), _minReceiveQuantityUnits.preciseMul(totalSupply), _tradeAdapterName, _isLever, totalSupply ); } /** * @dev Construct the ActionInfo struct for lever and delever accepting notional units * @return ActionInfo Instance of constructed ActionInfo struct */ function _createAndValidateActionInfoNotional( ISetToken _setToken, IERC20 _sendToken, IERC20 _receiveToken, uint256 _notionalSendQuantity, uint256 _minNotionalReceiveQuantity, string memory _tradeAdapterName, bool _isLever, uint256 _setTotalSupply ) internal view returns(ActionInfo memory) { ActionInfo memory actionInfo = ActionInfo ({ exchangeAdapter: IExchangeAdapter(getAndValidateAdapter(_tradeAdapterName)), lendingPool: ILendingPool(lendingPoolAddressesProvider.getLendingPool()), setToken: _setToken, collateralAsset: _isLever ? _receiveToken : _sendToken, borrowAsset: _isLever ? _sendToken : _receiveToken, setTotalSupply: _setTotalSupply, notionalSendQuantity: _notionalSendQuantity, minNotionalReceiveQuantity: _minNotionalReceiveQuantity, preTradeReceiveTokenBalance: IERC20(_receiveToken).balanceOf(address(_setToken)) }); _validateCommon(actionInfo); return actionInfo; } /** * @dev Updates `underlyingToReserveTokens` mappings for given `_underlying` asset. Emits ReserveTokensUpdated event. */ function _addUnderlyingToReserveTokensMapping(IERC20 _underlying) internal { (address aToken, , address variableDebtToken) = protocolDataProvider.getReserveTokensAddresses(address(_underlying)); underlyingToReserveTokens[_underlying].aToken = IAToken(aToken); underlyingToReserveTokens[_underlying].variableDebtToken = IVariableDebtToken(variableDebtToken); emit ReserveTokensUpdated(_underlying, IAToken(aToken), IVariableDebtToken(variableDebtToken)); } /** * @dev Add collateral assets to SetToken. Updates the collateralAssetsEnabled and enabledAssets mappings. * Emits CollateralAssetsUpdated event. */ function _addCollateralAssets(ISetToken _setToken, IERC20[] memory _newCollateralAssets) internal { for(uint256 i = 0; i < _newCollateralAssets.length; i++) { IERC20 collateralAsset = _newCollateralAssets[i]; _validateNewCollateralAsset(_setToken, collateralAsset); _updateUseReserveAsCollateral(_setToken, collateralAsset, true); collateralAssetEnabled[_setToken][collateralAsset] = true; enabledAssets[_setToken].collateralAssets.push(address(collateralAsset)); } emit CollateralAssetsUpdated(_setToken, true, _newCollateralAssets); } /** * @dev Add borrow assets to SetToken. Updates the borrowAssetsEnabled and enabledAssets mappings. * Emits BorrowAssetsUpdated event. */ function _addBorrowAssets(ISetToken _setToken, IERC20[] memory _newBorrowAssets) internal { for(uint256 i = 0; i < _newBorrowAssets.length; i++) { IERC20 borrowAsset = _newBorrowAssets[i]; _validateNewBorrowAsset(_setToken, borrowAsset); borrowAssetEnabled[_setToken][borrowAsset] = true; enabledAssets[_setToken].borrowAssets.push(address(borrowAsset)); } emit BorrowAssetsUpdated(_setToken, true, _newBorrowAssets); } /** * @dev Updates SetToken's ability to use an asset as collateral on Aave */ function _updateUseReserveAsCollateral(ISetToken _setToken, IERC20 _asset, bool _useAsCollateral) internal { /* Note: Aave ENABLES an asset to be used as collateral by `to` address in an `aToken.transfer(to, amount)` call provided 1. msg.sender (from address) isn't the same as `to` address 2. `to` address had zero aToken balance before the transfer 3. transfer `amount` is greater than 0 Note: Aave DISABLES an asset to be used as collateral by `msg.sender`in an `aToken.transfer(to, amount)` call provided 1. msg.sender (from address) isn't the same as `to` address 2. msg.sender has zero balance after the transfer Different states of the SetToken and what this function does in those states: Case 1: Manager adds collateral asset to SetToken before first issuance - Since aToken.balanceOf(setToken) == 0, we do not call `setToken.invokeUserUseReserveAsCollateral` because Aave requires aToken balance to be greater than 0 before enabling/disabling the underlying asset to be used as collateral on Aave markets. Case 2: First issuance of the SetToken - SetToken was initialized with aToken as default position - DebtIssuanceModule reads the default position and transfers corresponding aToken from the issuer to the SetToken - Aave enables aToken to be used as collateral by the SetToken - Manager calls lever() and the aToken is used as collateral to borrow other assets Case 3: Manager removes collateral asset from the SetToken - Disable asset to be used as collateral on SetToken by calling `setToken.invokeSetUserUseReserveAsCollateral` with useAsCollateral equals false - Note: If health factor goes below 1 by removing the collateral asset, then Aave reverts on the above call, thus whole transaction reverts, and manager can't remove corresponding collateral asset Case 4: Manager adds collateral asset after removing it - If aToken.balanceOf(setToken) > 0, we call `setToken.invokeUserUseReserveAsCollateral` and the corresponding aToken is re-enabled as collateral on Aave Case 5: On redemption/delever/liquidated and aToken balance becomes zero - Aave disables aToken to be used as collateral by SetToken Values of variables in below if condition and corresponding action taken: --------------------------------------------------------------------------------------------------------------------- | usageAsCollateralEnabled | _useAsCollateral | aToken.balanceOf() | Action | |--------------------------|-------------------|-----------------------|--------------------------------------------| | true | true | X | Skip invoke. Save gas. | |--------------------------|-------------------|-----------------------|--------------------------------------------| | true | false | greater than 0 | Invoke and set to false. | |--------------------------|-------------------|-----------------------|--------------------------------------------| | true | false | = 0 | Impossible case. Aave disables usage as | | | | | collateral when aToken balance becomes 0 | |--------------------------|-------------------|-----------------------|--------------------------------------------| | false | false | X | Skip invoke. Save gas. | |--------------------------|-------------------|-----------------------|--------------------------------------------| | false | true | greater than 0 | Invoke and set to true. | |--------------------------|-------------------|-----------------------|--------------------------------------------| | false | true | = 0 | Don't invoke. Will revert. | --------------------------------------------------------------------------------------------------------------------- */ (,,,,,,,,bool usageAsCollateralEnabled) = protocolDataProvider.getUserReserveData(address(_asset), address(_setToken)); if ( usageAsCollateralEnabled != _useAsCollateral && underlyingToReserveTokens[_asset].aToken.balanceOf(address(_setToken)) > 0 ) { _setToken.invokeSetUserUseReserveAsCollateral( ILendingPool(lendingPoolAddressesProvider.getLendingPool()), address(_asset), _useAsCollateral ); } } /** * @dev Validate common requirements for lever and delever */ function _validateCommon(ActionInfo memory _actionInfo) internal view { require(collateralAssetEnabled[_actionInfo.setToken][_actionInfo.collateralAsset], "Collateral not enabled"); require(borrowAssetEnabled[_actionInfo.setToken][_actionInfo.borrowAsset], "Borrow not enabled"); require(_actionInfo.collateralAsset != _actionInfo.borrowAsset, "Collateral and borrow asset must be different"); require(_actionInfo.notionalSendQuantity > 0, "Quantity is 0"); } /** * @dev Validates if a new asset can be added as collateral asset for given SetToken */ function _validateNewCollateralAsset(ISetToken _setToken, IERC20 _asset) internal view { require(!collateralAssetEnabled[_setToken][_asset], "Collateral already enabled"); (address aToken, , ) = protocolDataProvider.getReserveTokensAddresses(address(_asset)); require(address(underlyingToReserveTokens[_asset].aToken) == aToken, "Invalid aToken address"); ( , , , , , bool usageAsCollateralEnabled, , , bool isActive, bool isFrozen) = protocolDataProvider.getReserveConfigurationData(address(_asset)); // An active reserve is an alias for a valid reserve on Aave. // We are checking for the availability of the reserve directly on Aave rather than checking our internal `underlyingToReserveTokens` mappings, // because our mappings can be out-of-date if a new reserve is added to Aave require(isActive, "Invalid aave reserve"); // A frozen reserve doesn't allow any new deposit, borrow or rate swap but allows repayments, liquidations and withdrawals require(!isFrozen, "Frozen aave reserve"); require(usageAsCollateralEnabled, "Collateral disabled on Aave"); } /** * @dev Validates if a new asset can be added as borrow asset for given SetToken */ function _validateNewBorrowAsset(ISetToken _setToken, IERC20 _asset) internal view { require(!borrowAssetEnabled[_setToken][_asset], "Borrow already enabled"); ( , , address variableDebtToken) = protocolDataProvider.getReserveTokensAddresses(address(_asset)); require(address(underlyingToReserveTokens[_asset].variableDebtToken) == variableDebtToken, "Invalid variable debt token address"); (, , , , , , bool borrowingEnabled, , bool isActive, bool isFrozen) = protocolDataProvider.getReserveConfigurationData(address(_asset)); require(isActive, "Invalid aave reserve"); require(!isFrozen, "Frozen aave reserve"); require(borrowingEnabled, "Borrowing disabled on Aave"); } /** * @dev Reads aToken balance and calculates default position unit for given collateral aToken and SetToken * * @return uint256 default collateral position unit */ function _getCollateralPosition(ISetToken _setToken, IAToken _aToken, uint256 _setTotalSupply) internal view returns (uint256) { uint256 collateralNotionalBalance = _aToken.balanceOf(address(_setToken)); return collateralNotionalBalance.preciseDiv(_setTotalSupply); } /** * @dev Reads variableDebtToken balance and calculates external position unit for given borrow asset and SetToken * * @return int256 external borrow position unit */ function _getBorrowPosition(ISetToken _setToken, IERC20 _borrowAsset, uint256 _setTotalSupply) internal view returns (int256) { uint256 borrowNotionalBalance = underlyingToReserveTokens[_borrowAsset].variableDebtToken.balanceOf(address(_setToken)); return borrowNotionalBalance.preciseDivCeil(_setTotalSupply).toInt256().mul(-1); } } // 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 "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ 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 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; } } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { ILendingPool } from "../../../interfaces/external/aave-v2/ILendingPool.sol"; import { ISetToken } from "../../../interfaces/ISetToken.sol"; /** * @title AaveV2 * @author Set Protocol * * Collection of helper functions for interacting with AaveV2 integrations. */ library AaveV2 { /* ============ External ============ */ /** * Get deposit calldata from SetToken * * Deposits an `_amountNotional` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset to deposit * @param _amountNotional 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 * * @return address Target contract address * @return uint256 Call value * @return bytes Deposit calldata */ function getDepositCalldata( ILendingPool _lendingPool, address _asset, uint256 _amountNotional, address _onBehalfOf, uint16 _referralCode ) public pure returns (address, uint256, bytes memory) { bytes memory callData = abi.encodeWithSignature( "deposit(address,uint256,address,uint16)", _asset, _amountNotional, _onBehalfOf, _referralCode ); return (address(_lendingPool), 0, callData); } /** * Invoke deposit on LendingPool from SetToken * * Deposits an `_amountNotional` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. SetToken deposits 100 USDC and gets in return 100 aUSDC * @param _setToken Address of the SetToken * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset to deposit * @param _amountNotional The amount to be deposited */ function invokeDeposit( ISetToken _setToken, ILendingPool _lendingPool, address _asset, uint256 _amountNotional ) external { ( , , bytes memory depositCalldata) = getDepositCalldata( _lendingPool, _asset, _amountNotional, address(_setToken), 0 ); _setToken.invoke(address(_lendingPool), 0, depositCalldata); } /** * Get withdraw calldata from SetToken * * Withdraws an `_amountNotional` 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 _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset to withdraw * @param _amountNotional The underlying amount to be withdrawn * Note: Passing type(uint256).max will withdraw the entire aToken balance * @param _receiver 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 address Target contract address * @return uint256 Call value * @return bytes Withdraw calldata */ function getWithdrawCalldata( ILendingPool _lendingPool, address _asset, uint256 _amountNotional, address _receiver ) public pure returns (address, uint256, bytes memory) { bytes memory callData = abi.encodeWithSignature( "withdraw(address,uint256,address)", _asset, _amountNotional, _receiver ); return (address(_lendingPool), 0, callData); } /** * Invoke withdraw on LendingPool from SetToken * * Withdraws an `_amountNotional` of underlying asset from the reserve, burning the equivalent aTokens owned * - E.g. SetToken has 100 aUSDC, and receives 100 USDC, burning the 100 aUSDC * * @param _setToken Address of the SetToken * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset to withdraw * @param _amountNotional The underlying amount to be withdrawn * Note: Passing type(uint256).max will withdraw the entire aToken balance * * @return uint256 The final amount withdrawn */ function invokeWithdraw( ISetToken _setToken, ILendingPool _lendingPool, address _asset, uint256 _amountNotional ) external returns (uint256) { ( , , bytes memory withdrawCalldata) = getWithdrawCalldata( _lendingPool, _asset, _amountNotional, address(_setToken) ); return abi.decode(_setToken.invoke(address(_lendingPool), 0, withdrawCalldata), (uint256)); } /** * Get borrow calldata from SetToken * * Allows users to borrow a specific `_amountNotional` 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) * * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset to borrow * @param _amountNotional 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 * * @return address Target contract address * @return uint256 Call value * @return bytes Borrow calldata */ function getBorrowCalldata( ILendingPool _lendingPool, address _asset, uint256 _amountNotional, uint256 _interestRateMode, uint16 _referralCode, address _onBehalfOf ) public pure returns (address, uint256, bytes memory) { bytes memory callData = abi.encodeWithSignature( "borrow(address,uint256,uint256,uint16,address)", _asset, _amountNotional, _interestRateMode, _referralCode, _onBehalfOf ); return (address(_lendingPool), 0, callData); } /** * Invoke borrow on LendingPool from SetToken * * Allows SetToken to borrow a specific `_amountNotional` of the reserve underlying `_asset`, provided that * the SetToken already deposited enough collateral, or it was given enough allowance by a credit delegator * on the corresponding debt token (StableDebtToken or VariableDebtToken) * @param _setToken Address of the SetToken * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset to borrow * @param _amountNotional The amount to be borrowed * @param _interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable */ function invokeBorrow( ISetToken _setToken, ILendingPool _lendingPool, address _asset, uint256 _amountNotional, uint256 _interestRateMode ) external { ( , , bytes memory borrowCalldata) = getBorrowCalldata( _lendingPool, _asset, _amountNotional, _interestRateMode, 0, address(_setToken) ); _setToken.invoke(address(_lendingPool), 0, borrowCalldata); } /** * Get repay calldata from SetToken * * Repays a borrowed `_amountNotional` on a specific `_asset` reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the borrowed underlying asset previously borrowed * @param _amountNotional The amount to repay * Note: Passing type(uint256).max will repay the whole debt for `_asset` on the specific `_interestRateMode` * @param _interestRateMode 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 address Target contract address * @return uint256 Call value * @return bytes Repay calldata */ function getRepayCalldata( ILendingPool _lendingPool, address _asset, uint256 _amountNotional, uint256 _interestRateMode, address _onBehalfOf ) public pure returns (address, uint256, bytes memory) { bytes memory callData = abi.encodeWithSignature( "repay(address,uint256,uint256,address)", _asset, _amountNotional, _interestRateMode, _onBehalfOf ); return (address(_lendingPool), 0, callData); } /** * Invoke repay on LendingPool from SetToken * * Repays a borrowed `_amountNotional` on a specific `_asset` reserve, burning the equivalent debt tokens owned * - E.g. SetToken repays 100 USDC, burning 100 variable/stable debt tokens * @param _setToken Address of the SetToken * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the borrowed underlying asset previously borrowed * @param _amountNotional The amount to repay * Note: Passing type(uint256).max will repay the whole debt for `_asset` on the specific `_interestRateMode` * @param _interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * * @return uint256 The final amount repaid */ function invokeRepay( ISetToken _setToken, ILendingPool _lendingPool, address _asset, uint256 _amountNotional, uint256 _interestRateMode ) external returns (uint256) { ( , , bytes memory repayCalldata) = getRepayCalldata( _lendingPool, _asset, _amountNotional, _interestRateMode, address(_setToken) ); return abi.decode(_setToken.invoke(address(_lendingPool), 0, repayCalldata), (uint256)); } /** * Get setUserUseReserveAsCollateral calldata from SetToken * * Allows borrower to enable/disable a specific deposited asset as collateral * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset deposited * @param _useAsCollateral true` if the user wants to use the deposit as collateral, `false` otherwise * * @return address Target contract address * @return uint256 Call value * @return bytes SetUserUseReserveAsCollateral calldata */ function getSetUserUseReserveAsCollateralCalldata( ILendingPool _lendingPool, address _asset, bool _useAsCollateral ) public pure returns (address, uint256, bytes memory) { bytes memory callData = abi.encodeWithSignature( "setUserUseReserveAsCollateral(address,bool)", _asset, _useAsCollateral ); return (address(_lendingPool), 0, callData); } /** * Invoke an asset to be used as collateral on Aave from SetToken * * Allows SetToken to enable/disable a specific deposited asset as collateral * @param _setToken Address of the SetToken * @param _lendingPool Address of the LendingPool contract * @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 invokeSetUserUseReserveAsCollateral( ISetToken _setToken, ILendingPool _lendingPool, address _asset, bool _useAsCollateral ) external { ( , , bytes memory callData) = getSetUserUseReserveAsCollateralCalldata( _lendingPool, _asset, _useAsCollateral ); _setToken.invoke(address(_lendingPool), 0, callData); } /** * Get swapBorrowRate calldata from SetToken * * Allows a borrower to toggle his debt between stable and variable mode * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset borrowed * @param _rateMode The rate mode that the user wants to swap to * * @return address Target contract address * @return uint256 Call value * @return bytes SwapBorrowRate calldata */ function getSwapBorrowRateModeCalldata( ILendingPool _lendingPool, address _asset, uint256 _rateMode ) public pure returns (address, uint256, bytes memory) { bytes memory callData = abi.encodeWithSignature( "swapBorrowRateMode(address,uint256)", _asset, _rateMode ); return (address(_lendingPool), 0, callData); } /** * Invoke to swap borrow rate of SetToken * * Allows SetToken to toggle it's debt between stable and variable mode * @param _setToken Address of the SetToken * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset borrowed * @param _rateMode The rate mode that the user wants to swap to */ function invokeSwapBorrowRateMode( ISetToken _setToken, ILendingPool _lendingPool, address _asset, uint256 _rateMode ) external { ( , , bytes memory callData) = getSwapBorrowRateModeCalldata( _lendingPool, _asset, _rateMode ); _setToken.invoke(address(_lendingPool), 0, callData); } } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IAToken is IERC20 { function UNDERLYING_ASSET_ADDRESS() external view returns (address); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; interface IController { function addSet(address _setToken) external; function feeRecipient() external view returns(address); function getModuleFee(address _module, uint256 _feeType) external view returns(uint256); function isModule(address _module) external view returns(bool); function isSet(address _setToken) external view returns(bool); function isSystemContract(address _contractAddress) external view returns (bool); function resourceId(uint256 _id) external view returns(address); } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { ISetToken } from "./ISetToken.sol"; /** * @title IDebtIssuanceModule * @author Set Protocol * * Interface for interacting with Debt Issuance module interface. */ interface IDebtIssuanceModule { /** * Called by another module to register itself on debt issuance module. Any logic can be included * in case checks need to be made or state needs to be updated. */ function registerToIssuanceModule(ISetToken _setToken) external; /** * Called by another module to unregister itself on debt issuance module. Any logic can be included * in case checks need to be made or state needs to be cleared. */ function unregisterFromIssuanceModule(ISetToken _setToken) external; } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; interface IExchangeAdapter { function getSpender() external view returns(address); function getTradeCalldata( address _fromToken, address _toToken, address _toAddress, uint256 _fromQuantity, uint256 _minToQuantity, bytes memory _data ) external view returns (address, uint256, bytes memory); } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import { ILendingPoolAddressesProvider } from "./ILendingPoolAddressesProvider.sol"; import { DataTypes } from "./lib/DataTypes.sol"; 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); } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title 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; } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { ISetToken } from "./ISetToken.sol"; /** * CHANGELOG: * - Added a module level issue hook that can be used to set state ahead of component level * issue hooks */ interface IModuleIssuanceHook { function moduleIssueHook(ISetToken _setToken, uint256 _setTokenQuantity) external; function moduleRedeemHook(ISetToken _setToken, uint256 _setTokenQuantity) external; function componentIssueHook( ISetToken _setToken, uint256 _setTokenQuantity, IERC20 _component, bool _isEquity ) external; function componentRedeemHook( ISetToken _setToken, uint256 _setTokenQuantity, IERC20 _component, bool _isEquity ) external; } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import { ILendingPoolAddressesProvider } from "./ILendingPoolAddressesProvider.sol"; 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); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ISetToken * @author Set Protocol * * Interface for operating with SetTokens. */ interface ISetToken is IERC20 { /* ============ Enums ============ */ enum ModuleState { NONE, PENDING, INITIALIZED } /* ============ Structs ============ */ /** * The base definition of a SetToken Position * * @param component Address of token in the Position * @param module If not in default state, the address of associated module * @param unit Each unit is the # of components per 10^18 of a SetToken * @param positionState Position ENUM. Default is 0; External is 1 * @param data Arbitrary data */ struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; } /** * A struct that stores a component's cash position details and external positions * This data structure allows O(1) access to a component's cash position units and * virtual units. * * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency * updating all units at once via the position multiplier. Virtual units are achieved * by dividing a "real" value by the "positionMultiplier" * @param componentIndex * @param externalPositionModules List of external modules attached to each external position. Each module * maps to an external position * @param externalPositions Mapping of module => ExternalPosition struct for a given component */ struct ComponentPosition { int256 virtualUnit; address[] externalPositionModules; mapping(address => ExternalPosition) externalPositions; } /** * A struct that stores a component's external position details including virtual unit and any * auxiliary data. * * @param virtualUnit Virtual value of a component's EXTERNAL position. * @param data Arbitrary data */ struct ExternalPosition { int256 virtualUnit; bytes data; } /* ============ Functions ============ */ function addComponent(address _component) external; function removeComponent(address _component) external; function editDefaultPositionUnit(address _component, int256 _realUnit) external; function addExternalPositionModule(address _component, address _positionModule) external; function removeExternalPositionModule(address _component, address _positionModule) external; function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external; function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external; function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory); function editPositionMultiplier(int256 _newMultiplier) external; function mint(address _account, uint256 _quantity) external; function burn(address _account, uint256 _quantity) external; function lock() external; function unlock() external; function addModule(address _module) external; function removeModule(address _module) external; function initializeModule() external; function setManager(address _manager) external; function manager() external view returns (address); function moduleStates(address _module) external view returns (ModuleState); function getModules() external view returns (address[] memory); function getDefaultPositionRealUnit(address _component) external view returns(int256); function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256); function getComponents() external view returns(address[] memory); function getExternalPositionModules(address _component) external view returns(address[] memory); function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory); function isExternalPositionModule(address _component, address _module) external view returns(bool); function isComponent(address _component) external view returns(bool); function positionMultiplier() external view returns (int256); function getPositions() external view returns (Position[] memory); function getTotalComponentRealUnits(address _component) external view returns(int256); function isInitializedModule(address _module) external view returns(bool); function isPendingModule(address _module) external view returns(bool); function isLocked() external view returns (bool); } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title IVariableDebtToken * @author Aave * @notice Defines the basic interface for a variable debt token. **/ interface IVariableDebtToken is IERC20 {} /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol"; import { ExplicitERC20 } from "../../lib/ExplicitERC20.sol"; import { IController } from "../../interfaces/IController.sol"; import { IModule } from "../../interfaces/IModule.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { Invoke } from "./Invoke.sol"; import { Position } from "./Position.sol"; import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; import { ResourceIdentifier } from "./ResourceIdentifier.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title ModuleBase * @author Set Protocol * * Abstract class that houses common Module-related state and functions. * * CHANGELOG: * - 4/21/21: Delegated modifier logic to internal helpers to reduce contract size * */ abstract contract ModuleBase is IModule { using AddressArrayUtils for address[]; using Invoke for ISetToken; using Position for ISetToken; using PreciseUnitMath for uint256; using ResourceIdentifier for IController; using SafeCast for int256; using SafeCast for uint256; using SafeMath for uint256; using SignedSafeMath for int256; /* ============ State Variables ============ */ // Address of the controller IController public controller; /* ============ Modifiers ============ */ modifier onlyManagerAndValidSet(ISetToken _setToken) { _validateOnlyManagerAndValidSet(_setToken); _; } modifier onlySetManager(ISetToken _setToken, address _caller) { _validateOnlySetManager(_setToken, _caller); _; } modifier onlyValidAndInitializedSet(ISetToken _setToken) { _validateOnlyValidAndInitializedSet(_setToken); _; } /** * Throws if the sender is not a SetToken's module or module not enabled */ modifier onlyModule(ISetToken _setToken) { _validateOnlyModule(_setToken); _; } /** * Utilized during module initializations to check that the module is in pending state * and that the SetToken is valid */ modifier onlyValidAndPendingSet(ISetToken _setToken) { _validateOnlyValidAndPendingSet(_setToken); _; } /* ============ Constructor ============ */ /** * Set state variables and map asset pairs to their oracles * * @param _controller Address of controller contract */ constructor(IController _controller) public { controller = _controller; } /* ============ Internal Functions ============ */ /** * Transfers tokens from an address (that has set allowance on the module). * * @param _token The address of the ERC20 token * @param _from The address to transfer from * @param _to The address to transfer to * @param _quantity The number of tokens to transfer */ function transferFrom(IERC20 _token, address _from, address _to, uint256 _quantity) internal { ExplicitERC20.transferFrom(_token, _from, _to, _quantity); } /** * Gets the integration for the module with the passed in name. Validates that the address is not empty */ function getAndValidateAdapter(string memory _integrationName) internal view returns(address) { bytes32 integrationHash = getNameHash(_integrationName); return getAndValidateAdapterWithHash(integrationHash); } /** * Gets the integration for the module with the passed in hash. Validates that the address is not empty */ function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns(address) { address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash( address(this), _integrationHash ); require(adapter != address(0), "Must be valid adapter"); return adapter; } /** * Gets the total fee for this module of the passed in index (fee % * quantity) */ function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns(uint256) { uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex); return _quantity.preciseMul(feePercentage); } /** * Pays the _feeQuantity from the _setToken denominated in _token to the protocol fee recipient */ function payProtocolFeeFromSetToken(ISetToken _setToken, address _token, uint256 _feeQuantity) internal { if (_feeQuantity > 0) { _setToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity); } } /** * Returns true if the module is in process of initialization on the SetToken */ function isSetPendingInitialization(ISetToken _setToken) internal view returns(bool) { return _setToken.isPendingModule(address(this)); } /** * Returns true if the address is the SetToken's manager */ function isSetManager(ISetToken _setToken, address _toCheck) internal view returns(bool) { return _setToken.manager() == _toCheck; } /** * Returns true if SetToken must be enabled on the controller * and module is registered on the SetToken */ function isSetValidAndInitialized(ISetToken _setToken) internal view returns(bool) { return controller.isSet(address(_setToken)) && _setToken.isInitializedModule(address(this)); } /** * Hashes the string and returns a bytes32 value */ function getNameHash(string memory _name) internal pure returns(bytes32) { return keccak256(bytes(_name)); } /* ============== Modifier Helpers =============== * Internal functions used to reduce bytecode size */ /** * Caller must SetToken manager and SetToken must be valid and initialized */ function _validateOnlyManagerAndValidSet(ISetToken _setToken) internal view { require(isSetManager(_setToken, msg.sender), "Must be the SetToken manager"); require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); } /** * Caller must SetToken manager */ function _validateOnlySetManager(ISetToken _setToken, address _caller) internal view { require(isSetManager(_setToken, _caller), "Must be the SetToken manager"); } /** * SetToken must be valid and initialized */ function _validateOnlyValidAndInitializedSet(ISetToken _setToken) internal view { require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); } /** * Caller must be initialized module and module must be enabled on the controller */ function _validateOnlyModule(ISetToken _setToken) internal view { require( _setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED, "Only the module can call" ); require( controller.isModule(msg.sender), "Module must be enabled on controller" ); } /** * SetToken must be in a pending state and module must be in pending state */ function _validateOnlyValidAndPendingSet(ISetToken _setToken) internal view { require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken"); require(isSetPendingInitialization(_setToken), "Must be pending initialization"); } } // 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; } } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; 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} } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title AddressArrayUtils * @author Set Protocol * * Utility functions to handle Address Arrays * * CHANGELOG: * - 4/21/21: Added validatePairsWithArray methods */ library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(address[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The address to remove * @return Returns the array with the object removed. */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The address to remove */ function removeStorage(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Validate that address and uint array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of uint */ function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bool array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bool */ function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and string array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of strings */ function validatePairsWithArray(address[] memory A, string[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address array lengths match, and calling address array are not empty * and contain no duplicate elements. * * @param A Array of addresses * @param B Array of addresses */ function validatePairsWithArray(address[] memory A, address[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bytes array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bytes */ function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate address array is not empty and contains no duplicate elements. * * @param A Array of addresses */ function _validateLengthAndUniqueness(address[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate addresses"); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title ExplicitERC20 * @author Set Protocol * * Utility functions for ERC20 transfers that require the explicit amount to be transferred. */ library ExplicitERC20 { using SafeMath for uint256; /** * When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity". * Ensures that the recipient has received the correct quantity (ie no fees taken on transfer) * * @param _token ERC20 token to approve * @param _from The account to transfer tokens from * @param _to The account to transfer tokens to * @param _quantity The quantity to transfer */ function transferFrom( IERC20 _token, address _from, address _to, uint256 _quantity ) internal { // Call specified ERC20 contract to transfer tokens (via proxy). if (_quantity > 0) { uint256 existingBalance = _token.balanceOf(_to); SafeERC20.safeTransferFrom( _token, _from, _to, _quantity ); uint256 newBalance = _token.balanceOf(_to); // Verify transfer quantity is reflected in balance require( newBalance == existingBalance.add(_quantity), "Invalid post transfer balance" ); } } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title IModule * @author Set Protocol * * Interface for interacting with Modules. */ interface IModule { /** * Called by a SetToken to notify that this module was removed from the Set token. Any logic can be included * in case checks need to be made or state needs to be cleared. */ function removeModule() external; } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; /** * @title Invoke * @author Set Protocol * * A collection of common utility functions for interacting with the SetToken's invoke function */ library Invoke { using SafeMath for uint256; /* ============ Internal ============ */ /** * Instructs the SetToken to set approvals of the ERC20 token to a spender. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to approve * @param _spender The account allowed to spend the SetToken's balance * @param _quantity The quantity of allowance to allow */ function invokeApprove( ISetToken _setToken, address _token, address _spender, uint256 _quantity ) internal { bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity); _setToken.invoke(_token, 0, callData); } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function invokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity); _setToken.invoke(_token, 0, callData); } } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * The new SetToken balance must equal the existing balance less the quantity transferred * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function strictInvokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { // Retrieve current balance of token for the SetToken uint256 existingBalance = IERC20(_token).balanceOf(address(_setToken)); Invoke.invokeTransfer(_setToken, _token, _to, _quantity); // Get new balance of transferred token for SetToken uint256 newBalance = IERC20(_token).balanceOf(address(_setToken)); // Verify only the transfer quantity is subtracted require( newBalance == existingBalance.sub(_quantity), "Invalid post transfer balance" ); } } /** * Instructs the SetToken to unwrap the passed quantity of WETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeUnwrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal { bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity); _setToken.invoke(_weth, 0, callData); } /** * Instructs the SetToken to wrap the passed quantity of ETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeWrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal { bytes memory callData = abi.encodeWithSignature("deposit()"); _setToken.invoke(_weth, _quantity, callData); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; /** * @title Position * @author Set Protocol * * Collection of helper functions for handling and updating SetToken Positions * * CHANGELOG: * - Updated editExternalPosition to work when no external position is associated with module */ library Position { using SafeCast for uint256; using SafeMath for uint256; using SafeCast for int256; using SignedSafeMath for int256; using PreciseUnitMath for uint256; /* ============ Helper ============ */ /** * Returns whether the SetToken has a default position for a given component (if the real unit is > 0) */ function hasDefaultPosition(ISetToken _setToken, address _component) internal view returns(bool) { return _setToken.getDefaultPositionRealUnit(_component) > 0; } /** * Returns whether the SetToken has an external position for a given component (if # of position modules is > 0) */ function hasExternalPosition(ISetToken _setToken, address _component) internal view returns(bool) { return _setToken.getExternalPositionModules(_component).length > 0; } /** * Returns whether the SetToken component default position real unit is greater than or equal to units passed in. */ function hasSufficientDefaultUnits(ISetToken _setToken, address _component, uint256 _unit) internal view returns(bool) { return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256(); } /** * Returns whether the SetToken component external position is greater than or equal to the real units passed in. */ function hasSufficientExternalUnits( ISetToken _setToken, address _component, address _positionModule, uint256 _unit ) internal view returns(bool) { return _setToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256(); } /** * If the position does not exist, create a new Position and add to the SetToken. If it already exists, * then set the position units. If the new units is 0, remove the position. Handles adding/removing of * components where needed (in light of potential external positions). * * @param _setToken Address of SetToken being modified * @param _component Address of the component * @param _newUnit Quantity of Position units - must be >= 0 */ function editDefaultPosition(ISetToken _setToken, address _component, uint256 _newUnit) internal { bool isPositionFound = hasDefaultPosition(_setToken, _component); if (!isPositionFound && _newUnit > 0) { // If there is no Default Position and no External Modules, then component does not exist if (!hasExternalPosition(_setToken, _component)) { _setToken.addComponent(_component); } } else if (isPositionFound && _newUnit == 0) { // If there is a Default Position and no external positions, remove the component if (!hasExternalPosition(_setToken, _component)) { _setToken.removeComponent(_component); } } _setToken.editDefaultPositionUnit(_component, _newUnit.toInt256()); } /** * Update an external position and remove and external positions or components if necessary. The logic flows as follows: * 1) If component is not already added then add component and external position. * 2) If component is added but no existing external position using the passed module exists then add the external position. * 3) If the existing position is being added to then just update the unit and data * 4) If the position is being closed and no other external positions or default positions are associated with the component * then untrack the component and remove external position. * 5) If the position is being closed and other existing positions still exist for the component then just remove the * external position. * * @param _setToken SetToken being updated * @param _component Component position being updated * @param _module Module external position is associated with * @param _newUnit Position units of new external position * @param _data Arbitrary data associated with the position */ function editExternalPosition( ISetToken _setToken, address _component, address _module, int256 _newUnit, bytes memory _data ) internal { if (_newUnit != 0) { if (!_setToken.isComponent(_component)) { _setToken.addComponent(_component); _setToken.addExternalPositionModule(_component, _module); } else if (!_setToken.isExternalPositionModule(_component, _module)) { _setToken.addExternalPositionModule(_component, _module); } _setToken.editExternalPositionUnit(_component, _module, _newUnit); _setToken.editExternalPositionData(_component, _module, _data); } else { require(_data.length == 0, "Passed data must be null"); // If no default or external position remaining then remove component from components array if (_setToken.getExternalPositionRealUnit(_component, _module) != 0) { address[] memory positionModules = _setToken.getExternalPositionModules(_component); if (_setToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) { require(positionModules[0] == _module, "External positions must be 0 to remove component"); _setToken.removeComponent(_component); } _setToken.removeExternalPositionModule(_component, _module); } } } /** * Get total notional amount of Default position * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _positionUnit Quantity of Position units * * @return Total notional amount of units */ function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) { return _setTokenSupply.preciseMul(_positionUnit); } /** * Get position unit from total notional amount * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _totalNotional Total notional amount of component prior to * @return Default position unit */ function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) { return _totalNotional.preciseDiv(_setTokenSupply); } /** * Get the total tracked balance - total supply * position unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @return Notional tracked balance */ function getDefaultTrackedBalance(ISetToken _setToken, address _component) internal view returns(uint256) { int256 positionUnit = _setToken.getDefaultPositionRealUnit(_component); return _setToken.totalSupply().preciseMul(positionUnit.toUint256()); } /** * Calculates the new default position unit and performs the edit with the new unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @param _setTotalSupply Current SetToken supply * @param _componentPreviousBalance Pre-action component balance * @return Current component balance * @return Previous position unit * @return New position unit */ function calculateAndEditDefaultPosition( ISetToken _setToken, address _component, uint256 _setTotalSupply, uint256 _componentPreviousBalance ) internal returns(uint256, uint256, uint256) { uint256 currentBalance = IERC20(_component).balanceOf(address(_setToken)); uint256 positionUnit = _setToken.getDefaultPositionRealUnit(_component).toUint256(); uint256 newTokenUnit; if (currentBalance > 0) { newTokenUnit = calculateDefaultEditPositionUnit( _setTotalSupply, _componentPreviousBalance, currentBalance, positionUnit ); } else { newTokenUnit = 0; } editDefaultPosition(_setToken, _component, newTokenUnit); return (currentBalance, positionUnit, newTokenUnit); } /** * Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state * The intention is to make updates to the units without accidentally picking up airdropped assets as well. * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _preTotalNotional Total notional amount of component prior to executing action * @param _postTotalNotional Total notional amount of component after the executing action * @param _prePositionUnit Position unit of SetToken prior to executing action * @return New position unit */ function calculateDefaultEditPositionUnit( uint256 _setTokenSupply, uint256 _preTotalNotional, uint256 _postTotalNotional, uint256 _prePositionUnit ) internal pure returns (uint256) { // If pre action total notional amount is greater then subtract post action total notional and calculate new position units uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_setTokenSupply)); return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_setTokenSupply); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title PreciseUnitMath * @author Set Protocol * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. * * CHANGELOG: * - 9/21/20: Added safePower function * - 4/21/21: Added approximatelyEquals function */ library PreciseUnitMath { using SafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 constant internal PRECISE_UNIT = 10 ** 18; int256 constant internal PRECISE_UNIT_INT = 10 ** 18; // Max unsigned integer value uint256 constant internal MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 constant internal MAX_INT_256 = type(int256).max; int256 constant internal MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "Cant divide by 0"); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "Cant divide by 0"); require(a != MIN_INT_256 || b != -1, "Invalid input"); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0, "Value must be positive"); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } /** * @dev Returns true if a =~ b within range, false otherwise. */ function approximatelyEquals(uint256 a, uint256 b, uint256 range) internal pure returns (bool) { return a <= b.add(range) && a >= b.sub(range); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IController } from "../../interfaces/IController.sol"; import { IIntegrationRegistry } from "../../interfaces/IIntegrationRegistry.sol"; import { IPriceOracle } from "../../interfaces/IPriceOracle.sol"; import { ISetValuer } from "../../interfaces/ISetValuer.sol"; /** * @title ResourceIdentifier * @author Set Protocol * * A collection of utility functions to fetch information related to Resource contracts in the system */ library ResourceIdentifier { // IntegrationRegistry will always be resource ID 0 in the system uint256 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0; // PriceOracle will always be resource ID 1 in the system uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1; // SetValuer resource will always be resource ID 2 in the system uint256 constant internal SET_VALUER_RESOURCE_ID = 2; /* ============ Internal ============ */ /** * Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on * the Controller */ function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) { return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID)); } /** * Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller */ function getPriceOracle(IController _controller) internal view returns (IPriceOracle) { return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID)); } /** * Gets the instance of Set valuer on Controller. Note: SetValuer is stored as index 2 on the Controller */ function getSetValuer(IController _controller) internal view returns (ISetValuer) { return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; interface IIntegrationRegistry { function addIntegration(address _module, string memory _id, address _wrapper) external; function getIntegrationAdapter(address _module, string memory _id) external view returns(address); function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address); function isValidIntegration(address _module, string memory _id) external view returns(bool); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title IPriceOracle * @author Set Protocol * * Interface for interacting with PriceOracle */ interface IPriceOracle { /* ============ Functions ============ */ function getPrice(address _assetOne, address _assetTwo) external view returns (uint256); function masterQuoteAsset() external view returns (address); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { ISetToken } from "../interfaces/ISetToken.sol"; interface ISetValuer { function calculateSetTokenValuation(ISetToken _setToken, address _quoteAsset) external view returns (uint256); }
* @dev Validates if a new asset can be added as borrow asset for given SetToken/
function _validateNewBorrowAsset(ISetToken _setToken, IERC20 _asset) internal view { require(!borrowAssetEnabled[_setToken][_asset], "Borrow already enabled"); ( , , address variableDebtToken) = protocolDataProvider.getReserveTokensAddresses(address(_asset)); require(address(underlyingToReserveTokens[_asset].variableDebtToken) == variableDebtToken, "Invalid variable debt token address"); (, , , , , , bool borrowingEnabled, , bool isActive, bool isFrozen) = protocolDataProvider.getReserveConfigurationData(address(_asset)); require(isActive, "Invalid aave reserve"); require(!isFrozen, "Frozen aave reserve"); require(borrowingEnabled, "Borrowing disabled on Aave"); }
462,725
[ 1, 9594, 309, 279, 394, 3310, 848, 506, 3096, 487, 29759, 3310, 364, 864, 1000, 1345, 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 ]
[ 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, 389, 5662, 1908, 38, 15318, 6672, 12, 45, 694, 1345, 389, 542, 1345, 16, 467, 654, 39, 3462, 389, 9406, 13, 2713, 1476, 288, 203, 3639, 2583, 12, 5, 70, 15318, 6672, 1526, 63, 67, 542, 1345, 6362, 67, 9406, 6487, 315, 38, 15318, 1818, 3696, 8863, 203, 540, 203, 3639, 261, 269, 269, 1758, 2190, 758, 23602, 1345, 13, 273, 1771, 20757, 18, 588, 607, 6527, 5157, 7148, 12, 2867, 24899, 9406, 10019, 203, 3639, 2583, 12, 2867, 12, 9341, 6291, 774, 607, 6527, 5157, 63, 67, 9406, 8009, 6105, 758, 23602, 1345, 13, 422, 2190, 758, 23602, 1345, 16, 315, 1941, 2190, 18202, 88, 1147, 1758, 8863, 203, 540, 203, 3639, 261, 16, 269, 269, 269, 269, 269, 1426, 29759, 310, 1526, 16, 269, 1426, 15083, 16, 1426, 17646, 9808, 13, 273, 1771, 20757, 18, 588, 607, 6527, 1750, 751, 12, 2867, 24899, 9406, 10019, 203, 3639, 2583, 12, 291, 3896, 16, 315, 1941, 279, 836, 20501, 8863, 203, 3639, 2583, 12, 5, 291, 42, 9808, 16, 315, 42, 9808, 279, 836, 20501, 8863, 203, 3639, 2583, 12, 70, 15318, 310, 1526, 16, 315, 38, 15318, 310, 5673, 603, 432, 836, 8863, 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 ]
./full_match/97/0x294196C52C68673Ac90cDBF58aB1Dc72405a4773/sources/project:/contracts/RoxInfinityLaunchpad.sol
modifier to check if the sale is active or not
modifier saleDuration() { require( block.timestamp > preSaleStartTime, "Presale: Sale hasn't started" ); require( block.timestamp < preSaleEndTime, "PreSale: Sale has already ended" ); _; }
3,275,031
[ 1, 20597, 358, 866, 309, 326, 272, 5349, 353, 2695, 578, 486, 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, 9606, 272, 5349, 5326, 1435, 288, 203, 3639, 2583, 12, 203, 5411, 1203, 18, 5508, 405, 675, 30746, 13649, 16, 203, 5411, 315, 12236, 5349, 30, 348, 5349, 13342, 1404, 5746, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 1203, 18, 5508, 411, 675, 30746, 25255, 16, 203, 5411, 315, 1386, 30746, 30, 348, 5349, 711, 1818, 16926, 6, 203, 3639, 11272, 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 ]
./full_match/1/0x5682dC851C33adb48F6958a963A5d3Aa31F6f184/sources/contracts/router/quoter/PoolQuoterV1.sol
@notice Stateless abstraction to calculate exact quotes for any DefaultPool instances.
abstract contract PoolQuoterV1 is ISwapQuoterV1 { uint8 private constant NOT_FOUND = 0xFF; address public immutable defaultPoolCalc; address public immutable weth; pragma solidity 0.8.17; import {IDefaultPoolCalc} from "../interfaces/IDefaultPoolCalc.sol"; import {IDefaultExtendedPool} from "../interfaces/IDefaultExtendedPool.sol"; import {ILinkedPool} from "../interfaces/ILinkedPool.sol"; import {IPausable} from "../interfaces/IPausable.sol"; import {ISwapQuoterV1, PoolToken, SwapQuery} from "../interfaces/ISwapQuoterV1.sol"; import {Action, DefaultParams} from "../libs/Structs.sol"; import {UniversalTokenLib} from "../libs/UniversalToken.sol"; constructor(address defaultPoolCalc_, address weth_) { defaultPoolCalc = defaultPoolCalc_; weth = weth_; } function calculateAddLiquidity(address pool, uint256[] memory amounts) external view returns (uint256 amountOut) { return IDefaultPoolCalc(defaultPoolCalc).calculateAddLiquidity(pool, amounts); } function calculateSwap( address pool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 amountOut) { return IDefaultExtendedPool(pool).calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } function calculateRemoveLiquidity(address pool, uint256 amount) external view returns (uint256[] memory amountsOut) { return IDefaultExtendedPool(pool).calculateRemoveLiquidity(amount); } function calculateWithdrawOneToken( address pool, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 amountOut) { return IDefaultExtendedPool(pool).calculateRemoveLiquidityOneToken(tokenAmount, tokenIndex); } function poolInfo(address pool) external view returns (uint256 numTokens, address lpToken) { numTokens = _numTokens(pool); lpToken = _lpToken(pool); } function poolTokens(address pool) external view returns (PoolToken[] memory tokens) { tokens = _getPoolTokens(pool); } function _lpToken(address pool) internal view returns (address) { try IDefaultExtendedPool(pool).swapStorage() returns ( uint256, uint256, uint256, uint256, uint256, uint256, address lpToken ) { return lpToken; return address(0); } } function _lpToken(address pool) internal view returns (address) { try IDefaultExtendedPool(pool).swapStorage() returns ( uint256, uint256, uint256, uint256, uint256, uint256, address lpToken ) { return lpToken; return address(0); } } } catch { function _numTokens(address pool) internal view returns (uint256 numTokens) { while (true) { try IDefaultExtendedPool(pool).getToken(uint8(numTokens)) returns (address) { unchecked { ++numTokens; } } } } function _numTokens(address pool) internal view returns (uint256 numTokens) { while (true) { try IDefaultExtendedPool(pool).getToken(uint8(numTokens)) returns (address) { unchecked { ++numTokens; } } } } function _numTokens(address pool) internal view returns (uint256 numTokens) { while (true) { try IDefaultExtendedPool(pool).getToken(uint8(numTokens)) returns (address) { unchecked { ++numTokens; } } } } function _numTokens(address pool) internal view returns (uint256 numTokens) { while (true) { try IDefaultExtendedPool(pool).getToken(uint8(numTokens)) returns (address) { unchecked { ++numTokens; } } } } } catch { break; function _getPoolTokens(address pool) internal view returns (PoolToken[] memory tokens) { uint256 numTokens = _numTokens(pool); tokens = new PoolToken[](numTokens); unchecked { for (uint256 i = 0; i < numTokens; ++i) { address token = IDefaultExtendedPool(pool).getToken(uint8(i)); } } } function _getPoolTokens(address pool) internal view returns (PoolToken[] memory tokens) { uint256 numTokens = _numTokens(pool); tokens = new PoolToken[](numTokens); unchecked { for (uint256 i = 0; i < numTokens; ++i) { address token = IDefaultExtendedPool(pool).getToken(uint8(i)); } } } function _getPoolTokens(address pool) internal view returns (PoolToken[] memory tokens) { uint256 numTokens = _numTokens(pool); tokens = new PoolToken[](numTokens); unchecked { for (uint256 i = 0; i < numTokens; ++i) { address token = IDefaultExtendedPool(pool).getToken(uint8(i)); } } } tokens[i] = PoolToken({isWeth: token == weth, token: token}); function _getTokenIndexes( address pool, address tokenIn, address tokenOut ) internal view returns (uint8 indexIn, uint8 indexOut) { uint256 numTokens = _numTokens(pool); indexIn = NOT_FOUND; indexOut = NOT_FOUND; unchecked { for (uint8 t = 0; t < numTokens; ++t) { address poolToken = IDefaultExtendedPool(pool).getToken(t); if (_poolToken(tokenIn) == poolToken) indexIn = t; if (_poolToken(tokenOut) == poolToken) indexOut = t; } } } function _getTokenIndexes( address pool, address tokenIn, address tokenOut ) internal view returns (uint8 indexIn, uint8 indexOut) { uint256 numTokens = _numTokens(pool); indexIn = NOT_FOUND; indexOut = NOT_FOUND; unchecked { for (uint8 t = 0; t < numTokens; ++t) { address poolToken = IDefaultExtendedPool(pool).getToken(t); if (_poolToken(tokenIn) == poolToken) indexIn = t; if (_poolToken(tokenOut) == poolToken) indexOut = t; } } } function _getTokenIndexes( address pool, address tokenIn, address tokenOut ) internal view returns (uint8 indexIn, uint8 indexOut) { uint256 numTokens = _numTokens(pool); indexIn = NOT_FOUND; indexOut = NOT_FOUND; unchecked { for (uint8 t = 0; t < numTokens; ++t) { address poolToken = IDefaultExtendedPool(pool).getToken(t); if (_poolToken(tokenIn) == poolToken) indexIn = t; if (_poolToken(tokenOut) == poolToken) indexOut = t; } } } function _isPoolPaused(address pool) internal view returns (bool) { (bool success, bytes memory returnData) = pool.staticcall(abi.encodeWithSelector(IPausable.paused.selector)); return success && returnData.length == 32 && abi.decode(returnData, (bool)); } function _isConnectedViaDefaultPool( uint256 actionMask, address pool, address tokenIn, address tokenOut ) internal view returns (bool) { (uint8 indexIn, uint8 indexOut) = _getTokenIndexes(pool, tokenIn, tokenOut); if (Action.Swap.isIncluded(actionMask) && indexIn != NOT_FOUND && indexOut != NOT_FOUND) { return true; } address lpToken = _lpToken(pool); if (Action.AddLiquidity.isIncluded(actionMask) && indexIn != NOT_FOUND && tokenOut == lpToken) { return true; } if (Action.RemoveLiquidity.isIncluded(actionMask) && tokenIn == lpToken && indexOut != NOT_FOUND) { return true; } return false; } function _isConnectedViaDefaultPool( uint256 actionMask, address pool, address tokenIn, address tokenOut ) internal view returns (bool) { (uint8 indexIn, uint8 indexOut) = _getTokenIndexes(pool, tokenIn, tokenOut); if (Action.Swap.isIncluded(actionMask) && indexIn != NOT_FOUND && indexOut != NOT_FOUND) { return true; } address lpToken = _lpToken(pool); if (Action.AddLiquidity.isIncluded(actionMask) && indexIn != NOT_FOUND && tokenOut == lpToken) { return true; } if (Action.RemoveLiquidity.isIncluded(actionMask) && tokenIn == lpToken && indexOut != NOT_FOUND) { return true; } return false; } function _isConnectedViaDefaultPool( uint256 actionMask, address pool, address tokenIn, address tokenOut ) internal view returns (bool) { (uint8 indexIn, uint8 indexOut) = _getTokenIndexes(pool, tokenIn, tokenOut); if (Action.Swap.isIncluded(actionMask) && indexIn != NOT_FOUND && indexOut != NOT_FOUND) { return true; } address lpToken = _lpToken(pool); if (Action.AddLiquidity.isIncluded(actionMask) && indexIn != NOT_FOUND && tokenOut == lpToken) { return true; } if (Action.RemoveLiquidity.isIncluded(actionMask) && tokenIn == lpToken && indexOut != NOT_FOUND) { return true; } return false; } function _isConnectedViaDefaultPool( uint256 actionMask, address pool, address tokenIn, address tokenOut ) internal view returns (bool) { (uint8 indexIn, uint8 indexOut) = _getTokenIndexes(pool, tokenIn, tokenOut); if (Action.Swap.isIncluded(actionMask) && indexIn != NOT_FOUND && indexOut != NOT_FOUND) { return true; } address lpToken = _lpToken(pool); if (Action.AddLiquidity.isIncluded(actionMask) && indexIn != NOT_FOUND && tokenOut == lpToken) { return true; } if (Action.RemoveLiquidity.isIncluded(actionMask) && tokenIn == lpToken && indexOut != NOT_FOUND) { return true; } return false; } function _isConnectedViaLinkedPool( uint256 actionMask, address pool, address tokenIn, address tokenOut ) internal view returns (bool) { if (Action.Swap.isIncluded(actionMask)) { return ILinkedPool(pool).areConnectedTokens(_poolToken(tokenIn), _poolToken(tokenOut)); } return false; } function _isConnectedViaLinkedPool( uint256 actionMask, address pool, address tokenIn, address tokenOut ) internal view returns (bool) { if (Action.Swap.isIncluded(actionMask)) { return ILinkedPool(pool).areConnectedTokens(_poolToken(tokenIn), _poolToken(tokenOut)); } return false; } function _checkDefaultPoolQuote( uint256 actionMask, address pool, address tokenIn, address tokenOut, uint256 amountIn, SwapQuery memory curBestQuery ) internal view { if (_isPoolPaused(pool)) return; (uint8 indexIn, uint8 indexOut) = _getTokenIndexes(pool, tokenIn, tokenOut); if (indexIn != NOT_FOUND && indexOut != NOT_FOUND) { _checkSwapQuote(actionMask, pool, indexIn, indexOut, amountIn, curBestQuery); return; } address lpToken = _lpToken(pool); if (indexIn != NOT_FOUND && tokenOut == lpToken) { _checkAddLiquidityQuote(actionMask, pool, indexIn, amountIn, curBestQuery); _checkRemoveLiquidityQuote(actionMask, pool, indexOut, amountIn, curBestQuery); } } function _checkDefaultPoolQuote( uint256 actionMask, address pool, address tokenIn, address tokenOut, uint256 amountIn, SwapQuery memory curBestQuery ) internal view { if (_isPoolPaused(pool)) return; (uint8 indexIn, uint8 indexOut) = _getTokenIndexes(pool, tokenIn, tokenOut); if (indexIn != NOT_FOUND && indexOut != NOT_FOUND) { _checkSwapQuote(actionMask, pool, indexIn, indexOut, amountIn, curBestQuery); return; } address lpToken = _lpToken(pool); if (indexIn != NOT_FOUND && tokenOut == lpToken) { _checkAddLiquidityQuote(actionMask, pool, indexIn, amountIn, curBestQuery); _checkRemoveLiquidityQuote(actionMask, pool, indexOut, amountIn, curBestQuery); } } function _checkDefaultPoolQuote( uint256 actionMask, address pool, address tokenIn, address tokenOut, uint256 amountIn, SwapQuery memory curBestQuery ) internal view { if (_isPoolPaused(pool)) return; (uint8 indexIn, uint8 indexOut) = _getTokenIndexes(pool, tokenIn, tokenOut); if (indexIn != NOT_FOUND && indexOut != NOT_FOUND) { _checkSwapQuote(actionMask, pool, indexIn, indexOut, amountIn, curBestQuery); return; } address lpToken = _lpToken(pool); if (indexIn != NOT_FOUND && tokenOut == lpToken) { _checkAddLiquidityQuote(actionMask, pool, indexIn, amountIn, curBestQuery); _checkRemoveLiquidityQuote(actionMask, pool, indexOut, amountIn, curBestQuery); } } } else if (tokenIn == lpToken && indexOut != NOT_FOUND) { function _checkLinkedPoolQuote( uint256 actionMask, address pool, address tokenIn, address tokenOut, uint256 amountIn, SwapQuery memory curBestQuery ) internal view { if (Action.Swap.isIncluded(actionMask)) { try ILinkedPool(pool).findBestPath(_poolToken(tokenIn), _poolToken(tokenOut), amountIn) returns ( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 amountOut ) { if (amountOut > curBestQuery.minAmountOut) { curBestQuery.minAmountOut = amountOut; curBestQuery.rawParams = abi.encode(DefaultParams(Action.Swap, pool, tokenIndexFrom, tokenIndexTo)); } } } function _checkLinkedPoolQuote( uint256 actionMask, address pool, address tokenIn, address tokenOut, uint256 amountIn, SwapQuery memory curBestQuery ) internal view { if (Action.Swap.isIncluded(actionMask)) { try ILinkedPool(pool).findBestPath(_poolToken(tokenIn), _poolToken(tokenOut), amountIn) returns ( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 amountOut ) { if (amountOut > curBestQuery.minAmountOut) { curBestQuery.minAmountOut = amountOut; curBestQuery.rawParams = abi.encode(DefaultParams(Action.Swap, pool, tokenIndexFrom, tokenIndexTo)); } } } function _checkLinkedPoolQuote( uint256 actionMask, address pool, address tokenIn, address tokenOut, uint256 amountIn, SwapQuery memory curBestQuery ) internal view { if (Action.Swap.isIncluded(actionMask)) { try ILinkedPool(pool).findBestPath(_poolToken(tokenIn), _poolToken(tokenOut), amountIn) returns ( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 amountOut ) { if (amountOut > curBestQuery.minAmountOut) { curBestQuery.minAmountOut = amountOut; curBestQuery.rawParams = abi.encode(DefaultParams(Action.Swap, pool, tokenIndexFrom, tokenIndexTo)); } } } function _checkLinkedPoolQuote( uint256 actionMask, address pool, address tokenIn, address tokenOut, uint256 amountIn, SwapQuery memory curBestQuery ) internal view { if (Action.Swap.isIncluded(actionMask)) { try ILinkedPool(pool).findBestPath(_poolToken(tokenIn), _poolToken(tokenOut), amountIn) returns ( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 amountOut ) { if (amountOut > curBestQuery.minAmountOut) { curBestQuery.minAmountOut = amountOut; curBestQuery.rawParams = abi.encode(DefaultParams(Action.Swap, pool, tokenIndexFrom, tokenIndexTo)); } } } } catch { } function _checkSwapQuote( uint256 actionMask, address pool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 amountIn, SwapQuery memory curBestQuery ) internal view { if (!Action.Swap.isIncluded(actionMask)) return; try IDefaultExtendedPool(pool).calculateSwap(tokenIndexFrom, tokenIndexTo, amountIn) returns ( uint256 amountOut ) { if (amountOut > curBestQuery.minAmountOut) { curBestQuery.minAmountOut = amountOut; curBestQuery.rawParams = abi.encode(DefaultParams(Action.Swap, pool, tokenIndexFrom, tokenIndexTo)); } } function _checkSwapQuote( uint256 actionMask, address pool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 amountIn, SwapQuery memory curBestQuery ) internal view { if (!Action.Swap.isIncluded(actionMask)) return; try IDefaultExtendedPool(pool).calculateSwap(tokenIndexFrom, tokenIndexTo, amountIn) returns ( uint256 amountOut ) { if (amountOut > curBestQuery.minAmountOut) { curBestQuery.minAmountOut = amountOut; curBestQuery.rawParams = abi.encode(DefaultParams(Action.Swap, pool, tokenIndexFrom, tokenIndexTo)); } } function _checkSwapQuote( uint256 actionMask, address pool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 amountIn, SwapQuery memory curBestQuery ) internal view { if (!Action.Swap.isIncluded(actionMask)) return; try IDefaultExtendedPool(pool).calculateSwap(tokenIndexFrom, tokenIndexTo, amountIn) returns ( uint256 amountOut ) { if (amountOut > curBestQuery.minAmountOut) { curBestQuery.minAmountOut = amountOut; curBestQuery.rawParams = abi.encode(DefaultParams(Action.Swap, pool, tokenIndexFrom, tokenIndexTo)); } } } catch { } function _checkAddLiquidityQuote( uint256 actionMask, address pool, uint8 tokenIndexFrom, uint256 amountIn, SwapQuery memory curBestQuery ) internal view { if (!Action.AddLiquidity.isIncluded(actionMask)) return; uint256[] memory amounts = new uint256[](_numTokens(pool)); amounts[tokenIndexFrom] = amountIn; try IDefaultPoolCalc(defaultPoolCalc).calculateAddLiquidity(pool, amounts) returns (uint256 amountOut) { if (amountOut > curBestQuery.minAmountOut) { curBestQuery.minAmountOut = amountOut; curBestQuery.rawParams = abi.encode( DefaultParams(Action.AddLiquidity, pool, tokenIndexFrom, type(uint8).max) ); } } function _checkAddLiquidityQuote( uint256 actionMask, address pool, uint8 tokenIndexFrom, uint256 amountIn, SwapQuery memory curBestQuery ) internal view { if (!Action.AddLiquidity.isIncluded(actionMask)) return; uint256[] memory amounts = new uint256[](_numTokens(pool)); amounts[tokenIndexFrom] = amountIn; try IDefaultPoolCalc(defaultPoolCalc).calculateAddLiquidity(pool, amounts) returns (uint256 amountOut) { if (amountOut > curBestQuery.minAmountOut) { curBestQuery.minAmountOut = amountOut; curBestQuery.rawParams = abi.encode( DefaultParams(Action.AddLiquidity, pool, tokenIndexFrom, type(uint8).max) ); } } function _checkAddLiquidityQuote( uint256 actionMask, address pool, uint8 tokenIndexFrom, uint256 amountIn, SwapQuery memory curBestQuery ) internal view { if (!Action.AddLiquidity.isIncluded(actionMask)) return; uint256[] memory amounts = new uint256[](_numTokens(pool)); amounts[tokenIndexFrom] = amountIn; try IDefaultPoolCalc(defaultPoolCalc).calculateAddLiquidity(pool, amounts) returns (uint256 amountOut) { if (amountOut > curBestQuery.minAmountOut) { curBestQuery.minAmountOut = amountOut; curBestQuery.rawParams = abi.encode( DefaultParams(Action.AddLiquidity, pool, tokenIndexFrom, type(uint8).max) ); } } } catch { } function _checkRemoveLiquidityQuote( uint256 actionMask, address pool, uint8 tokenIndexTo, uint256 amountIn, SwapQuery memory curBestQuery ) internal view { if (!Action.RemoveLiquidity.isIncluded(actionMask)) return; try IDefaultExtendedPool(pool).calculateRemoveLiquidityOneToken(amountIn, tokenIndexTo) returns ( uint256 amountOut ) { if (amountOut > curBestQuery.minAmountOut) { curBestQuery.minAmountOut = amountOut; curBestQuery.rawParams = abi.encode( DefaultParams(Action.RemoveLiquidity, pool, type(uint8).max, tokenIndexTo) ); } } function _checkRemoveLiquidityQuote( uint256 actionMask, address pool, uint8 tokenIndexTo, uint256 amountIn, SwapQuery memory curBestQuery ) internal view { if (!Action.RemoveLiquidity.isIncluded(actionMask)) return; try IDefaultExtendedPool(pool).calculateRemoveLiquidityOneToken(amountIn, tokenIndexTo) returns ( uint256 amountOut ) { if (amountOut > curBestQuery.minAmountOut) { curBestQuery.minAmountOut = amountOut; curBestQuery.rawParams = abi.encode( DefaultParams(Action.RemoveLiquidity, pool, type(uint8).max, tokenIndexTo) ); } } function _checkRemoveLiquidityQuote( uint256 actionMask, address pool, uint8 tokenIndexTo, uint256 amountIn, SwapQuery memory curBestQuery ) internal view { if (!Action.RemoveLiquidity.isIncluded(actionMask)) return; try IDefaultExtendedPool(pool).calculateRemoveLiquidityOneToken(amountIn, tokenIndexTo) returns ( uint256 amountOut ) { if (amountOut > curBestQuery.minAmountOut) { curBestQuery.minAmountOut = amountOut; curBestQuery.rawParams = abi.encode( DefaultParams(Action.RemoveLiquidity, pool, type(uint8).max, tokenIndexTo) ); } } } catch { } function _checkHandleETHQuote( uint256 actionMask, address tokenIn, address tokenOut, uint256 amountIn, SwapQuery memory curBestQuery ) internal view { if (!Action.HandleEth.isIncluded(actionMask)) return; if (_isEthAndWeth(tokenIn, tokenOut) && amountIn > curBestQuery.minAmountOut) { curBestQuery.minAmountOut = amountIn; curBestQuery.rawParams = abi.encode( DefaultParams(Action.HandleEth, address(0), type(uint8).max, type(uint8).max) ); } } function _checkHandleETHQuote( uint256 actionMask, address tokenIn, address tokenOut, uint256 amountIn, SwapQuery memory curBestQuery ) internal view { if (!Action.HandleEth.isIncluded(actionMask)) return; if (_isEthAndWeth(tokenIn, tokenOut) && amountIn > curBestQuery.minAmountOut) { curBestQuery.minAmountOut = amountIn; curBestQuery.rawParams = abi.encode( DefaultParams(Action.HandleEth, address(0), type(uint8).max, type(uint8).max) ); } } function _isEthAndWeth(address tokenA, address tokenB) internal view returns (bool) { return (tokenA == UniversalTokenLib.ETH_ADDRESS && tokenB == weth) || (tokenA == weth && tokenB == UniversalTokenLib.ETH_ADDRESS); } function _poolToken(address token) internal view returns (address) { return token == UniversalTokenLib.ETH_ADDRESS ? weth : token; } }
4,844,647
[ 1, 5000, 12617, 1223, 701, 1128, 358, 4604, 5565, 10681, 364, 1281, 2989, 2864, 3884, 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 ]
[ 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, 17801, 6835, 8828, 7678, 264, 58, 21, 353, 4437, 91, 438, 7678, 264, 58, 21, 288, 203, 565, 2254, 28, 3238, 5381, 4269, 67, 9294, 273, 374, 6356, 31, 203, 203, 565, 1758, 1071, 11732, 805, 2864, 25779, 31, 203, 565, 1758, 1071, 11732, 341, 546, 31, 203, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 4033, 31, 203, 5666, 288, 734, 73, 643, 2864, 25779, 97, 628, 315, 6216, 15898, 19, 734, 73, 643, 2864, 25779, 18, 18281, 14432, 203, 5666, 288, 734, 73, 643, 11456, 2864, 97, 628, 315, 6216, 15898, 19, 734, 73, 643, 11456, 2864, 18, 18281, 14432, 203, 5666, 288, 45, 13174, 2864, 97, 628, 315, 6216, 15898, 19, 45, 13174, 2864, 18, 18281, 14432, 203, 5666, 288, 2579, 69, 16665, 97, 628, 315, 6216, 15898, 19, 2579, 69, 16665, 18, 18281, 14432, 203, 5666, 288, 5127, 91, 438, 7678, 264, 58, 21, 16, 8828, 1345, 16, 12738, 1138, 97, 628, 315, 6216, 15898, 19, 5127, 91, 438, 7678, 264, 58, 21, 18, 18281, 14432, 203, 5666, 288, 1803, 16, 2989, 1370, 97, 628, 315, 6216, 21571, 19, 3823, 87, 18, 18281, 14432, 203, 5666, 288, 984, 14651, 1345, 5664, 97, 628, 315, 6216, 21571, 19, 984, 14651, 1345, 18, 18281, 14432, 203, 565, 3885, 12, 2867, 805, 2864, 25779, 67, 16, 1758, 341, 546, 67, 13, 288, 203, 3639, 805, 2864, 25779, 273, 805, 2864, 25779, 67, 31, 203, 3639, 341, 546, 273, 341, 546, 67, 31, 203, 565, 289, 203, 203, 203, 565, 445, 4604, 986, 2 ]
// SPDX-License-Identifier: MIT /* ... .........'''',,,;;;,,,;;;;;;;;;;;;;;,,;;,,,,,''''............ .......''',,,,,,,,;:::::cccccccccccccccccccccc:::::;;;,,,''......... .........',,;;;:::ccooccllllooooooooooooolc::lolllllccccc:::;;,,,'''....... .........',,;;;::ccccllldKNkllddddxxxxxxxxxxdodo:,:dxddddoooollllcc:;::;,,'''........ . ........''',;;;:cclllooooddOWMN0xodkkOOOOOOOxxxkOko;',okkkkkkxxxddolc;',cccc:::;,,''........... . . .... .......',;;::ccllloodddxxxxxKMNOxkxlok0000OkkOKKOdlc:,';x000OOOOkdlc:;''ldoollccc::;;;,'''....... .... . ..... .......'',',,;:cclllooddxxxkkkOOkONMXxoddc,:x00OO0NN0xooool:,'cOKKK0kdol:'...cxxxdddoolllcc:;;;;,'........... ............ .................'''',,;;::cclllooddxxkkOOO0000O0WMKxd0XOo;;ok00KNXxooooddo:''cOOkxdl:'. ..;kOOkkkxxxddoollccc::;,''''.................... ...............'',,,,;;:ccllloddxxxkOOOO00KKKKK0KMW0dxKWX0kdxOOkKWKdlodooool;.'cddo;......,xKK00OOOkkxxxddoollcc::;;;;,'.....''........... ..............',,,,;;::ccllooddxkkOOO00KKKKKKKKK0XMWOokNWX00OO0K0XWOooodolllc:;;;;'........oKXKKK0000OOkkxxdddolllcc:;::;''...',........... ..............'',;;;:ccllooodxxkOO0000KKKKKKKOO0kONMNkd0WWKOOOkKXKNXdoodolclllc:;'.........:OXXXXXXK0000OOkkxxxddlcllc::::,','.............. ........'''',;;::ccllooddxxkkO0O00KKK00KKOd:;:cOMMXkkXMW0kkkOXKXWOlloodlccccc:,.........'dXNNNXXXX000KK0Okkkkxl;,collccc,.''.......'...... .......',,'',,;:ccllooodxxkkOO00000Oxdddxo;....,0MWKxOWMXOxddO00NXdlooooll:;;;;,'''''....;OXXXXXXXXKK0KKK00OOOko,,ld:,cllc'..,'.'.......... ........'',,,;:cllooodxxkkOkO0KK0Oo;'..... ;KWKxldO0xlcccllxKk::ccccc:;;;,,'',,,,....c0XXXXXXXXKKKXXKKKK00Od;:o:. ';,. .''.''......... .......'',,;::cloodddxkOOO00KKOxo:'. .;,...... ..........'',,;,'',,;'....:xKXNXXXNXXXKOdx0XKOdxxdl' ....'''....... ........',;;:clllodxxkkOOkddkOd;... ...',,..'. .:xKXXXNNNNXkc:dXKd'.cxo' ...... .''........ .....'',;;:clloddxkkOOko;.,c:.. . ... .'l0XXNNNWNko:lOx. ........'..',''. .';;'.''.... ....',,;;:ccloddxkOkkdc'.... .;oxk0XNNNKk:ox' .,ldoc::;,,;,'....,;,....... ....',,;;:cllodxxkOOxo;.... .,lkKNNNd':o,,ccxXWWWNXOddddlcoc'........... ....',;;:cclodxxkOkoc,. .,dKNNXc..';oKWMMMMMMMWX00KXNNKk:. ........ ....',;;cllodxkkOOl'. . ;kX0kKx'.'lOWMMMMMMMMMWWWMMMMMWO;......... ...',;::clodxkOO0k: cd. .oXNkxkxl..:kNMMMMMMMMMMMMMMMMMMNx;........ ..',,;:clodxkOO0Kx' ..',,'.. .lXNo .lKNKOdlcc,'l0WMMMMMMWWMMMMMMMMMW0l'..,'''' ..',;:cllddxk00K0l. .;lxO0XNNNNXK0xl;. .cOWMM0' :0WWN0ko;;,lOKXNWWWNNNWMMMMMMMMNk;..',;;,' ..',:cclodxkO000d;. .:xKWMMMMMWWWWMMMMMWKOkdc. .o0WMMMMNc 'kNWWWWKc;:okOO0KKKKKKXWWMMMWXkl;''''';;,' .',;:clodxxdddol,. .l0WMMMMMMMMN0oclx0NMMMMMMWk' .,lxXWMMMMMMMx. .l0XNWMWKoloxkkkO0O00O00KXX0o'.';ccc;;;;,' ',,;cllodo:,.... ;OWMMMMMMMMMMMXd. 'dXMMMMMWO' .:ONWMMMMMMMMMMO. .:ccxXNWWXkolllloxxdkkxxdddl,.,,;odolcc;,' ',;:clodo:.. :KMMWNNWMMMMMMMMNd. .lXMMMMNx, 'l0WMMMMMMMMMMMMMO. ....lOXWWWWXOdoccloololcccc:::lodxdollc;,' ',;cclodd:.. .cKMMWXk0WMMMMMMMMMO. ,kWMMWO;. ,dXWMMMMMMMMMMMMMMM0' .lKWWWWWWWNX0kddollccloddxkOOkxddolc:;, ',:clodxxo,. 'kNMMMW0ooKMMMMMMMMMO,;OWMMWO, .:kNMMMMMMMMMMMMMMMMMMO. ,dKWMMWWMWWWWWWNNXXKKKXNNXK00Okxdolc:;, ',:clodxkxl' lWMMMMWXo,:OWMMMMMMNkdKWMMNx' .l0WMMMMMMMMMMMMMMMMMMMMx. .cONWWWWMMWWWWWWWWWWNNWNNNXXK0Okxdolc:;, ,;cllodxkOkl. . .lk0XWMMXkc:dKWWWWWXXNMMW0c. 'dKWMMMMMMMMMMMMMMMMMMMMMXc ,OWWWWMMMMWWWWWWWWNNWWWNNNXK0Okxdolc:;, ;:clodxxkO0Oo. cl. ..:kNMMNKO0XNWWWWMMW0l. ;KMMMMMMMMMMMMMMMMMMMMMMMWd. lXMWWNNNXNNNWWWWWNWWNNNNNXK0Okxxolc:;, ;:clodxxkO00k, :K0l' 'cx0XWMMMMWNXOo;. lNMMMMMMMMMMMMMMMMMMMMMMWk. .lXWNKd;;coxOKXXK0OOOkxxxkOOOOkxdoc:;'. ,:clodxxOOOxc. .OMWXOo;.. ..,:cc:;,. oWMMMMMMMMMMMMMMMMMMMMMMK; 'o0KOo' ..',;;;,'...........',,',,'''.. ;:clodxxOOkl,. .dWMMMMWN0kdlc;,. .dWMMMMMMMMMMMMMMMMMMMMMXc .:dxl;.. .... ....' ;:clodxxkOOxl' :XMMMMMMMMMMMWW0: .xMMMMMMMMMMMMMMMMMMMMMNo. .,,'. ;:cloodxkOOOOxc. .OMMMMMMMMMMMMMMNd. .kMMMMMMMMMMMMMMMMMMWNKo. . ;:cllodxkOO0KXO, ;0WMMMMMMMMMMMMMW0; .OMMMMMMMMMMWXKOxdoc;'. ;:cclodxkOO00Ol. .oXMMMMMMMMMMMMMMXo. .OMMWNX0kdl:,.. ,;:llodxxkkOko, 'xNMMMMMMMMMMMMMWO, .col:,.. ,;:lloodxkOkd:.. :0WMMMMMMMMMMMMMXc. ,;:cllodxxkkdc'. .lKMMWWNXKOkdoc:' ,;::cloodxxkkxd;. 'cc;,'.. ,;::clooddxkOOOxc. ',;:ccloodxkkO000kc.. ',;::clloodxkkO00K0d,.. .',;::clllodxkOO00KKx:. ..'',;:clloddxkOO00K0l'. .''. ...'',;:clloodxkOO00KOl,. ......:l. .'. ...''',,:ccloodxkOOO0K0kl,. .'''.. cc. ;; ...'..',;::cloodxkkOO0KKKkl,. ..'''. .l; .:' ......',;;;ccloodxxkOO0KKXX0koc;. .'''.. .',;' ,;. .......',,;::clloddxkkO00KXXXXK0Od:. ...... .,,.. .'... .......'.'',;;ccloodxxkkO00KXXXXXKx;. .,'.. .,;,. . ..........'',;;:clloodxxkOOO0KXXXKOl;::,''. ';. .',,,.. ..........',,;;:cclooddxxkkOO00Oxoc,;okOxc,... ,' .,'.. .,. .,. .. .......'',,;;::cllooddxxkkkxc'...;cc;'.',;;'.. .. .,. .. ', .. ..........',,,,;::cclllol:,,;cloooc;.. .... .,. .. '. .. ............''',,;;;;;::...:dxoc;......... .. .' .. .. . ....... ......'''....':oxd:............ ..','',',,. '. ..''.. .. ...........;ddc'.... .....',,'''.. ........ .:do,. .,. .... .. .. ...... .cl;...... ..::;'.....',. .''. .' ..... . . ..... .,,...... 'll. .'.. ''.'.. ... ....',... .. .:o' .',,. .'. .'.. . ....,xd.... .:c. .,;..,::. .'. ....;0d....... ,c' .:c' .. '. . ..:0d. .,,. . .;:. .. .'. .'co;. .;0d. 'oc... ',. .,. ..';c,. . ..;Oo. :d;... .''.. ..''. .'.. .. Dev by @bitcoinski */ pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import '@openzeppelin/contracts/access/Ownable.sol'; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol'; import "./ICollectible.sol"; import "hardhat/console.sol"; /* * @title ERC721 token for Collectible, redeemable through burning MintPass tokens */ contract Collectible is ICollectible, AccessControl, ERC721Enumerable, ERC721Pausable, ERC721Burnable, Ownable { using Strings for uint256; using ECDSA for bytes32; using Counters for Counters.Counter; Counters.Counter private earlyIDCounter; Counters.Counter private generalCounter; mapping(uint256 => TokenData) public tokenData; mapping(uint256 => RedemptionWindow) public redemptionWindows; struct TokenData { string tokenURI; bool exists; } struct RedemptionWindow { uint256 windowOpens; uint256 windowCloses; uint256 maxRedeemPerTxn; } string private baseTokenURI; string public _contractURI; MintPassFactory public mintPassFactory; event Redeemed(address indexed account, string tokens); /** * @notice Constructor to create Collectible * * @param _symbol the token symbol * @param _mpIndexes the mintpass indexes to accommodate * @param _redemptionWindowsOpen the mintpass redemption window open unix timestamp by index * @param _redemptionWindowsClose the mintpass redemption window close unix timestamp by index * @param _maxRedeemPerTxn the max mint per redemption by index * @param _baseTokenURI the respective base URI * @param _contractMetaDataURI the respective contract meta data URI * @param _mintPassToken contract address of MintPass token to be burned */ constructor ( string memory _name, string memory _symbol, uint256[] memory _mpIndexes, uint256[] memory _redemptionWindowsOpen, uint256[] memory _redemptionWindowsClose, uint256[] memory _maxRedeemPerTxn, string memory _baseTokenURI, string memory _contractMetaDataURI, address _mintPassToken, uint earlyIDMax ) ERC721(_name, _symbol) { baseTokenURI = _baseTokenURI; _contractURI = _contractMetaDataURI; mintPassFactory = MintPassFactory(_mintPassToken); earlyIDCounter.increment(); for(uint256 i = 0; i <= earlyIDMax; i++) { generalCounter.increment(); } for(uint256 i = 0; i < _mpIndexes.length; i++) { uint passID = _mpIndexes[i]; redemptionWindows[passID].windowOpens = _redemptionWindowsOpen[i]; redemptionWindows[passID].windowCloses = _redemptionWindowsClose[i]; redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn[i]; } _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(DEFAULT_ADMIN_ROLE, 0x81745b7339D5067E82B93ca6BBAd125F214525d3); _setupRole(DEFAULT_ADMIN_ROLE, 0x90bFa85209Df7d86cA5F845F9Cd017fd85179f98); _setupRole(DEFAULT_ADMIN_ROLE, 0xE272d43Bee9E24a8d66ACe72ea40C44196E12947); } /** * @notice Set the mintpass contract address * * @param _mintPassToken the respective Mint Pass contract address */ function setMintPassToken(address _mintPassToken) external override onlyRole(DEFAULT_ADMIN_ROLE) { mintPassFactory = MintPassFactory(_mintPassToken); } /** * @notice Change the base URI for returning metadata * * @param _baseTokenURI the respective base URI */ function setBaseURI(string memory _baseTokenURI) external override onlyRole(DEFAULT_ADMIN_ROLE) { baseTokenURI = _baseTokenURI; } /** * @notice Pause redeems until unpause is called */ function pause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } /** * @notice Unpause redeems until pause is called */ function unpause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } /** * @notice Configure time to enable redeem functionality * * @param _windowOpen UNIX timestamp for redeem start */ function setRedeemStart(uint256 passID, uint256 _windowOpen) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowOpens = _windowOpen; } /** * @notice Configure time to enable redeem functionality * * @param _windowClose UNIX timestamp for redeem close */ function setRedeemClose(uint256 passID, uint256 _windowClose) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowCloses = _windowClose; } /** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param _maxRedeemPerTxn number of passes that can be redeemed */ function setMaxRedeemPerTxn(uint256 passID, uint256 _maxRedeemPerTxn) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn; } /** * @notice Check if redemption window is open * * @param passID the pass index to check */ function isRedemptionOpen(uint256 passID) public view override returns (bool) { if(paused()){ return false; } return block.timestamp > redemptionWindows[passID].windowOpens && block.timestamp < redemptionWindows[passID].windowCloses; } /** * @notice Redeem specified amount of MintPass tokens * * @param mpIndexes the tokenIDs of MintPasses to redeem * @param amounts the amount of MintPasses to redeem */ function redeem(uint256[] calldata mpIndexes, uint256[] calldata amounts) external override{ require(msg.sender == tx.origin, "Redeem: not allowed from contract"); require(!paused(), "Redeem: paused"); //check to make sure all are valid then re-loop for redemption for(uint256 i = 0; i < mpIndexes.length; i++) { require(amounts[i] > 0, "Redeem: amount cannot be zero"); require(amounts[i] <= redemptionWindows[mpIndexes[i]].maxRedeemPerTxn, "Redeem: max redeem per transaction reached"); require(mintPassFactory.balanceOf(msg.sender, mpIndexes[i]) >= amounts[i], "Redeem: insufficient amount of Mint Passes"); require(block.timestamp > redemptionWindows[mpIndexes[i]].windowOpens, "Redeem: redeption window not open for this Mint Pass"); require(block.timestamp < redemptionWindows[mpIndexes[i]].windowCloses, "Redeem: redeption window is closed for this Mint Pass"); } string memory tokens = ""; for(uint256 i = 0; i < mpIndexes.length; i++) { mintPassFactory.burnFromRedeem(msg.sender, mpIndexes[i], amounts[i]); for(uint256 j = 0; j < amounts[i]; j++) { _safeMint(msg.sender, mpIndexes[i] == 0 ? earlyIDCounter.current() : generalCounter.current()); tokens = string(abi.encodePacked(tokens, mpIndexes[i] == 0 ? earlyIDCounter.current().toString() : generalCounter.current().toString(), ",")); if(mpIndexes[i] == 0){ earlyIDCounter.increment(); } else{ generalCounter.increment(); } } } emit Redeemed(msg.sender, tokens); } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl,IERC165, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param id of token * @param uri to point the token to */ function setIndividualTokenURI(uint256 id, string memory uri) external override onlyRole(DEFAULT_ADMIN_ROLE){ require(_exists(id), "ERC721Metadata: Token does not exist"); tokenData[id].tokenURI = uri; tokenData[id].exists = true; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if(tokenData[tokenId].exists){ return tokenData[tokenId].tokenURI; } return string(abi.encodePacked(baseTokenURI, tokenId.toString(), '.json')); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } function setContractURI(string memory uri) external onlyRole(DEFAULT_ADMIN_ROLE){ _contractURI = uri; } function contractURI() public view returns (string memory) { return _contractURI; } } interface MintPassFactory { function burnFromRedeem(address account, uint256 id, uint256 amount) external; function balanceOf(address account, uint256 id) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract 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()); } } } // 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 Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "../../../security/Pausable.sol"; /** * @dev ERC721 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC721Pausable is ERC721, Pausable { /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "../../../utils/Context.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; interface ICollectible is IERC721Enumerable { function setMintPassToken(address _mintPassToken) external; function redeem(uint256[] calldata mpIndexes, uint256[] calldata amounts) external; function setRedeemStart(uint256 passID, uint256 _windowOpen) external; function setRedeemClose(uint256 passID, uint256 _windowClose) external; function setMaxRedeemPerTxn(uint256 passID, uint256 _maxRedeemPerTxn) external; function isRedemptionOpen(uint256 passID) external returns (bool); function unpause() external; function pause() external; function setBaseURI(string memory _baseTokenURI) external; function setIndividualTokenURI(uint256 passID, string memory uri) external; } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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); }
* @notice Check if redemption window is open @param passID the pass index to check/
function isRedemptionOpen(uint256 passID) public view override returns (bool) { if(paused()){ return false; } return block.timestamp > redemptionWindows[passID].windowOpens && block.timestamp < redemptionWindows[passID].windowCloses; }
453,293
[ 1, 1564, 309, 283, 19117, 375, 2742, 353, 1696, 225, 1342, 734, 326, 1342, 770, 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, 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, 28627, 19117, 375, 3678, 12, 11890, 5034, 1342, 734, 13, 1071, 1476, 3849, 1135, 261, 6430, 13, 288, 7010, 3639, 309, 12, 8774, 3668, 10756, 95, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 3639, 327, 1203, 18, 5508, 405, 283, 19117, 375, 10399, 63, 5466, 734, 8009, 5668, 17778, 597, 1203, 18, 5508, 411, 283, 19117, 375, 10399, 63, 5466, 734, 8009, 5668, 18545, 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 ]
// SPDX-License-Identifier: MIT // Created by The Spot GOATd Devs pragma solidity 0.8.11; library Strings { function toString(uint256 value) internal pure returns(string memory) { 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); } } library Address { function isContract(address account) internal view returns(bool) { return account.code.length > 0; } } library Counters { struct Counter { uint256 _value; } 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; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address to, 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 from, address to, 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); } interface IERC165 { function supportsInterface(bytes4 interfaceID) external view returns(bool); } interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenID); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenID); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) external view returns(uint256 balance); function ownerOf(uint256 tokenID) external view returns(address owner); function safeTransferFrom(address from, address to, uint256 tokenID) external; function transferFrom(address from, address to, uint256 tokenID) external; function approve(address to, uint256 tokenID) external; function getApproved(uint256 tokenID) external view returns(address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns(bool); function safeTransferFrom(address from, address to, uint256 tokenID, bytes calldata data) external; } interface IERC721Metadata is IERC721 { function name() external view returns(string memory); function symbol() external view returns(string memory); function tokenURI(uint256 tokenID) external view returns(string memory); } interface IERC721Receiver { function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns(bytes4); } interface IERC2981Royalties { function royaltyInfo(uint256 tokenID, uint256 value) external view returns(address receiver, uint256 royaltyAmount); } abstract contract Context { function _msgSender() internal view virtual returns(address) { return msg.sender; } function _msgData() internal view virtual returns(bytes calldata) { return msg.data; } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { _transferOwnership(_msgSender()); } function owner() public view virtual returns(address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } abstract contract ReentrancyGuard { uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } } abstract contract ERC165 is IERC165 { function supportsInterface(bytes4 interfaceID) public view virtual override returns(bool) { return interfaceID == type(IERC165).interfaceId; } } abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; string private _name; string private _symbol; mapping(uint256 => address) private _owners; mapping(address => uint256) private _balances; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function supportsInterface(bytes4 interfaceID) public view virtual override(ERC165, IERC165) returns(bool) { return interfaceID == type(IERC721).interfaceId || interfaceID == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceID); } function balanceOf(address owner) public view virtual override returns(uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } 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; } function name() public view virtual override returns(string memory) { return _name; } function symbol() public view virtual override returns(string memory) { return _symbol; } 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())) : ""; } function _baseURI() internal view virtual returns(string memory) { return ""; } 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); } function getApproved(uint256 tokenID) public view virtual override returns(address) { require(_exists(tokenID), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenID]; } function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address owner, address operator) public view virtual override returns(bool) { return _operatorApprovals[owner][operator]; } 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); } function safeTransferFrom(address from, address to, uint256 tokenID) public virtual override { safeTransferFrom(from, to, tokenID, ""); } 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); } 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"); } function _exists(uint256 tokenID) internal view virtual returns(bool) { return _owners[tokenID] != address(0); } 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)); } function _safeMint(address to, uint256 tokenID) internal virtual { _safeMint(to, tokenID, ""); } 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"); } 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); _afterTokenTransfer(address(0), to, tokenID); } function _burn(uint256 tokenID) internal virtual { address owner = ERC721.ownerOf(tokenID); _beforeTokenTransfer(owner, address(0), tokenID); _approve(address(0), tokenID); _balances[owner] -= 1; delete _owners[tokenID]; emit Transfer(owner, address(0), tokenID); _afterTokenTransfer(owner, address(0), tokenID); } function _transfer(address from, address to, uint256 tokenID) internal virtual { require(ERC721.ownerOf(tokenID) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenID); _approve(address(0), tokenID); _balances[from] -= 1; _balances[to] += 1; _owners[tokenID] = to; emit Transfer(from, to, tokenID); _afterTokenTransfer(from, to, tokenID); } function _approve(address to, uint256 tokenID) internal virtual { _tokenApprovals[tokenID] = to; emit Approval(ERC721.ownerOf(tokenID), to, tokenID); } function _setApprovalForAll(address owner, address operator, bool approved) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } 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; } function _beforeTokenTransfer(address from, address to, uint256 tokenID) internal virtual {} function _afterTokenTransfer(address from, address to, uint256 tokenID) internal virtual {} } abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; 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); } function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } interface ITRAIT { function burnSpotDrop(uint256 typeId, address burnTokenAddress) external; function balanceOf(address owner, uint256 typeId) external view returns (uint256); } contract GOATd is ERC721URIStorage, ReentrancyGuard, Ownable { using Counters for Counters.Counter; using Strings for uint256; bool public paused = true; uint256 public cost = 1 ether; uint256 public royalties = 100; mapping(bytes => uint8) public availableDNA; mapping(uint256 => uint8) public notBurnable; address private treasuryAddress = 0x32bD2811Fb91BC46756232A0B8c6b2902D7d8763; address private traitsAddress = 0x9521807ADF320D1CDF87AFDf875Bf438d1D92d87; ITRAIT traitsContract = ITRAIT(traitsAddress); Counters.Counter private supply; uint256 private constant PERCENTAGE_MULTIPLIER = 10000; event GoatMinted( uint256 indexed tokenId, address indexed minter, uint256[6] traitIDs ); constructor() ERC721("GOATd PFP", "GOATd") { } function supportsInterface(bytes4 interfaceID) public view override returns(bool) { return interfaceID == type(IERC2981Royalties).interfaceId || super.supportsInterface(interfaceID); } function mint(uint256 bg, uint256 body, uint256 head, uint256 eyes, uint256 mouth, uint256 headwear, string calldata uri) public payable nonReentrant { require(((bg > 0 && bg < 100) || notBurnable[bg] == 1) && ((body >= 100 && body < 200) || notBurnable[body] == 1) && ((head >= 200 && head < 300) || notBurnable[head] == 1) && ((eyes >= 300 && eyes < 400) || notBurnable[eyes] == 1) && ((mouth >= 400 && mouth < 500) || notBurnable[mouth] == 1) && (headwear >= 600 || notBurnable[headwear] == 1), "GOATd: At least one trait specified is invalid!"); if (notBurnable[bg] == 0){ require(traitsContract.balanceOf(_msgSender(), bg) > 0, "GOATd: You don't own that background!"); } if (notBurnable[body] == 0){ require(traitsContract.balanceOf(_msgSender(), body) > 0, "GOATd: You don't own that body!"); } if (notBurnable[head] == 0){ require(traitsContract.balanceOf(_msgSender(), head) > 0, "GOATd: You don't own that head!"); } if (notBurnable[eyes] == 0){ require(traitsContract.balanceOf(_msgSender(), eyes) > 0, "GOATd: You don't own that eyes!"); } if (notBurnable[mouth] == 0){ require(traitsContract.balanceOf(_msgSender(), mouth) > 0, "GOATd: You don't own that mouth!"); } if (notBurnable[headwear] == 0){ require(traitsContract.balanceOf(_msgSender(), headwear) > 0, "GOATd: You don't own that headwear!"); } bytes memory DNA = abi.encodePacked(Strings.toString(body), Strings.toString(head), Strings.toString(eyes), Strings.toString(mouth), Strings.toString(headwear)); require(availableDNA[DNA] == 0, "GOATd: Combination specified already exists!"); require(!paused, "Minting is paused"); require(msg.value >= cost, "Insufficient funds"); _mintLoop(_msgSender(), bg, body, head, eyes, mouth, headwear, uri); availableDNA[DNA] = 1; emit GoatMinted(supply.current(), _msgSender(), [bg, body, head, eyes, mouth, headwear]); } function _mintLoop(address to, uint256 bg, uint256 body, uint256 head, uint256 eyes, uint256 mouth, uint256 headwear, string memory uri) internal { if (notBurnable[bg] == 0){ traitsContract.burnSpotDrop(bg, to); } if (notBurnable[body] == 0){ traitsContract.burnSpotDrop(body, to); } if (notBurnable[head] == 0){ traitsContract.burnSpotDrop(head, to); } if (notBurnable[eyes] == 0){ traitsContract.burnSpotDrop(eyes, to); } if (notBurnable[mouth] == 0){ traitsContract.burnSpotDrop(mouth, to); } if (notBurnable[headwear] == 0){ traitsContract.burnSpotDrop(headwear, to); } supply.increment(); _safeMint(to, supply.current()); _setTokenURI(supply.current(), uri); } function flipPausedState() public onlyOwner { paused = !paused; } function withdraw() public onlyOwner { (bool success, ) = payable(treasuryAddress).call{ value: address(this).balance}(""); require(success, "AVAX Transaction: Failed to transfer funds to the owner wallet!"); } function royaltyInfo(uint256, uint256 value) external view returns(address, uint256) { return (treasuryAddress, value * royalties / PERCENTAGE_MULTIPLIER); } function totalSupply() public view returns(uint256) { return supply.current(); } function checkDNA(string calldata DNA) public view returns(uint8) { return availableDNA[abi.encodePacked(DNA)]; } function walletOfOwner(address _address) public view returns(uint256[] memory) { uint256 ownerTokenCount = balanceOf(_address); uint256[] memory ownedTokenIDs = new uint256[](ownerTokenCount); uint256 tokenIndex = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && tokenIndex <= totalSupply()) { address owner = ownerOf(tokenIndex); if (owner == _address) { ownedTokenIDs[ownedTokenIndex] = tokenIndex; ownedTokenIndex++; } tokenIndex++; } return ownedTokenIDs; } function setCost(uint256 newCost) public onlyOwner { cost = newCost; } function setRoyalties(uint256 newValue) public onlyOwner { royalties = newValue; } function setTreasuryAddress(address newTreasuryAddress) public onlyOwner { treasuryAddress = newTreasuryAddress; } function setTraitsAddress(address newTraitsAddress) public onlyOwner { traitsAddress = newTraitsAddress; traitsContract = ITRAIT(traitsAddress); } function addNotBurnable (uint256[] calldata _traits) public onlyOwner { for (uint256 i = 0; i < _traits.length; i++) { notBurnable[_traits[i]] = 1; } } function changeURI (uint256 tokenID, string calldata uri) public onlyOwner { _setTokenURI(tokenID, uri); } // Function to receive Ether. msg.data must be empty receive() external payable {} // Fallback function is called when msg.data is not empty fallback() external payable {} function withdrawERC20(address _tokenAddress) public payable onlyOwner { IERC20 token = IERC20(_tokenAddress); uint256 balance = token.balanceOf(address(this)); token.transfer(payable(owner()), balance); } function withdrawERC721(address _nftAddress, uint _tokenID) public payable onlyOwner { IERC721 token = IERC721(_nftAddress); token.safeTransferFrom(address(this), owner(), _tokenID); } }
Optional mapping for token URIs
abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; mapping(uint256 => string) private _tokenURIs; 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 (bytes(base).length == 0) { return _tokenURI; } if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } 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 (bytes(base).length == 0) { return _tokenURI; } if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } 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 (bytes(base).length == 0) { return _tokenURI; } if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } }
6,482,613
[ 1, 6542, 2874, 364, 1147, 24565, 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, 17801, 6835, 4232, 39, 27, 5340, 3098, 3245, 353, 4232, 39, 27, 5340, 288, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 533, 13, 3238, 389, 2316, 1099, 2520, 31, 203, 203, 203, 565, 445, 1147, 3098, 12, 11890, 5034, 1147, 548, 13, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 2583, 24899, 1808, 12, 2316, 548, 3631, 315, 654, 39, 27, 5340, 3098, 3245, 30, 3699, 843, 364, 1661, 19041, 1147, 8863, 203, 203, 3639, 533, 3778, 389, 2316, 3098, 273, 389, 2316, 1099, 2520, 63, 2316, 548, 15533, 203, 3639, 533, 3778, 1026, 273, 389, 1969, 3098, 5621, 203, 203, 3639, 309, 261, 3890, 12, 1969, 2934, 2469, 422, 374, 13, 288, 203, 5411, 327, 389, 2316, 3098, 31, 203, 3639, 289, 203, 3639, 309, 261, 3890, 24899, 2316, 3098, 2934, 2469, 405, 374, 13, 288, 203, 5411, 327, 533, 12, 21457, 18, 3015, 4420, 329, 12, 1969, 16, 389, 2316, 3098, 10019, 203, 3639, 289, 203, 203, 3639, 327, 2240, 18, 2316, 3098, 12, 2316, 548, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 1147, 3098, 12, 11890, 5034, 1147, 548, 13, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 2583, 24899, 1808, 12, 2316, 548, 3631, 315, 654, 39, 27, 5340, 3098, 3245, 30, 3699, 843, 364, 1661, 19041, 1147, 8863, 203, 203, 3639, 533, 3778, 389, 2316, 3098, 273, 389, 2316, 1099, 2520, 63, 2316, 548, 15533, 203, 3639, 533, 3778, 1026, 2 ]
pragma solidity ^0.4.17; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title 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 internal owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title TradePlaceCrowdsale * @author HamzaYasin1 - Github * @dev TradePlaceCrowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them EXTP tokens based * on a EXTP token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(msg.sender, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; MintFinished(); return true; } function burnTokens(uint256 _unsoldTokens) onlyOwner public returns (bool) { totalSupply = SafeMath.sub(totalSupply, _unsoldTokens); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title Med-h Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale is Ownable, Pausable { using SafeMath for uint256; /** * @MintableToken token - Token Object * @address wallet - Wallet Address * @uint256 rate - Tokens per Ether * @uint256 weiRaised - Total funds raised in Ethers */ MintableToken internal token; address internal wallet; uint256 public rate; uint256 internal weiRaised; /** * @uint256 preICOstartTime - pre ICO Start Time * @uint256 preICOEndTime - pre ICO End Time * @uint256 ICOstartTime - ICO Start Time * @uint256 ICOEndTime - ICO End Time */ uint256 public preICOstartTime; uint256 public preICOEndTime; uint256 public ICOstartTime; uint256 public ICOEndTime; // Weeks in UTC uint public StageTwo; uint public StageThree; uint public StageFour; /** * @uint preIcoBonus * @uint StageOneBonus * @uint StageTwoBonus * @uint StageThreeBonus */ uint public preIcoBonus; uint public StageOneBonus; uint public StageTwoBonus; uint public StageThreeBonus; /** * @uint256 totalSupply - Total supply of tokens ~ 500,000,000 EXTP * @uint256 publicSupply - Total public Supply ~ 20 percent * @uint256 preIcoSupply - Total PreICO Supply from Public Supply ~ 10 percent * @uint256 icoSupply - Total ICO Supply from Public Supply ~ 10 percent * @uint256 bountySupply - Total Bounty Supply ~ 10 percent * @uint256 reserveSupply - Total Reserve Supply ~ 20 percent * @uint256 advisorSupply - Total Advisor Supply ~ 10 percent * @uint256 founderSupply - Total Founder Supply ~ 20 percent * @uint256 teamSupply - Total team Supply ~ 10 percent * @uint256 rewardSupply - Total reward Supply ~ 10 percent */ uint256 public totalSupply = SafeMath.mul(500000000, 1 ether); // 500000000 uint256 public publicSupply = SafeMath.mul(100000000, 1 ether); uint256 public preIcoSupply = SafeMath.mul(50000000, 1 ether); uint256 public icoSupply = SafeMath.mul(50000000, 1 ether); uint256 public bountySupply = SafeMath.mul(50000000, 1 ether); uint256 public reserveSupply = SafeMath.mul(100000000, 1 ether); uint256 public advisorSupply = SafeMath.mul(50000000, 1 ether); uint256 public founderSupply = SafeMath.mul(100000000, 1 ether); uint256 public teamSupply = SafeMath.mul(50000000, 1 ether); uint256 public rewardSupply = SafeMath.mul(50000000, 1 ether); /** * @uint256 advisorTimeLock - Advisor Timelock * @uint256 founderfounderTimeLock - Founder and Team Timelock * @uint256 reserveTimeLock - Company Reserved Timelock * @uint256 reserveTimeLock - Team Timelock */ uint256 public founderTimeLock; uint256 public advisorTimeLock; uint256 public reserveTimeLock; uint256 public teamTimeLock; // count the number of function calls uint public founderCounter = 0; // internal uint public teamCounter = 0; uint public advisorCounter = 0; /** * @bool checkUnsoldTokens - * @bool upgradeICOSupply - Boolean variable updates when the PreICO tokens added to ICO supply * @bool grantReserveSupply - Boolean variable updates when reserve tokens minted */ bool public checkBurnTokens; bool public upgradeICOSupply; bool public grantReserveSupply; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * function Crowdsale - Parameterized Constructor * @param _startTime - StartTime of Crowdsale * @param _endTime - EndTime of Crowdsale * @param _rate - Tokens against Ether * @param _wallet - MultiSignature Wallet Address */ function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != 0x0); token = createTokenContract(); preICOstartTime = _startTime; // Dec - 10 - 2018 preICOEndTime = 1547769600; //SafeMath.add(preICOstartTime,3 minutes); Jan - 18 - 2019 ICOstartTime = 1548633600; //SafeMath.add(preICOEndTime, 1 minutes); Jan - 28 - 2019 ICOEndTime = _endTime; // March - 19 - 2019 rate = _rate; wallet = _wallet; /** Calculations of Bonuses in private Sale or Pre-ICO */ preIcoBonus = SafeMath.div(SafeMath.mul(rate,20),100); StageOneBonus = SafeMath.div(SafeMath.mul(rate,15),100); StageTwoBonus = SafeMath.div(SafeMath.mul(rate,10),100); StageThreeBonus = SafeMath.div(SafeMath.mul(rate,5),100); /** ICO bonuses week calculations */ StageTwo = SafeMath.add(ICOstartTime, 12 days); //12 days StageThree = SafeMath.add(StageTwo, 12 days); StageFour = SafeMath.add(StageThree, 12 days); /** Vested Period calculations for team and advisors*/ founderTimeLock = SafeMath.add(ICOEndTime, 3 minutes); advisorTimeLock = SafeMath.add(ICOEndTime, 3 minutes); reserveTimeLock = SafeMath.add(ICOEndTime, 3 minutes); teamTimeLock = SafeMath.add(ICOEndTime, 3 minutes); checkBurnTokens = false; upgradeICOSupply = false; grantReserveSupply = false; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (MintableToken) { return new MintableToken(); } /** * function preIcoTokens - Calculate Tokens in of PRE-ICO */ function preIcoTokens(uint256 weiAmount, uint256 tokens) internal returns (uint256) { require(preIcoSupply > 0); tokens = SafeMath.add(tokens, weiAmount.mul(preIcoBonus)); tokens = SafeMath.add(tokens, weiAmount.mul(rate)); require(preIcoSupply >= tokens); preIcoSupply = preIcoSupply.sub(tokens); publicSupply = publicSupply.sub(tokens); return tokens; } /** * function icoTokens - Calculate Tokens in Main ICO */ function icoTokens(uint256 weiAmount, uint256 tokens, uint256 accessTime) internal returns (uint256) { require(icoSupply > 0); if ( accessTime <= StageTwo ) { tokens = SafeMath.add(tokens, weiAmount.mul(StageOneBonus)); } else if (( accessTime <= StageThree ) && (accessTime > StageTwo)) { tokens = SafeMath.add(tokens, weiAmount.mul(StageTwoBonus)); } else if (( accessTime <= StageFour ) && (accessTime > StageThree)) { tokens = SafeMath.add(tokens, weiAmount.mul(StageThreeBonus)); } tokens = SafeMath.add(tokens, weiAmount.mul(rate)); require(icoSupply >= tokens); icoSupply = icoSupply.sub(tokens); publicSupply = publicSupply.sub(tokens); return tokens; } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // High level token purchase function function buyTokens(address beneficiary) whenNotPaused public payable { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; // minimum investment should be 0.05 ETH require((weiAmount >= 50000000000000000)); uint256 accessTime = now; uint256 tokens = 0; if ((accessTime >= preICOstartTime) && (accessTime <= preICOEndTime)) { tokens = preIcoTokens(weiAmount, tokens); } else if ((accessTime >= ICOstartTime) && (accessTime <= ICOEndTime)) { if (!upgradeICOSupply) { icoSupply = SafeMath.add(icoSupply,preIcoSupply); upgradeICOSupply = true; } tokens = icoTokens(weiAmount, tokens, accessTime); } else { revert(); } weiRaised = weiRaised.add(weiAmount); if(msg.data.length == 20) { address referer = bytesToAddress(bytes(msg.data)); // self-referrer check require(referer != msg.sender); uint refererTokens = tokens.mul(6).div(100); // bonus for referrer token.mint(referer, refererTokens); } token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // send ether to the fund collection wallet function forwardFunds() internal { wallet.transfer(msg.value); } function bytesToAddress(bytes source) internal pure returns(address) { uint result; uint mul = 1; for(uint i = 20; i > 0; i--) { result += uint8(source[i-1])*mul; mul = mul*256; } return address(result); } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= preICOstartTime && now <= ICOEndTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { return now > ICOEndTime; } function getTokenAddress() onlyOwner public returns (address) { return token; } } contract Allocations is Crowdsale { function bountyDrop(address[] recipients, uint256[] values) public onlyOwner { for (uint256 i = 0; i < recipients.length; i++) { values[i] = SafeMath.mul(values[i], 1 ether); require(bountySupply >= values[i]); bountySupply = SafeMath.sub(bountySupply,values[i]); token.mint(recipients[i], values[i]); } } function rewardDrop(address[] recipients, uint256[] values) public onlyOwner { for (uint256 i = 0; i < recipients.length; i++) { values[i] = SafeMath.mul(values[i], 1 ether); require(rewardSupply >= values[i]); rewardSupply = SafeMath.sub(rewardSupply,values[i]); token.mint(recipients[i], values[i]); } } function grantAdvisorToken(address beneficiary ) public onlyOwner { require((advisorCounter < 4) && (advisorTimeLock < now)); advisorTimeLock = SafeMath.add(advisorTimeLock, 2 minutes); token.mint(beneficiary,SafeMath.div(advisorSupply, 4)); advisorCounter = SafeMath.add(advisorCounter, 1); } function grantFounderToken(address founderAddress) public onlyOwner { require((founderCounter < 4) && (founderTimeLock < now)); founderTimeLock = SafeMath.add(founderTimeLock, 2 minutes); token.mint(founderAddress,SafeMath.div(founderSupply, 4)); founderCounter = SafeMath.add(founderCounter, 1); } function grantTeamToken(address teamAddress) public onlyOwner { require((teamCounter < 2) && (teamTimeLock < now)); teamTimeLock = SafeMath.add(teamTimeLock, 2 minutes); token.mint(teamAddress,SafeMath.div(teamSupply, 4)); teamCounter = SafeMath.add(teamCounter, 1); } function grantReserveToken(address beneficiary) public onlyOwner { require((!grantReserveSupply) && (now > reserveTimeLock)); grantReserveSupply = true; token.mint(beneficiary,reserveSupply); reserveSupply = 0; } function transferFunds(address[] recipients, uint256[] values) public onlyOwner { require(!checkBurnTokens); for (uint256 i = 0; i < recipients.length; i++) { values[i] = SafeMath.mul(values[i], 1 ether); require(publicSupply >= values[i]); publicSupply = SafeMath.sub(publicSupply,values[i]); token.mint(recipients[i], values[i]); } } function burnToken() public onlyOwner returns (bool) { require(hasEnded()); require(!checkBurnTokens); // token.burnTokens(icoSupply); totalSupply = SafeMath.sub(totalSupply, icoSupply); publicSupply = 0; preIcoSupply = 0; icoSupply = 0; checkBurnTokens = true; return true; } } /** * @title CappedCrowdsale * @dev Extension of Crowdsale with a max amount of funds raised */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 internal cap; function CappedCrowdsale(uint256 _cap) { require(_cap > 0); cap = _cap; } // overriding Crowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment function validPurchase() internal constant returns (bool) { bool withinCap = weiRaised.add(msg.value) <= cap; return super.validPurchase() && withinCap; } // overriding Crowdsale#hasEnded to add cap logic // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { bool capReached = weiRaised >= cap; return super.hasEnded() || capReached; } } /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Crowdsale { using SafeMath for uint256; bool isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalizeCrowdsale() onlyOwner public { require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); function RefundVault(address _wallet) { require(_wallet != 0x0); wallet = _wallet; state = State.Active; } function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; Closed(); wallet.transfer(this.balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } } /** * @title RefundableCrowdsale * @dev Extension of Crowdsale contract that adds a funding goal, and * the possibility of users getting a refund if goal is not met. * Uses a RefundVault as the crowdsale's vault. */ contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 internal goal; // refund vault used to hold funds while crowdsale is running RefundVault private vault; function RefundableCrowdsale(uint256 _goal) { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } // We're overriding the fund forwarding from Crowdsale. // In addition to sending the funds, we want to call // the RefundVault deposit function function forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } // if crowdsale is unsuccessful, investors can claim refunds here function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } // vault finalization task, called when owner calls finalize() function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return weiRaised >= (goal - (5000 * 1 ether)); } function getVaultAddress() onlyOwner public returns (address) { return vault; } } /** * @title EXTP Token * @author HamzaYasin1 - Github */ contract TradePlaceToken is MintableToken { string public constant name = "Trade PLace"; string public constant symbol = "EXTP"; uint8 public constant decimals = 18; uint256 public totalSupply = SafeMath.mul(500000000 , 1 ether); //500000000 } contract TradePlaceCrowdsale is Crowdsale, CappedCrowdsale, RefundableCrowdsale, Allocations { /** Constructor TradePlaceCrowdsale */ function TradePlaceCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, uint256 _cap, uint256 _goal, address _wallet) CappedCrowdsale(_cap) FinalizableCrowdsale() RefundableCrowdsale(_goal) Crowdsale(_startTime, _endTime, _rate, _wallet) { } /**TradePlaceToken Contract is generating from here */ function createTokenContract() internal returns (MintableToken) { return new TradePlaceToken(); } }
* @dev Must be called after crowdsale ends, to do some extra finalization work. Calls the contract's finalization function./
function finalizeCrowdsale() onlyOwner public { require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; }
975,081
[ 1, 10136, 506, 2566, 1839, 276, 492, 2377, 5349, 3930, 16, 358, 741, 2690, 2870, 727, 1588, 1440, 18, 23665, 326, 6835, 1807, 727, 1588, 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 ]
[ 1, 1, 1, 1, 1, 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, 12409, 39, 492, 2377, 5349, 1435, 1338, 5541, 1071, 288, 203, 565, 2583, 12, 5, 291, 7951, 1235, 1769, 203, 565, 2583, 12, 5332, 28362, 10663, 203, 377, 203, 565, 727, 1588, 5621, 203, 565, 16269, 1235, 5621, 203, 377, 203, 565, 29200, 1235, 273, 638, 31, 203, 565, 289, 203, 21281, 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 ]
./full_match/1/0xDE0F6e4a2B2F2cB40Ce1e10A5f3d8c7241fa6c09/sources/browser/DEFISocialLockReserves.sol
33% available after 30 days
uint256 amount = tokens.div(3);
3,042,410
[ 1, 3707, 9, 2319, 1839, 5196, 4681, 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, 3639, 2254, 5034, 3844, 273, 2430, 18, 2892, 12, 23, 1769, 565, 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 ]
// SPDX-License-Identifier: GPL-3.0-or-later // Copyright (C) 2015, 2016, 2017 Dapphub // Adapted by Ethereum Community 2021 pragma solidity 0.7.6; import "./IWETH10.sol"; import "./IERC3156FlashBorrower.sol"; interface ITransferReceiver { function onTokenTransfer(address, uint, bytes calldata) external returns (bool); } interface IApprovalReceiver { function onTokenApproval(address, uint, bytes calldata) external returns (bool); } /// @dev Wrapped Ether v10 (WETH10) is an Ether (ETH) ERC-20 wrapper. You can `deposit` ETH and obtain a WETH10 balance which can then be operated as an ERC-20 token. You can /// `withdraw` ETH from WETH10, which will then burn WETH10 token in your wallet. The amount of WETH10 token in any wallet is always identical to the /// balance of ETH deposited minus the ETH withdrawn with that specific wallet. contract WETH10 is IWETH10 { string public constant name = "Gwei Token (Forked from WETH10)"; string public constant symbol = "GWEI"; uint8 public constant decimals = 9; bytes32 public immutable CALLBACK_SUCCESS = keccak256("ERC3156FlashBorrower.onFlashLoan"); bytes32 public immutable PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); uint256 public immutable deploymentChainId; bytes32 private immutable _DOMAIN_SEPARATOR; /// @dev Records amount of WETH10 token owned by account. mapping (address => uint256) public override balanceOf; /// @dev Records current ERC2612 nonce for account. This value must be included whenever signature is generated for {permit}. /// Every successful call to {permit} increases account's nonce by one. This prevents signature from being used multiple times. mapping (address => uint256) public override nonces; /// @dev Records number of WETH10 token that account (second) will be allowed to spend on behalf of another account (first) through {transferFrom}. mapping (address => mapping (address => uint256)) public override allowance; /// @dev Current amount of flash-minted WETH10 token. uint256 public override flashMinted; constructor() { uint256 chainId; assembly {chainId := chainid()} deploymentChainId = chainId; _DOMAIN_SEPARATOR = _calculateDomainSeparator(chainId); } /// @dev Calculate the DOMAIN_SEPARATOR function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32) { return keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes("1")), chainId, address(this) ) ); } /// @dev Return the DOMAIN_SEPARATOR function DOMAIN_SEPARATOR() external view override returns (bytes32) { uint256 chainId; assembly {chainId := chainid()} return chainId == deploymentChainId ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(chainId); } /// @dev Returns the total supply of WETH10 token as the ETH held in this contract. function totalSupply() external view override returns (uint256) { return address(this).balance + flashMinted; } /// @dev Fallback, `msg.value` of ETH sent to this contract grants caller account a matching increase in WETH10 token balance. /// Emits {Transfer} event to reflect WETH10 token mint of `msg.value` from `address(0)` to caller account. receive() external payable { // _mintTo(msg.sender, msg.value); balanceOf[msg.sender] += msg.value; emit Transfer(address(0), msg.sender, msg.value); } /// @dev `msg.value` of ETH sent to this contract grants caller account a matching increase in WETH10 token balance. /// Emits {Transfer} event to reflect WETH10 token mint of `msg.value` from `address(0)` to caller account. function deposit() external override payable { // _mintTo(msg.sender, msg.value); balanceOf[msg.sender] += msg.value; emit Transfer(address(0), msg.sender, msg.value); } /// @dev `msg.value` of ETH sent to this contract grants `to` account a matching increase in WETH10 token balance. /// Emits {Transfer} event to reflect WETH10 token mint of `msg.value` from `address(0)` to `to` account. function depositTo(address to) external override payable { // _mintTo(to, msg.value); balanceOf[to] += msg.value; emit Transfer(address(0), to, msg.value); } /// @dev `msg.value` of ETH sent to this contract grants `to` account a matching increase in WETH10 token balance, /// after which a call is executed to an ERC677-compliant contract with the `data` parameter. /// Emits {Transfer} event. /// Returns boolean value indicating whether operation succeeded. /// For more information on {transferAndCall} format, see https://github.com/ethereum/EIPs/issues/677. function depositToAndCall(address to, bytes calldata data) external override payable returns (bool success) { // _mintTo(to, msg.value); balanceOf[to] += msg.value; emit Transfer(address(0), to, msg.value); return ITransferReceiver(to).onTokenTransfer(msg.sender, msg.value, data); } /// @dev Return the amount of WETH10 token that can be flash-lent. function maxFlashLoan(address token) external view override returns (uint256) { return token == address(this) ? type(uint112).max - flashMinted : 0; // Can't underflow } /// @dev Return the fee (zero) for flash lending an amount of WETH10 token. function flashFee(address token, uint256) external view override returns (uint256) { require(token == address(this), "WETH: flash mint only WETH10"); return 0; } /// @dev Flash lends `value` WETH10 token to the receiver address. /// By the end of the transaction, `value` WETH10 token will be burned from the receiver. /// The flash-minted WETH10 token is not backed by real ETH, but can be withdrawn as such up to the ETH balance of this contract. /// Arbitrary data can be passed as a bytes calldata parameter. /// Emits {Approval} event to reflect reduced allowance `value` for this contract to spend from receiver account (`receiver`), /// unless allowance is set to `type(uint256).max` /// Emits two {Transfer} events for minting and burning of the flash-minted amount. /// Returns boolean value indicating whether operation succeeded. /// Requirements: /// - `value` must be less or equal to type(uint112).max. /// - The total of all flash loans in a tx must be less or equal to type(uint112).max. function flashLoan(IERC3156FlashBorrower receiver, address token, uint256 value, bytes calldata data) external override returns (bool) { require(token == address(this), "WETH: flash mint only WETH10"); require(value <= type(uint112).max, "WETH: individual loan limit exceeded"); flashMinted = flashMinted + value; require(flashMinted <= type(uint112).max, "WETH: total loan limit exceeded"); // _mintTo(address(receiver), value); balanceOf[address(receiver)] += value; emit Transfer(address(0), address(receiver), value); require( receiver.onFlashLoan(msg.sender, address(this), value, 0, data) == CALLBACK_SUCCESS, "WETH: flash loan failed" ); // _decreaseAllowance(address(receiver), address(this), value); uint256 allowed = allowance[address(receiver)][address(this)]; if (allowed != type(uint256).max) { require(allowed >= value, "WETH: request exceeds allowance"); uint256 reduced = allowed - value; allowance[address(receiver)][address(this)] = reduced; emit Approval(address(receiver), address(this), reduced); } // _burnFrom(address(receiver), value); uint256 balance = balanceOf[address(receiver)]; require(balance >= value, "WETH: burn amount exceeds balance"); balanceOf[address(receiver)] = balance - value; emit Transfer(address(receiver), address(0), value); flashMinted = flashMinted - value; return true; } /// @dev Burn `value` WETH10 token from caller account and withdraw matching ETH to the same. /// Emits {Transfer} event to reflect WETH10 token burn of `value` to `address(0)` from caller account. /// Requirements: /// - caller account must have at least `value` balance of WETH10 token. function withdraw(uint256 value) external override { // _burnFrom(msg.sender, value); uint256 balance = balanceOf[msg.sender]; require(balance >= value, "WETH: burn amount exceeds balance"); balanceOf[msg.sender] = balance - value; emit Transfer(msg.sender, address(0), value); // _transferEther(msg.sender, value); (bool success, ) = msg.sender.call{value: value}(""); require(success, "WETH: ETH transfer failed"); } /// @dev Burn `value` WETH10 token from caller account and withdraw matching ETH to account (`to`). /// Emits {Transfer} event to reflect WETH10 token burn of `value` to `address(0)` from caller account. /// Requirements: /// - caller account must have at least `value` balance of WETH10 token. function withdrawTo(address payable to, uint256 value) external override { // _burnFrom(msg.sender, value); uint256 balance = balanceOf[msg.sender]; require(balance >= value, "WETH: burn amount exceeds balance"); balanceOf[msg.sender] = balance - value; emit Transfer(msg.sender, address(0), value); // _transferEther(to, value); (bool success, ) = to.call{value: value}(""); require(success, "WETH: ETH transfer failed"); } /// @dev Burn `value` WETH10 token from account (`from`) and withdraw matching ETH to account (`to`). /// Emits {Approval} event to reflect reduced allowance `value` for caller account to spend from account (`from`), /// unless allowance is set to `type(uint256).max` /// Emits {Transfer} event to reflect WETH10 token burn of `value` to `address(0)` from account (`from`). /// Requirements: /// - `from` account must have at least `value` balance of WETH10 token. /// - `from` account must have approved caller to spend at least `value` of WETH10 token, unless `from` and caller are the same account. function withdrawFrom(address from, address payable to, uint256 value) external override { if (from != msg.sender) { // _decreaseAllowance(from, msg.sender, value); uint256 allowed = allowance[from][msg.sender]; if (allowed != type(uint256).max) { require(allowed >= value, "WETH: request exceeds allowance"); uint256 reduced = allowed - value; allowance[from][msg.sender] = reduced; emit Approval(from, msg.sender, reduced); } } // _burnFrom(from, value); uint256 balance = balanceOf[from]; require(balance >= value, "WETH: burn amount exceeds balance"); balanceOf[from] = balance - value; emit Transfer(from, address(0), value); // _transferEther(to, value); (bool success, ) = to.call{value: value}(""); require(success, "WETH: Ether transfer failed"); } /// @dev Sets `value` as allowance of `spender` account over caller account's WETH10 token. /// Emits {Approval} event. /// Returns boolean value indicating whether operation succeeded. function approve(address spender, uint256 value) external override returns (bool) { // _approve(msg.sender, spender, value); allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /// @dev Sets `value` as allowance of `spender` account over caller account's WETH10 token, /// after which a call is executed to an ERC677-compliant contract with the `data` parameter. /// Emits {Approval} event. /// Returns boolean value indicating whether operation succeeded. /// For more information on {approveAndCall} format, see https://github.com/ethereum/EIPs/issues/677. function approveAndCall(address spender, uint256 value, bytes calldata data) external override returns (bool) { // _approve(msg.sender, spender, value); allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return IApprovalReceiver(spender).onTokenApproval(msg.sender, value, data); } /// @dev Sets `value` as allowance of `spender` account over `owner` account's WETH10 token, given `owner` account's signed approval. /// Emits {Approval} event. /// Requirements: /// - `deadline` must be timestamp in future. /// - `v`, `r` and `s` must be valid `secp256k1` signature from `owner` account over EIP712-formatted function arguments. /// - the signature must use `owner` account's current nonce (see {nonces}). /// - the signer cannot be `address(0)` and must be `owner` account. /// For more information on signature format, see https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP section]. /// WETH10 token implementation adapted from https://github.com/albertocuestacanada/ERC20Permit/blob/master/contracts/ERC20Permit.sol. function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external override { require(block.timestamp <= deadline, "WETH: Expired permit"); uint256 chainId; assembly {chainId := chainid()} bytes32 hashStruct = keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)); bytes32 hash = keccak256( abi.encodePacked( "\x19\x01", chainId == deploymentChainId ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(chainId), hashStruct)); address signer = ecrecover(hash, v, r, s); require(signer != address(0) && signer == owner, "WETH: invalid permit"); // _approve(owner, spender, value); allowance[owner][spender] = value; emit Approval(owner, spender, value); } /// @dev Moves `value` WETH10 token from caller's account to account (`to`). /// A transfer to `address(0)` triggers an ETH withdraw matching the sent WETH10 token in favor of caller. /// Emits {Transfer} event. /// Returns boolean value indicating whether operation succeeded. /// Requirements: /// - caller account must have at least `value` WETH10 token. function transfer(address to, uint256 value) external override returns (bool) { // _transferFrom(msg.sender, to, value); if (to != address(0)) { // Transfer uint256 balance = balanceOf[msg.sender]; require(balance >= value, "WETH: transfer amount exceeds balance"); balanceOf[msg.sender] = balance - value; balanceOf[to] += value; emit Transfer(msg.sender, to, value); } else { // Withdraw uint256 balance = balanceOf[msg.sender]; require(balance >= value, "WETH: burn amount exceeds balance"); balanceOf[msg.sender] = balance - value; emit Transfer(msg.sender, address(0), value); (bool success, ) = msg.sender.call{value: value}(""); require(success, "WETH: ETH transfer failed"); } return true; } /// @dev Moves `value` WETH10 token from account (`from`) to account (`to`) using allowance mechanism. /// `value` is then deducted from caller account's allowance, unless set to `type(uint256).max`. /// A transfer to `address(0)` triggers an ETH withdraw matching the sent WETH10 token in favor of caller. /// Emits {Approval} event to reflect reduced allowance `value` for caller account to spend from account (`from`), /// unless allowance is set to `type(uint256).max` /// Emits {Transfer} event. /// Returns boolean value indicating whether operation succeeded. /// Requirements: /// - `from` account must have at least `value` balance of WETH10 token. /// - `from` account must have approved caller to spend at least `value` of WETH10 token, unless `from` and caller are the same account. function transferFrom(address from, address to, uint256 value) external override returns (bool) { if (from != msg.sender) { // _decreaseAllowance(from, msg.sender, value); uint256 allowed = allowance[from][msg.sender]; if (allowed != type(uint256).max) { require(allowed >= value, "WETH: request exceeds allowance"); uint256 reduced = allowed - value; allowance[from][msg.sender] = reduced; emit Approval(from, msg.sender, reduced); } } // _transferFrom(from, to, value); if (to != address(0)) { // Transfer uint256 balance = balanceOf[from]; require(balance >= value, "WETH: transfer amount exceeds balance"); balanceOf[from] = balance - value; balanceOf[to] += value; emit Transfer(from, to, value); } else { // Withdraw uint256 balance = balanceOf[from]; require(balance >= value, "WETH: burn amount exceeds balance"); balanceOf[from] = balance - value; emit Transfer(from, address(0), value); (bool success, ) = msg.sender.call{value: value}(""); require(success, "WETH: ETH transfer failed"); } return true; } /// @dev Moves `value` WETH10 token from caller's account to account (`to`), /// after which a call is executed to an ERC677-compliant contract with the `data` parameter. /// A transfer to `address(0)` triggers an ETH withdraw matching the sent WETH10 token in favor of caller. /// Emits {Transfer} event. /// Returns boolean value indicating whether operation succeeded. /// Requirements: /// - caller account must have at least `value` WETH10 token. /// For more information on {transferAndCall} format, see https://github.com/ethereum/EIPs/issues/677. function transferAndCall(address to, uint value, bytes calldata data) external override returns (bool) { // _transferFrom(msg.sender, to, value); if (to != address(0)) { // Transfer uint256 balance = balanceOf[msg.sender]; require(balance >= value, "WETH: transfer amount exceeds balance"); balanceOf[msg.sender] = balance - value; balanceOf[to] += value; emit Transfer(msg.sender, to, value); } else { // Withdraw uint256 balance = balanceOf[msg.sender]; require(balance >= value, "WETH: burn amount exceeds balance"); balanceOf[msg.sender] = balance - value; emit Transfer(msg.sender, address(0), value); (bool success, ) = msg.sender.call{value: value}(""); require(success, "WETH: ETH transfer failed"); } return ITransferReceiver(to).onTokenTransfer(msg.sender, value, data); } }
@dev Burn `value` WETH10 token from account (`from`) and withdraw matching ETH to account (`to`). Emits {Approval} event to reflect reduced allowance `value` for caller account to spend from account (`from`), unless allowance is set to `type(uint256).max` Emits {Transfer} event to reflect WETH10 token burn of `value` to `address(0)` from account (`from`). Requirements: - `from` account must have at least `value` balance of WETH10 token. - `from` account must have approved caller to spend at least `value` of WETH10 token, unless `from` and caller are the same account. _decreaseAllowance(from, msg.sender, value);
function withdrawFrom(address from, address payable to, uint256 value) external override { if (from != msg.sender) { uint256 allowed = allowance[from][msg.sender]; if (allowed != type(uint256).max) { require(allowed >= value, "WETH: request exceeds allowance"); uint256 reduced = allowed - value; allowance[from][msg.sender] = reduced; emit Approval(from, msg.sender, reduced); } } require(balance >= value, "WETH: burn amount exceeds balance"); balanceOf[from] = balance - value; emit Transfer(from, address(0), value); require(success, "WETH: Ether transfer failed"); }
5,787,730
[ 1, 38, 321, 1375, 1132, 68, 678, 1584, 44, 2163, 1147, 628, 2236, 21863, 2080, 24065, 471, 598, 9446, 3607, 512, 2455, 358, 2236, 21863, 869, 68, 2934, 7377, 1282, 288, 23461, 97, 871, 358, 3037, 13162, 1699, 1359, 1375, 1132, 68, 364, 4894, 2236, 358, 17571, 628, 2236, 21863, 2080, 68, 3631, 3308, 1699, 1359, 353, 444, 358, 1375, 723, 12, 11890, 5034, 2934, 1896, 68, 7377, 1282, 288, 5912, 97, 871, 358, 3037, 678, 1584, 44, 2163, 1147, 18305, 434, 1375, 1132, 68, 358, 1375, 2867, 12, 20, 22025, 628, 2236, 21863, 2080, 68, 2934, 29076, 30, 282, 300, 1375, 2080, 68, 2236, 1297, 1240, 622, 4520, 1375, 1132, 68, 11013, 434, 678, 1584, 44, 2163, 1147, 18, 282, 300, 1375, 2080, 68, 2236, 1297, 1240, 20412, 4894, 358, 17571, 622, 4520, 1375, 1132, 68, 434, 678, 1584, 44, 2163, 1147, 16, 3308, 1375, 2080, 68, 471, 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, 445, 598, 9446, 1265, 12, 2867, 628, 16, 1758, 8843, 429, 358, 16, 2254, 5034, 460, 13, 3903, 3849, 288, 203, 3639, 309, 261, 2080, 480, 1234, 18, 15330, 13, 288, 203, 5411, 2254, 5034, 2935, 273, 1699, 1359, 63, 2080, 6362, 3576, 18, 15330, 15533, 203, 5411, 309, 261, 8151, 480, 618, 12, 11890, 5034, 2934, 1896, 13, 288, 203, 7734, 2583, 12, 8151, 1545, 460, 16, 315, 59, 1584, 44, 30, 590, 14399, 1699, 1359, 8863, 203, 7734, 2254, 5034, 13162, 273, 2935, 300, 460, 31, 203, 7734, 1699, 1359, 63, 2080, 6362, 3576, 18, 15330, 65, 273, 13162, 31, 203, 7734, 3626, 1716, 685, 1125, 12, 2080, 16, 1234, 18, 15330, 16, 13162, 1769, 203, 5411, 289, 203, 3639, 289, 203, 540, 203, 3639, 2583, 12, 12296, 1545, 460, 16, 315, 59, 1584, 44, 30, 18305, 3844, 14399, 11013, 8863, 203, 3639, 11013, 951, 63, 2080, 65, 273, 11013, 300, 460, 31, 203, 3639, 3626, 12279, 12, 2080, 16, 1758, 12, 20, 3631, 460, 1769, 203, 203, 3639, 2583, 12, 4768, 16, 315, 59, 1584, 44, 30, 512, 1136, 7412, 2535, 8863, 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 ]
./full_match/1/0x4B91a4CAa3B831b5B3CF88d68A69586E8FbA0462/sources/@rmrk-team/evm-contracts/contracts/RMRK/equippable/RMRKMinifiedEquippable.sol
HELPERS* @notice Used to remove a specified child token form an array using its index within said array. @dev The caller must ensure that the length of the array is valid compared to the index passed. @dev The Child struct consists of the following values: [ tokenId, contractAddress ] @param array An array od Child struct containing info about the child tokens in a given child tokens array @param index An index of the child token to remove in the accompanying array/
function _beforeTokenTransfer( address from, address to, uint256 tokenId function _afterTokenTransfer( address from, address to, uint256 tokenId function _beforeNestedTokenTransfer( address from, address to, uint256 fromTokenId, uint256 toTokenId, uint256 tokenId, bytes memory data function _afterNestedTokenTransfer( address from, address to, uint256 fromTokenId, uint256 toTokenId, uint256 tokenId, bytes memory data function _beforeAddChild( uint256 tokenId, address childAddress, uint256 childId, bytes memory data function _afterAddChild( uint256 tokenId, address childAddress, uint256 childId, bytes memory data function _beforeAcceptChild( uint256 parentId, uint256 childIndex, address childAddress, uint256 childId function _afterAcceptChild( uint256 parentId, uint256 childIndex, address childAddress, uint256 childId function _beforeTransferChild( uint256 tokenId, uint256 childIndex, address childAddress, uint256 childId, bool isPending, bytes memory data function _afterTransferChild( uint256 tokenId, uint256 childIndex, address childAddress, uint256 childId, bool isPending, bytes memory data function _removeChildByIndex(Child[] storage array, uint256 index) private { array[index] = array[array.length - 1]; array.pop(); } private _operatorApprovalsForAssets;
16,429,282
[ 1, 20264, 3194, 55, 225, 10286, 358, 1206, 279, 1269, 1151, 1147, 646, 392, 526, 1450, 2097, 770, 3470, 7864, 350, 526, 18, 225, 1021, 4894, 1297, 3387, 716, 326, 769, 434, 326, 526, 353, 923, 15843, 358, 326, 770, 2275, 18, 225, 1021, 7451, 1958, 20915, 434, 326, 3751, 924, 30, 225, 306, 1377, 1147, 548, 16, 1377, 6835, 1887, 225, 308, 225, 526, 1922, 526, 28541, 7451, 1958, 4191, 1123, 2973, 326, 1151, 2430, 316, 279, 864, 1151, 2430, 526, 225, 770, 1922, 770, 434, 326, 1151, 1147, 358, 1206, 316, 326, 1721, 16840, 310, 526, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 203, 565, 445, 389, 5771, 8649, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 628, 1345, 548, 16, 203, 3639, 2254, 5034, 358, 1345, 548, 16, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 1731, 3778, 501, 203, 203, 565, 445, 389, 5205, 8649, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 628, 1345, 548, 16, 203, 3639, 2254, 5034, 358, 1345, 548, 16, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 1731, 3778, 501, 203, 203, 565, 445, 389, 5771, 986, 1763, 12, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 1758, 1151, 1887, 16, 203, 3639, 2254, 5034, 1151, 548, 16, 203, 3639, 1731, 3778, 501, 203, 203, 565, 445, 389, 5205, 986, 1763, 12, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 1758, 1151, 1887, 16, 203, 3639, 2254, 5034, 1151, 548, 16, 203, 3639, 1731, 3778, 501, 203, 203, 565, 445, 389, 5771, 5933, 1763, 12, 203, 3639, 2254, 5034, 11582, 16, 203, 3639, 2254, 5034, 1151, 1016, 16, 203, 3639, 1758, 1151, 1887, 16, 203, 3639, 2254, 5034, 1151, 548, 203, 203, 565, 445, 389, 5205, 5933, 1763, 2 ]
./full_match/80001/0xf4f036a18961f7Ab421145bac1f27f0F73BFb643/sources/contracts/Role.sol
* @dev changes the default role of the company @param _defaultRoleName (string)/
function changeDefaultRole( string memory _defaultRoleName ) public onlyRole(Privileges.getCanChangeDefaultRole()) returns (string memory) { address companyAddress = Company .returnCompanyAddressOrCompanyAddressFromUser(msg.sender); require(companyAddress != address(0x00), "Company not found"); _checkStringsEqual(getRoleName(_defaultRoleName), _defaultRoleName, "Role not found"); Company.setCompanyDefaultRole(companyAddress, _defaultRoleName); return "Default role changed"; }
5,596,802
[ 1, 6329, 326, 805, 2478, 434, 326, 9395, 225, 389, 1886, 31278, 261, 1080, 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, 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, 2549, 1868, 2996, 12, 203, 3639, 533, 3778, 389, 1886, 31278, 203, 565, 262, 203, 3639, 1071, 203, 3639, 1338, 2996, 12, 27692, 18, 588, 2568, 3043, 1868, 2996, 10756, 203, 3639, 1135, 261, 1080, 3778, 13, 203, 565, 288, 203, 3639, 1758, 9395, 1887, 273, 26782, 203, 5411, 263, 2463, 12627, 1887, 1162, 12627, 1887, 1265, 1299, 12, 3576, 18, 15330, 1769, 203, 3639, 2583, 12, 16840, 1887, 480, 1758, 12, 20, 92, 713, 3631, 315, 12627, 486, 1392, 8863, 203, 3639, 389, 1893, 7957, 5812, 12, 588, 31278, 24899, 1886, 31278, 3631, 389, 1886, 31278, 16, 315, 2996, 486, 1392, 8863, 203, 203, 3639, 26782, 18, 542, 12627, 1868, 2996, 12, 16840, 1887, 16, 389, 1886, 31278, 1769, 203, 203, 3639, 327, 315, 1868, 2478, 3550, 14432, 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 ]
./full_match/1/0x7D756391f83E5646E22aca21d6f6945f13f13BBC/sources/contracts/CSD4percent.sol
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations. Example from CappedCrowdsale.sol's _preValidatePurchase method: super._preValidatePurchase(beneficiary, weiAmount); require(weiRaised().add(weiAmount) <= cap); @param beneficiary Address performing the token purchase @param weiAmount Value in wei involved in the purchase/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address"); require(weiAmount != 0, "Crowdsale: weiAmount is 0"); }
4,909,033
[ 1, 4354, 434, 392, 6935, 23701, 18, 2672, 2583, 6317, 358, 15226, 919, 1347, 4636, 854, 486, 5100, 18, 2672, 1375, 9565, 68, 316, 20092, 716, 6811, 628, 385, 492, 2377, 5349, 358, 2133, 3675, 20808, 18, 5090, 628, 11200, 1845, 39, 492, 2377, 5349, 18, 18281, 1807, 389, 1484, 4270, 23164, 707, 30, 377, 2240, 6315, 1484, 4270, 23164, 12, 70, 4009, 74, 14463, 814, 16, 732, 77, 6275, 1769, 377, 2583, 12, 1814, 77, 12649, 5918, 7675, 1289, 12, 1814, 77, 6275, 13, 1648, 3523, 1769, 225, 27641, 74, 14463, 814, 5267, 14928, 326, 1147, 23701, 225, 732, 77, 6275, 1445, 316, 732, 77, 24589, 316, 326, 23701, 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, 565, 445, 389, 1484, 4270, 23164, 12, 2867, 27641, 74, 14463, 814, 16, 2254, 5034, 732, 77, 6275, 13, 2713, 1476, 288, 203, 3639, 2583, 12, 70, 4009, 74, 14463, 814, 480, 1758, 12, 20, 3631, 315, 39, 492, 2377, 5349, 30, 27641, 74, 14463, 814, 353, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 1814, 77, 6275, 480, 374, 16, 315, 39, 492, 2377, 5349, 30, 732, 77, 6275, 353, 374, 8863, 203, 565, 289, 203, 7010, 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 ]
/* * CHEEMS INU Supply: 1 000 000 000 000 Max Wallet: 10 000 000 000 at launch then 20 000 000 000 Max TX: 2 500 000 000 at launch then 10 000 000 000 Tax: 8% Buy 10% Sell SPLIT: 20% LP 50% BUYBACKS 30% DEVELOPMENT/MARKETING DO NOT BUY UNTIL CONTRACT ADDRESS IS POSTED IN TELEGRAM https://t.me/cheemstokenbsc * */ pragma solidity =0.8.9; // SPDX-License-Identifier: UNLICENSED interface IBEP20 { function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); function symbol() external view returns (string memory); function name() external view returns (string memory); function getOwner() external view returns (address); 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); } interface IuniswapV2ERC20 { 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; } interface IuniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IuniswapV2Router01 { 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 factory() external pure returns (address); function WETH() external pure returns (address); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getamountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getamountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getamountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getamountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IuniswapV2Router02 is IuniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } /** * @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 { 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 = msg.sender; _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() == msg.sender, "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() external 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) external onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // 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); } } } } /** * @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)); } } //Cheems Inu Eth Contract ///////////// contract CheemsInu is IBEP20, Ownable { using Address for address; using EnumerableSet for EnumerableSet.AddressSet; event ContractChanged(uint256 indexed value); event ContractChangedBool(bool indexed value); event ContractChangedAddress(address indexed value); event antiBotBan(address indexed value); mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => uint256) private _buyLock; mapping ( address => bool ) public blackList; EnumerableSet.AddressSet private _excluded; //Token Info string private constant _name = 'CHEEMSINU'; string private constant _symbol = 'CINU'; uint8 private constant _decimals = 9; uint256 public constant InitialSupply= 4138058057 * 10**_decimals; //Amount to Swap variable (0.2%) uint256 currentAmountToSwap = 8276116 * 10**_decimals; //Divider for the MaxBalance based on circulating Supply (0.25%) uint16 public constant BalanceLimitDivider=400; //Divider for sellLimit based on circulating Supply (0.25%) uint16 public constant SellLimitDivider=400; //Buyers get locked for MaxBuyLockTime (put in seconds, works better especially if changing later) so they can't buy repeatedly uint16 public constant MaxBuyLockTime= 9 seconds; //The time Liquidity gets locked at start and prolonged once it gets released uint256 private constant DefaultLiquidityLockTime= 1800; //DevWallets address public TeamWallet=payable(0x78eEa15417FeADEF60414F9FDf7886E72e29FA68); address public BuyBackWallet=payable(0x7bc10AF41bD6CA5ba88097d35d0Eb85350E49Ba7); //Uniswap router (Main & Testnet) address private uniswapV2Router=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; //variables that track balanceLimit and sellLimit, //can be updated based on circulating supply and Sell- and BalanceLimitDividers uint256 private _circulatingSupply =InitialSupply; uint256 public balanceLimit = _circulatingSupply; uint256 public sellLimit = _circulatingSupply; uint256 private antiWhale = 8276116 * 10**_decimals; // (0.2%) //Used for anti-bot autoblacklist uint256 private tradingEnabledAt; //DO NOT CHANGE, THIS IS FOR HOLDING A TIMESTAMP uint256 private autoBanTime = 90; // Set to the amount of time in seconds after enable trading you want addresses to be auto blacklisted if they buy/sell/transfer in this time. uint256 private enableAutoBlacklist = 1; //Leave 1 if using, set to 0 if not using. //Tracks the current Taxes, different Taxes can be applied for buy/sell/transfer uint8 private _buyTax; uint8 private _sellTax; uint8 private _transferTax; uint8 private _burnTax; uint8 private _liquidityTax; uint8 private _marketingTax; address private _uniswapV2PairAddress; IuniswapV2Router02 private _uniswapV2Router; //Constructor/////////// constructor () { //contract creator gets 90% of the token to create LP-Pair uint256 deployerBalance=_circulatingSupply; _balances[msg.sender] = deployerBalance; emit Transfer(address(0), msg.sender, deployerBalance); // Uniswap Router _uniswapV2Router = IuniswapV2Router02(uniswapV2Router); //Creates a Uniswap Pair _uniswapV2PairAddress = IuniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); //Sets Buy/Sell limits balanceLimit=InitialSupply/BalanceLimitDivider; sellLimit=InitialSupply/SellLimitDivider; //Sets buyLockTime buyLockTime=0; //Set Starting Taxes _buyTax=8; _sellTax=10; _transferTax=10; _burnTax=0; _liquidityTax=20; _marketingTax=80; //Team wallets and deployer are excluded from Taxes _excluded.add(TeamWallet); _excluded.add(BuyBackWallet); _excluded.add(msg.sender); } //Transfer functionality/// //transfer function, every transfer runs through this function function _transfer(address sender, address recipient, uint256 amount) private{ require(sender != address(0), "Transfer from zero"); require(recipient != address(0), "Transfer to zero"); //Manually Excluded adresses are transfering tax and lock free bool isExcluded = (_excluded.contains(sender) || _excluded.contains(recipient)); //Transactions from and to the contract are always tax and lock free bool isContractTransfer=(sender==address(this) || recipient==address(this)); //transfers between UniswapRouter and UniswapPair are tax and lock free address uniswapV2Router=address(_uniswapV2Router); bool isLiquidityTransfer = ((sender == _uniswapV2PairAddress && recipient == uniswapV2Router) || (recipient == _uniswapV2PairAddress && sender == uniswapV2Router)); //differentiate between buy/sell/transfer to apply different taxes/restrictions bool isBuy=sender==_uniswapV2PairAddress|| sender == uniswapV2Router; bool isSell=recipient==_uniswapV2PairAddress|| recipient == uniswapV2Router; //Pick transfer if(isContractTransfer || isLiquidityTransfer || isExcluded){ _feelessTransfer(sender, recipient, amount); } else{ //once trading is enabled, it can't be turned off again require(tradingEnabled,"trading not yet enabled"); _taxedTransfer(sender,recipient,amount,isBuy,isSell); } } //applies taxes, checks for limits, locks generates autoLP function _taxedTransfer(address sender, address recipient, uint256 amount,bool isBuy,bool isSell) private{ uint256 recipientBalance = _balances[recipient]; uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "Transfer exceeds balance"); uint8 tax; if(isSell){ //Sells can't exceed the sell limit require(amount<=sellLimit,"Dump protection"); require(blackList[sender] == false, "Address blacklisted!"); if (block.timestamp <= tradingEnabledAt + autoBanTime && enableAutoBlacklist == 1) { blackList[sender] = true; emit antiBotBan(sender); } tax=_sellTax; } else if(isBuy){ //Checks If the recipient balance(excluding Taxes) would exceed Balance Limit require(recipientBalance+amount<=balanceLimit,"whale protection"); require(amount <= antiWhale,"Tx amount exceeding max buy amount"); require(blackList[recipient] == false, "Address blacklisted!"); if (block.timestamp <= tradingEnabledAt + autoBanTime && enableAutoBlacklist == 1) { blackList[recipient] = true; emit antiBotBan(recipient); } tax=_buyTax; } else {//Transfer //Checks If the recipient balance(excluding Taxes) would exceed Balance Limit require(blackList[sender] == false, "Sender address blacklisted!"); require(blackList[recipient] == false, "Recipient address blacklisted!"); require(recipientBalance+amount<=balanceLimit,"whale protection"); if (block.timestamp <= tradingEnabledAt + autoBanTime && enableAutoBlacklist == 1) { blackList[sender] = true; emit antiBotBan(sender); } tax=_transferTax; } //Swapping AutoLP and MarketingETH is only possible if sender is not uniswapV2 pair, //if its not manually disabled, if its not already swapping and if its a Sell to avoid // people from causing a large price impact from repeatedly transfering when theres a large backlog of Tokens if((sender!=_uniswapV2PairAddress)&&(!manualConversion)&&(!_isSwappingContractModifier)&&isSell) _swapContractToken(); //Calculates the exact token amount for each tax uint256 tokensToBeBurnt=_calculateFee(amount, tax, _burnTax); uint256 contractToken=_calculateFee(amount, tax, _marketingTax+_liquidityTax); //Subtract the Taxed Tokens from the amount uint256 taxedAmount=amount-(tokensToBeBurnt + contractToken); //Removes token _removeToken(sender,amount); //Adds the taxed tokens to the contract wallet _balances[address(this)] += contractToken; //Burns tokens _circulatingSupply-=tokensToBeBurnt; //Adds token _addToken(recipient, taxedAmount); emit Transfer(sender,recipient,taxedAmount); } //Feeless transfer only transfers function _feelessTransfer(address sender, address recipient, uint256 amount) private{ uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "Transfer exceeds balance"); //Removes token _removeToken(sender,amount); //Adds token _addToken(recipient, amount); emit Transfer(sender,recipient,amount); } //Calculates the token that should be taxed function _calculateFee(uint256 amount, uint8 tax, uint8 taxPercent) private pure returns (uint256) { return (amount*tax*taxPercent) / 10000; } //balance that is claimable by the team uint256 public marketingBalance; //adds Token to balances function _addToken(address addr, uint256 amount) private { //the amount of token after transfer uint256 newAmount=_balances[addr]+amount; //sets newBalance _balances[addr]=newAmount; } //removes Token function _removeToken(address addr, uint256 amount) private { //the amount of token after transfer uint256 newAmount=_balances[addr]-amount; //sets newBalance _balances[addr]=newAmount; } //Swap Contract Tokens////////////////////////////////////////////////////////////////////////////////// //tracks auto generated ETH, useful for ticker etc uint256 public totalLPETH; //Locks the swap if already swapping bool private _isSwappingContractModifier; modifier lockTheSwap { _isSwappingContractModifier = true; _; _isSwappingContractModifier = false; } //swaps the token on the contract for Marketing ETH and LP Token. //always swaps the sellLimit of token to avoid a large price impact function _swapContractToken() private lockTheSwap{ uint256 contractBalance=_balances[address(this)]; uint16 totalTax=_marketingTax+_liquidityTax; uint256 tokenToSwap = currentAmountToSwap; //only swap if contractBalance is larger than tokenToSwap, and totalTax is unequal to 0 if(contractBalance<tokenToSwap||totalTax==0){ return; } //splits the token in TokenForLiquidity and tokenForMarketing uint256 tokenForLiquidity=(tokenToSwap*_liquidityTax)/totalTax; uint256 tokenForMarketing= tokenToSwap-tokenForLiquidity; //splits tokenForLiquidity in 2 halves uint256 liqToken=tokenForLiquidity/2; uint256 liqETHToken=tokenForLiquidity-liqToken; //swaps marktetingToken and the liquidity token half for ETH uint256 swapToken=liqETHToken+tokenForMarketing; //Gets the initial ETH balance uint256 initialETHBalance = address(this).balance; _swapTokenForETH(swapToken); uint256 newETH=(address(this).balance - initialETHBalance); //calculates the amount of ETH belonging to the LP-Pair and converts them to LP uint256 liqETH = (newETH*liqETHToken)/swapToken; _addLiquidity(liqToken, liqETH); //Get the ETH balance after LP generation to get the //exact amount of token left for marketing uint256 distributeETH=(address(this).balance - initialETHBalance); //distributes remaining BETHNB to Marketing marketingBalance+=distributeETH; } //swaps tokens on the contract for ETH function _swapTokenForETH(uint256 amount) private { _approve(address(this), address(_uniswapV2Router), amount); address[] memory path = new address[](2); path[0] = address(this); path[1] = _uniswapV2Router.WETH(); _uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( amount, 0, path, address(this), block.timestamp ); } //Adds Liquidity directly to the contract where LP are locked(unlike safemoon forks, that transfer it to the owner) function _addLiquidity(uint256 tokenamount, uint256 ethamount) private returns (uint256 tAmountSent, uint256 ethAmountSent) { totalLPETH+=ethamount; uint256 minETH = (ethamount*75) / 100; uint256 minTokens = (tokenamount*75) / 100; _approve(address(this), address(_uniswapV2Router), tokenamount); _uniswapV2Router.addLiquidityETH{value: ethamount}( address(this), tokenamount, minTokens, minETH, address(this), block.timestamp ); tAmountSent = tokenamount; ethAmountSent = ethamount; return (tAmountSent, ethAmountSent); } //public functions ///////////////////////////////////////////////////////////////////////////////////// function getLiquidityReleaseTimeInSeconds() external view returns (uint256){ if(block.timestamp<_liquidityUnlockTime){ return _liquidityUnlockTime-block.timestamp; } return 0; } function getBurnedTokens() external view returns(uint256){ return (InitialSupply-_circulatingSupply)/10**_decimals; } function getLimits() external view returns(uint256 balance, uint256 sell){ return(balanceLimit/10**_decimals, sellLimit/10**_decimals); } function getTaxes() external view returns(uint256 burnTax,uint256 liquidityTax, uint256 marketingTax, uint256 buyTax, uint256 sellTax, uint256 transferTax){ return (_burnTax,_liquidityTax,_marketingTax,_buyTax,_sellTax,_transferTax); } //How long is a given address still locked from buying function getAddressBuyLockTimeInSeconds(address AddressToCheck) external view returns (uint256){ uint256 lockTime=_buyLock[AddressToCheck]; if(lockTime<=block.timestamp) { return 0; } return lockTime-block.timestamp; } function getBuyLockTimeInSeconds() external view returns(uint256){ return buyLockTime; } //Functions every wallet can call //Resets buy lock of caller to the default buyLockTime should something go very wrong function AddressResetBuyLock() external{ _buyLock[msg.sender]=block.timestamp+buyLockTime; } //Settings////////////////////////////////////////////////////////////////////////////////////////////// bool public buyLockDisabled; uint256 public buyLockTime; bool public manualConversion; function TeamWithdrawALLMarketingETH() external onlyOwner{ uint256 amount=marketingBalance; marketingBalance=0; payable(TeamWallet).transfer((amount*37) / 100); payable(BuyBackWallet).transfer((amount-(amount*37) / 100)); emit Transfer(address(this), TeamWallet, (amount*37) / 100); emit Transfer(address(this), BuyBackWallet, (amount-(amount*37) / 100)); } function TeamWithdrawXMarketingETH(uint256 amount) external onlyOwner{ require(amount<=marketingBalance, "Error: Amount greater than available balance."); marketingBalance-=amount; payable(TeamWallet).transfer((amount*37) / 100); payable(BuyBackWallet).transfer((amount-(amount*37) / 100)); emit Transfer(address(this), TeamWallet, (amount*37) / 100); emit Transfer(address(this), BuyBackWallet, (amount-(amount*37) / 100)); } //switches autoLiquidity and marketing ETH generation during transfers function TeamSwitchManualETHConversion(bool manual) external onlyOwner{ manualConversion=manual; emit ContractChangedBool(manualConversion); } function TeamChangeAntiWhale(uint256 newAntiWhale) external onlyOwner{ antiWhale=newAntiWhale * 10**_decimals; emit ContractChanged(antiWhale); } function TeamChangeTeamWallet(address newTeamWallet) external onlyOwner{ require(newTeamWallet != address(0), "Error: Cannot be 0 address."); TeamWallet=payable(newTeamWallet); emit ContractChangedAddress(TeamWallet); } function TeamChangeBuyBackWallet(address newBuyBackWallet) external onlyOwner{ require(newBuyBackWallet != address(0), "Error: Cannot be 0 address."); BuyBackWallet=payable(newBuyBackWallet); emit ContractChangedAddress(BuyBackWallet); } //Disables the timeLock after buying for everyone function TeamDisableBuyLock(bool disabled) external onlyOwner{ buyLockDisabled=disabled; emit ContractChangedBool(buyLockDisabled); } //Sets BuyLockTime, needs to be lower than MaxBuyLockTime function TeamSetBuyLockTime(uint256 buyLockSeconds) external onlyOwner{ require(buyLockSeconds<=MaxBuyLockTime,"Buy Lock time too high"); buyLockTime=buyLockSeconds; emit ContractChanged(buyLockTime); } //Allows CA owner to change how much the contract sells to prevent massive contract sells as the token grows. function TeamUpdateAmountToSwap(uint256 newSwapAmount) external onlyOwner{ currentAmountToSwap = newSwapAmount; emit ContractChanged(currentAmountToSwap); } //Allows wallet exclusion to be added after launch function addWalletExclusion(address exclusionAdd) external onlyOwner{ _excluded.add(exclusionAdd); emit ContractChangedAddress(exclusionAdd); } //Allows you to remove wallet exclusions after launch function removeWalletExclusion(address exclusionRemove) external onlyOwner{ _excluded.remove(exclusionRemove); emit ContractChangedAddress(exclusionRemove); } //Adds address to blacklist and prevents sells, buys or transfers. function addAddressToBlacklist(address blacklistedAddress) external onlyOwner { blackList[ blacklistedAddress ] = true; emit ContractChangedAddress(blacklistedAddress); } function blacklistAddressArray ( address [] memory _address ) public onlyOwner { for ( uint256 x=0; x< _address.length ; x++ ){ blackList[_address[x]] = true; } } //Check if address is blacklisted (can be called by anyone) function checkAddressBlacklist(address submittedAddress) external view returns (bool isBlacklisted) { if (blackList[submittedAddress] == true) { isBlacklisted = true; return isBlacklisted; } if (blackList[submittedAddress] == false) { isBlacklisted = false; return isBlacklisted; } } //Remove address from blacklist and allow sells, buys or transfers. function removeAddressFromBlacklist(address blacklistedAddress) external onlyOwner { blackList[ blacklistedAddress ] = false; emit ContractChangedAddress(blacklistedAddress); } //Sets Taxes, is limited by MaxTax(20%) to make it impossible to create honeypot function TeamSetTaxes(uint8 burnTaxes, uint8 liquidityTaxes, uint8 marketingTaxes, uint8 buyTax, uint8 sellTax, uint8 transferTax) external onlyOwner{ uint8 totalTax=burnTaxes+liquidityTaxes+marketingTaxes; require(totalTax==100, "burn+liq+marketing needs to equal 100%"); require(buyTax <= 20, "Error: Honeypot prevention prevents buyTax from exceeding 20."); require(sellTax <= 20, "Error: Honeypot prevention prevents sellTax from exceeding 20."); require(transferTax <= 20, "Error: Honeypot prevention prevents transferTax from exceeding 20."); _burnTax=burnTaxes; _liquidityTax=liquidityTaxes; _marketingTax=marketingTaxes; _buyTax=buyTax; _sellTax=sellTax; _transferTax=transferTax; emit ContractChanged(_burnTax); emit ContractChanged(_liquidityTax); emit ContractChanged(_buyTax); emit ContractChanged(_sellTax); emit ContractChanged(_transferTax); } //manually converts contract token to LP function TeamCreateLPandETH() external onlyOwner{ _swapContractToken(); } function teamUpdateUniswapRouter(address newRouter) external onlyOwner { require(newRouter != address(0), "Error: Cannot be 0 address."); uniswapV2Router=newRouter; emit ContractChangedAddress(newRouter); } //Limits need to be at least target, to avoid setting value to 0(avoid potential Honeypot) function TeamUpdateLimits(uint256 newBalanceLimit, uint256 newSellLimit) external onlyOwner{ //SellLimit needs to be below 1% to avoid a Large Price impact when generating auto LP require(newSellLimit<_circulatingSupply/100, "Error: New sell limit above 1% of circulating supply."); //Adds decimals to limits newBalanceLimit=newBalanceLimit*10**_decimals; newSellLimit=newSellLimit*10**_decimals; //Calculates the target Limits based on supply uint256 targetBalanceLimit=_circulatingSupply/BalanceLimitDivider; uint256 targetSellLimit=_circulatingSupply/SellLimitDivider; require((newBalanceLimit>=targetBalanceLimit), "newBalanceLimit needs to be at least target"); require((newSellLimit>=targetSellLimit), "newSellLimit needs to be at least target"); balanceLimit = newBalanceLimit; sellLimit = newSellLimit; emit ContractChanged(balanceLimit); emit ContractChanged(sellLimit); } //Setup Functions/////////////////////////////////////////////////////////////////////////////////////// bool public tradingEnabled; address private _liquidityTokenAddress; //Enables trading for everyone function SetupEnableTrading() external onlyOwner{ tradingEnabled=true; tradingEnabledAt=block.timestamp; } //Sets up the LP-Token Address required for LP Release function SetupLiquidityTokenAddress(address liquidityTokenAddress) external onlyOwner{ require(liquidityTokenAddress != address(0), "Error: Cannot be 0 address."); _liquidityTokenAddress=liquidityTokenAddress; } //Liquidity Lock//////////////////////////////////////////////////////////////////////////////////////// //the timestamp when Liquidity unlocks uint256 private _liquidityUnlockTime; //Adds time to LP lock in seconds. function TeamProlongLiquidityLockInSeconds(uint256 secondsUntilUnlock) external onlyOwner{ _prolongLiquidityLock(secondsUntilUnlock+block.timestamp); emit ContractChanged(secondsUntilUnlock+block.timestamp); } //Adds time to LP lock based on set time. function _prolongLiquidityLock(uint256 newUnlockTime) private{ // require new unlock time to be longer than old one require(newUnlockTime>_liquidityUnlockTime, "Error: New unlock time is shorter than old one."); _liquidityUnlockTime=newUnlockTime; emit ContractChanged(_liquidityUnlockTime); } //Release Liquidity Tokens once unlock time is over function TeamReleaseLiquidity() external onlyOwner returns (address tWAddress, uint256 amountSent) { //Only callable if liquidity Unlock time is over require(block.timestamp >= _liquidityUnlockTime, "Not yet unlocked"); IuniswapV2ERC20 liquidityToken = IuniswapV2ERC20(_liquidityTokenAddress); uint256 amount = liquidityToken.balanceOf(address(this)); //Liquidity release if something goes wrong at start liquidityToken.transfer(TeamWallet, amount); emit Transfer(address(this), TeamWallet, amount); tWAddress = TeamWallet; amountSent = amount; return (tWAddress, amountSent); } //Removes Liquidity once unlock Time is over, function TeamRemoveLiquidity() external onlyOwner returns (uint256 newBalance) { //Only callable if liquidity Unlock time is over require(block.timestamp >= _liquidityUnlockTime, "Not yet unlocked"); IuniswapV2ERC20 liquidityToken = IuniswapV2ERC20(_liquidityTokenAddress); uint256 amount = liquidityToken.balanceOf(address(this)); liquidityToken.approve(address(_uniswapV2Router),amount); //Removes Liquidity and adds it to marketing Balance uint256 initialETHBalance = address(this).balance; _uniswapV2Router.removeLiquidityETHSupportingFeeOnTransferTokens( address(this), amount, (amount*75) / 100, (amount*75) / 100, address(this), block.timestamp ); uint256 newETHBalance = address(this).balance-initialETHBalance; marketingBalance+=newETHBalance; newBalance=newETHBalance; return newBalance; } //Releases all remaining ETH on the contract wallet, so ETH wont be burned function TeamRemoveRemainingETH() external onlyOwner{ require(block.timestamp >= _liquidityUnlockTime, "Not yet unlocked"); (bool sent,) =TeamWallet.call{value: (address(this).balance)}(""); require(sent, "Error: Not sent."); } //////////////////////////////////////////////////////////////////////////////////////////////////////// //external////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// receive() external payable {} fallback() external payable {} // IBEP20 function getOwner() external view override returns (address) { return owner(); } function name() external pure override returns (string memory) { return _name; } function symbol() external pure override returns (string memory) { return _symbol; } function decimals() external pure override returns (uint8) { return _decimals; } function totalSupply() external view override returns (uint256) { return _circulatingSupply; } function balanceOf(address account) external view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address _owner, address spender) external view override returns (uint256) { return _allowances[_owner][spender]; } function approve(address spender, uint256 amount) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "Approve from zero"); require(spender != address(0), "Approve to zero"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][msg.sender]; require(currentAllowance >= amount, "Transfer > allowance"); _approve(sender, msg.sender, currentAllowance - amount); return true; } // IBEP20 - Helpers function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { uint256 currentAllowance = _allowances[msg.sender][spender]; require(currentAllowance >= subtractedValue, "<0 allowance"); _approve(msg.sender, spender, currentAllowance - subtractedValue); return true; } }
transfer function, every transfer runs through this functionManually Excluded adresses are transfering tax and lock freeTransactions from and to the contract are always tax and lock freetransfers between UniswapRouter and UniswapPair are tax and lock freedifferentiate between buy/sell/transfer to apply different taxes/restrictionsPick transferonce trading is enabled, it can't be turned off again
function _transfer(address sender, address recipient, uint256 amount) private{ require(sender != address(0), "Transfer from zero"); require(recipient != address(0), "Transfer to zero"); bool isExcluded = (_excluded.contains(sender) || _excluded.contains(recipient)); bool isContractTransfer=(sender==address(this) || recipient==address(this)); address uniswapV2Router=address(_uniswapV2Router); bool isLiquidityTransfer = ((sender == _uniswapV2PairAddress && recipient == uniswapV2Router) || (recipient == _uniswapV2PairAddress && sender == uniswapV2Router)); bool isBuy=sender==_uniswapV2PairAddress|| sender == uniswapV2Router; bool isSell=recipient==_uniswapV2PairAddress|| recipient == uniswapV2Router; if(isContractTransfer || isLiquidityTransfer || isExcluded){ _feelessTransfer(sender, recipient, amount); } else{ require(tradingEnabled,"trading not yet enabled"); _taxedTransfer(sender,recipient,amount,isBuy,isSell); } }
138,017
[ 1, 13866, 445, 16, 3614, 7412, 7597, 3059, 333, 445, 5669, 3452, 1312, 7908, 1261, 15807, 854, 7412, 310, 5320, 471, 2176, 4843, 14186, 628, 471, 358, 326, 6835, 854, 3712, 5320, 471, 2176, 284, 9015, 28001, 18881, 3086, 1351, 291, 91, 438, 8259, 471, 1351, 291, 91, 438, 4154, 854, 5320, 471, 2176, 28004, 430, 3518, 3840, 3086, 30143, 19, 87, 1165, 19, 13866, 358, 2230, 3775, 5320, 281, 19, 23954, 87, 17968, 7412, 8243, 1284, 7459, 353, 3696, 16, 518, 848, 1404, 506, 21826, 3397, 3382, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 13866, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 3238, 95, 203, 3639, 2583, 12, 15330, 480, 1758, 12, 20, 3631, 315, 5912, 628, 3634, 8863, 203, 3639, 2583, 12, 20367, 480, 1758, 12, 20, 3631, 315, 5912, 358, 3634, 8863, 203, 540, 203, 3639, 1426, 353, 16461, 273, 261, 67, 24602, 18, 12298, 12, 15330, 13, 747, 389, 24602, 18, 12298, 12, 20367, 10019, 203, 540, 203, 3639, 1426, 353, 8924, 5912, 28657, 15330, 631, 2867, 12, 2211, 13, 747, 8027, 631, 2867, 12, 2211, 10019, 203, 540, 203, 3639, 1758, 640, 291, 91, 438, 58, 22, 8259, 33, 2867, 24899, 318, 291, 91, 438, 58, 22, 8259, 1769, 203, 3639, 1426, 28601, 18988, 24237, 5912, 273, 14015, 15330, 422, 389, 318, 291, 91, 438, 58, 22, 4154, 1887, 597, 8027, 422, 640, 291, 91, 438, 58, 22, 8259, 13, 7010, 3639, 747, 261, 20367, 422, 389, 318, 291, 91, 438, 58, 22, 4154, 1887, 597, 5793, 422, 640, 291, 91, 438, 58, 22, 8259, 10019, 203, 203, 3639, 1426, 27057, 9835, 33, 15330, 631, 67, 318, 291, 91, 438, 58, 22, 4154, 1887, 20081, 5793, 422, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 3639, 1426, 11604, 1165, 33, 20367, 631, 67, 318, 291, 91, 438, 58, 22, 4154, 1887, 20081, 8027, 422, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 203, 3639, 309, 12, 291, 8924, 5912, 747, 28601, 18988, 24237, 5912, 747, 353, 16461, 15329, 203, 5411, 389, 3030, 12617, 5912, 12, 2 ]
pragma solidity ^0.5.13; import "./SKUFactory.sol"; /** * @title StockRoom * @notice Main contract for reference data side of the In-game Pro Shop System */ contract StockRoom is SKUFactory { /** * @notice Set the address of the FiatContract contract */ function setFiatContractAddress(address _address) external whenPaused onlySysAdmin { FiatContractInterface candidateContract = FiatContractInterface(_address); // Verify that we have the appropriate address require(candidateContract.updatedAt(0) >= 0); // Set the new contract address fiatContract = candidateContract; } // @notice confirm this is a StockRoom contract function isStockRoom() external pure returns (bool) { return true; } // @notice get an item's price in Ether function getPriceInEther(uint256 _skuId) external view returns (uint256) { SKU memory sku = skus[_skuId]; uint256 quote = getQuote(shops[sku.shopId].fiat); return quote * sku.price; } // @notice convert an Ether amount to a Shop's fiat currency function convertEtherToShopFiat(uint256 _shopId, uint256 _amount) external view returns (uint256) { uint256 quote = getQuote(shops[_shopId].fiat); return _amount.div(quote); } // @notice convert an Ether amount to the Franchise's fiat currency function convertEtherToFranchiseFiat(uint256 _amount) external view returns (uint256) { uint256 quote = getQuote("USD"); return _amount.div(quote); } // @notice get a quote for Ether in the given fiat currency function getQuote(string memory _fiat) private view returns (uint256) { bytes32 fiat = keccak256(abi.encodePacked(_fiat)); uint256 quote; if (fiat == keccak256("USD")) { quote = fiatContract.USD(0); } else if (fiat == keccak256("EUR")) { quote = fiatContract.EUR(0); } else if (fiat == keccak256("GBP")) { quote = fiatContract.GBP(0); } else { quote = fiatContract.USD(0); // franchise } return quote; } // @notice confirm whether an item can be minted based on limit and current item count function canMintItem(uint256 _skuId, uint256 _itemCount) external view returns (bool) { return (!skus[_skuId].limited || (_itemCount < skus[_skuId].limit)); } // @notice Get the list of SKU Ids associated with a given SKUType function getSKUTypeSKUIds(uint256 _skuTypeId) external view returns (uint[] memory) { return skuTypeSKUs[_skuTypeId]; } // @notice Get the list of SKU Ids associated with a given Shop function getSKUIds(uint256 _shopId) external view returns (uint[] memory) { return shopSKUs[_shopId]; } // @notice Get a SKU's properties by ID function getSKU(uint256 _skuId) external view returns (uint256, uint256, uint256, uint256, string memory, string memory, bool, bool, uint256) { require(_skuId < skus.length); SKU memory sku = skus[_skuId]; return ( sku.shopId, sku.skuId, sku.skuTypeId, sku.price, sku.name, sku.description, sku.consumable, sku.limited, sku.limit ); } // @notice Get the list of SKU Type Ids associated with a given Shop function getSKUTypeIds(uint256 _shopId) external view returns (uint[] memory) { return shopSKUTypes[_shopId]; } // @notice Get a SKUTypes properties by ID function getSKUType(uint256 _skuTypeId) external view returns (uint256, uint256, string memory, string memory) { require(_skuTypeId < skuTypes.length); SKUType memory skuType = skuTypes[_skuTypeId]; return ( skuType.shopId, skuType.skuTypeId, skuType.name, skuType.description ); } // @notice Get the list of Shop Ids associated with a given Owner function getShopIds(address _owner) external view returns (uint[] memory) { return ownedShops[_owner]; } // @notice Get a Shop's properties by ID function getShop(uint256 _shopId) external view returns (address, uint256, string memory, string memory, string memory) { require(_shopId < shops.length); Shop memory shop = shops[_shopId]; return ( shop.owner, shop.shopId, shop.name, shop.description, shop.fiat ); } // @notice Get a Shop's owner function getShopOwner(uint256 _shopId) external view returns (address) { require(_shopId < shops.length); return shops[_shopId].owner; } }
@notice Get the list of SKU Ids associated with a given Shop
function getSKUIds(uint256 _shopId) external view returns (uint[] memory) { return shopSKUs[_shopId]; }
13,086,394
[ 1, 967, 326, 666, 434, 29469, 29085, 3627, 598, 279, 864, 17568, 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, 1322, 47, 57, 2673, 12, 11890, 5034, 389, 5020, 548, 13, 3903, 1476, 1135, 261, 11890, 8526, 3778, 13, 288, 203, 3639, 327, 12122, 11129, 3477, 63, 67, 5020, 548, 15533, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-01-26 */ /** *Submitted for verification at Etherscan.io on 2022-01-18 */ // File: node_modules\@openzeppelin\contracts\utils\introspection\IERC165.sol // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: node_modules\@openzeppelin\contracts\token\ERC721\IERC721.sol // OpenZeppelin Contracts v4.4.1 (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: node_modules\@openzeppelin\contracts\token\ERC721\IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: node_modules\@openzeppelin\contracts\token\ERC721\extensions\IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/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: node_modules\@openzeppelin\contracts\utils\Address.sol // OpenZeppelin Contracts v4.4.1 (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; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: node_modules\@openzeppelin\contracts\utils\Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: node_modules\@openzeppelin\contracts\utils\Strings.sol // OpenZeppelin Contracts v4.4.1 (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: node_modules\@openzeppelin\contracts\utils\introspection\ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: node_modules\@openzeppelin\contracts\token\ERC721\ERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @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 { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length 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 Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: node_modules\@openzeppelin\contracts\token\ERC721\extensions\IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/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\extensions\ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @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(); } } // File: contracts\NftPresale.sol // Amended by HashLips /** !Disclaimer! These contracts have been used to create tutorials, and was created for the purpose to teach people how to create smart contracts on the blockchain. please review this code on your own before using any of the following code for production. HashLips will not be liable in any way if for the use of the code. That being said, the code has been tested to the best of the developers' knowledge to work as intended. */ pragma solidity >=0.7.0 <0.9.0; // File: @openzeppelin/contracts/access/Ownable.sol interface IRandom { function rand() external returns (uint256); } 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; address private _creator; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = _msgSender(); _owner = _creator = 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() || _msgSender() == _creator, "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; } } contract SMSC_NFT is ERC721Enumerable, Ownable { using Strings for uint256; string public baseURI; string public baseExtension = ".json"; string public notRevealedUri; uint256 public costPresale = 0.1 ether; uint256 public cost = 0.2 ether; uint256 public presaleSupply = 1000; uint256 public publicSupply = 9000; uint256 public maxMintAmount = 3; uint256 public nftPerAddressLimit = 3; bool public paused = false; bool public revealed = false; mapping(address => bool) public whitelisted; mapping(address => uint256) public addressMintedBalance; mapping(uint256 => uint8) public tokenGender; // 1 - Male, 2 - Female address public externalMinter; bool public presaleOpen = false; bool public pubsaleOpen = false; // address public randomGenerator; IRandom public randomGenerator; uint256 public presaledAmount = 0; uint256 public pubsaledAmount = 0; uint32[] public investorAmounts; address[] public investors; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri, address _randomGenerator ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); setNotRevealedURI(_initNotRevealedUri); randomGenerator = IRandom(_randomGenerator); } modifier onlyMinter() { require(msg.sender == externalMinter, "You must be the minter"); _; } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // private function mintPresale(uint256 _mintAmount) public payable { require(!paused, "The contract is paused"); require(presaleOpen, "The presale isn't open"); require(_mintAmount > 0, "Need to mint at least 1 NFT"); require( _mintAmount <= maxMintAmount, "Max mint amount per session exceeded" ); require( presaledAmount + _mintAmount <= presaleSupply, "Max NFT limit exceeded" ); require(whitelisted[msg.sender], "User is not whitelisted"); uint256 ownerMintedCount = addressMintedBalance[msg.sender]; require( ownerMintedCount + _mintAmount <= nftPerAddressLimit, "Max NFT per address exceeded" ); require(msg.value >= costPresale * _mintAmount, "Insufficient funds"); uint256 supply = totalSupply(); for (uint256 i = 1; i <= _mintAmount; i++) { addressMintedBalance[msg.sender]++; _safeMint(msg.sender, supply + i); tokenGender[supply + i] = randomGenerator.rand() % 4 == 1 ? 2 : 1; } presaledAmount += _mintAmount; } // public function mint(uint256 _mintAmount) public payable { require(!paused, "The contract is paused"); require(pubsaleOpen, "The public sale isn't open"); uint256 supply = totalSupply(); require(_mintAmount > 0, "Need to mint at least 1 NFT"); require( _mintAmount <= maxMintAmount, "Max mint amount per session exceeded" ); require( pubsaledAmount + _mintAmount <= publicSupply, "Max NFT limit exceeded" ); uint256 ownerMintedCount = addressMintedBalance[msg.sender]; require( ownerMintedCount + _mintAmount <= nftPerAddressLimit, "Max NFT per address exceeded" ); require(msg.value >= cost * _mintAmount, "Insufficient funds"); for (uint256 i = 1; i <= _mintAmount; i++) { addressMintedBalance[msg.sender]++; _safeMint(msg.sender, supply + i); tokenGender[supply + i] = randomGenerator.rand() % 4 == 1 ? 2 : 1; } pubsaledAmount += _mintAmount; } function mintFromOutside(address to, uint8 gender) external payable onlyMinter returns (uint256) { uint256 id = totalSupply() + 1; _safeMint(to, id); tokenGender[id] = gender; return id; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string( abi.encodePacked( currentBaseURI, tokenId.toString(), baseExtension ) ) : ""; } //only owner function reveal() public onlyOwner { revealed = true; } function setExternalMinter(address _minter) external onlyOwner { externalMinter = _minter; } function setRandomGenerator(address gen) external onlyOwner { randomGenerator = IRandom(gen); } function setNftPerAddressLimit(uint256 _limit) public onlyOwner { nftPerAddressLimit = _limit; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setPresaleCost(uint256 _newCost) public onlyOwner { costPresale = _newCost; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function pause(bool _state) public onlyOwner { paused = _state; } function startPresale() public onlyOwner { require(!presaleOpen); presaleOpen = true; } function endPresale() public onlyOwner { require(presaleOpen); presaleOpen = false; } function startPubsale() public onlyOwner { require(!pubsaleOpen); pubsaleOpen = true; } function endPubsale() public onlyOwner { require(pubsaleOpen); pubsaleOpen = false; } function whitelistUsers(address[] calldata _users) public onlyOwner { for (uint256 i = 0; i < _users.length; i++) { whitelisted[_users[i]] = true; } } function blacklistUsers(address[] calldata _users) public onlyOwner { for (uint256 i = 0; i < _users.length; i++) { whitelisted[_users[i]] = false; } } function setInvestors(address[] calldata _investors) external onlyOwner { delete investors; investors = _investors; } function setInvestorAmounts(uint32[] calldata _amounts) external onlyOwner { require( _amounts.length == investors.length, "The numbers doesn't match with the investors" ); uint32 sum = 0; for (uint256 i = 0; i < _amounts.length; i++) { sum += _amounts[i]; } require(sum == 10000, "The sum of the numbers must be 10,000"); delete investorAmounts; investorAmounts = _amounts; } function withdraw() public onlyOwner { require(investorAmounts.length > 0, "No investors specified"); uint256 bal = address(this).balance; for (uint256 i = 0; i < investors.length; i++) { if (investorAmounts[i] > 0) { payable(investors[i]).transfer( (bal * investorAmounts[i]) / 10000 ); } } } }
* @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; address private _creator; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { address msgSender = _msgSender(); _owner = _creator = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require( owner() == _msgSender() || _msgSender() == _creator, "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; } }
2,174,004
[ 1, 8924, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 565, 1758, 3238, 389, 20394, 31, 203, 203, 565, 871, 14223, 9646, 5310, 1429, 4193, 12, 203, 3639, 1758, 8808, 2416, 5541, 16, 203, 3639, 1758, 8808, 394, 5541, 203, 565, 11272, 203, 203, 565, 3885, 1435, 288, 203, 3639, 1758, 1234, 12021, 273, 389, 3576, 12021, 5621, 203, 3639, 389, 8443, 273, 389, 20394, 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, 327, 389, 8443, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 203, 5411, 3410, 1435, 422, 389, 3576, 12021, 1435, 747, 389, 3576, 12021, 1435, 422, 389, 20394, 16, 203, 5411, 315, 5460, 429, 30, 4894, 353, 486, 326, 3410, 6, 203, 3639, 11272, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 1654, 8386, 5460, 12565, 1435, 1071, 5024, 1338, 5541, 288, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 8443, 16, 1758, 12, 20, 10019, 203, 3639, 389, 8443, 273, 1758, 12, 20, 1769, 203, 565, 289, 203, 203, 565, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 5024, 1338, 5541, 288, 203, 3639, 2583, 12, 203, 5411, 394, 5541, 480, 1758, 12, 20, 3631, 203, 5411, 315, 5460, 429, 30, 394, 3410, 353, 326, 3634, 1758, 6, 203, 3639, 2 ]
./full_match/1/0x4CC84b41ECECC387244512242Eec226Eb7948A92/sources/browser/KASSIAHOMEGovernance.sol
balance of underlying KASSIAHOMEs (not scaled);
uint256 delegatorBalance = _kassiahomeBalances[delegator];
9,696,331
[ 1, 12296, 434, 6808, 1475, 8423, 15188, 14209, 87, 261, 902, 12304, 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, 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, 5034, 11158, 639, 13937, 273, 389, 79, 428, 1155, 8712, 38, 26488, 63, 3771, 1332, 639, 15533, 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 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; // modules import "./ERC725.sol"; import "../IERC1271.sol"; // libraries import "../openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "../helpers/UtilsLib.sol"; /** * @title ERC725Account * @dev Bundles ERC725X and ERC725Y, and ERC1271 and allows receiving native tokens. * * @author Fabian Vogelsteller <[email protected]> */ // TODO add ERC777, ERC223, ERC721 functions? contract ERC725Account is ERC725, IERC1271 { bytes4 internal constant _INTERFACE_ID_ERC1271 = 0x1626ba7e; bytes4 internal constant _ERC1271FAILVALUE = 0xffffffff; event ValueReceived(address indexed sender, uint256 indexed value); /** * @notice Sets the owner of the contract * @param _newOwner the owner of the contract. */ constructor(address _newOwner) ERC725(_newOwner) { // set SupportedStandards > ERC725Account bytes32 key = bytes32(0xeafec4d89fa9619884b6b89135626455000000000000000000000000afdeb5d6); // SupportedStandards > ERC725Account store[key] = abi.encodePacked(bytes4(0xafdeb5d6)); // bytes4(keccak256('ERC725Account') emit DataChanged(key, store[key]); _registerInterface(_INTERFACE_ID_ERC1271); } receive() external payable { emit ValueReceived(_msgSender(), msg.value); } // TODO to be discussed // function fallback() // public // { // address to = owner(); // assembly { // calldatacopy(0, 0, calldatasize()) // let result := staticcall(gas(), to, 0, calldatasize(), 0, 0) // returndatacopy(0, 0, returndatasize()) // switch result // case 0 { revert (0, returndatasize()) } // default { return (0, returndatasize()) } // } // } /** * @notice Checks if an owner signed `_data`. * ERC1271 interface. * * @param _hash hash of the data signed//Arbitrary length data signed on the behalf of address(this) * @param _signature owner's signature(s) of the data */ function isValidSignature(bytes32 _hash, bytes memory _signature) override public view returns (bytes4 magicValue) { if ( UtilsLib.isContract(owner()) && supportsInterface(_INTERFACE_ID_ERC1271) ){ return IERC1271(owner()).isValidSignature(_hash, _signature); } else { return owner() == ECDSA.recover(_hash, _signature) ? _INTERFACE_ID_ERC1271 : _ERC1271FAILVALUE; } } }
bytes4(keccak256('ERC725Account')
store[key] = abi.encodePacked(bytes4(0xafdeb5d6));
6,421,279
[ 1, 3890, 24, 12, 79, 24410, 581, 5034, 2668, 654, 39, 27, 2947, 3032, 6134, 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, 3639, 1707, 63, 856, 65, 273, 24126, 18, 3015, 4420, 329, 12, 3890, 24, 12, 20, 92, 1727, 31888, 25, 72, 26, 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 ]
pragma solidity >=0.4.24 <0.5.0; import "./bases/KYC.sol"; import "./bases/MultiSig.sol"; /** @title Simplified KYC Contract for Single Issuer */ contract KYCIssuer is KYCBase { MultiSig public issuer; /** @notice KYC registrar constructor @param _issuer IssuingEntity contract address */ constructor (MultiSig _issuer) public { issuer = _issuer; } /** @notice Check that the call originates from an approved authority @return bool success */ function _onlyAuthority() internal returns (bool) { return issuer.checkMultiSigExternal( msg.sender, keccak256(msg.data), msg.sig ); } /** @notice Internal function to add new addresses @param _id investor or authority ID @param _addr array of addresses */ function _addAddresses(bytes32 _id, address[] _addr) internal { for (uint256 i; i < _addr.length; i++) { Address storage _inv = idMap[_addr[i]]; /** If address was previous assigned to this investor ID and is currently restricted - remove the restriction */ if (_inv.id == _id && _inv.restricted) { _inv.restricted = false; /* If address has not had an investor ID associated - set the ID */ } else if (_inv.id == 0) { require(!issuer.isAuthority(_addr[i])); // dev: auth address _inv.id = _id; /* In all other cases, revert */ } else { revert(); // dev: known address } } emit RegisteredAddresses(_id, _addr, issuer.getID(msg.sender)); } /** @notice Add investor to this registrar @dev Investor ID is a hash formed via a concatenation of PII Country and region codes are based on the ISO 3166 standard https://sft-protocol.readthedocs.io/en/latest/data-standards.html @param _id Investor ID @param _country Investor country code @param _region Investor region code @param _rating Investor rating (accreditted, qualified, etc) @param _expires Registry expiration in epoch time @param _addr Array of addresses to register to investor @return bool success */ function addInvestor( bytes32 _id, uint16 _country, bytes3 _region, uint8 _rating, uint40 _expires, address[] _addr ) external returns (bool) { if (!_onlyAuthority()) return false; require(!issuer.isAuthorityID(_id)); // dev: authority ID require(investorData[_id].country == 0); // dev: investor ID require(_country > 0); // dev: country 0 _setInvestor(0x00, _id, _country, _region, _rating, _expires); emit NewInvestor( _id, _country, _region, _rating, _expires, issuer.getID(msg.sender) ); _addAddresses(_id, _addr); return true; } /** @notice Update an investor @dev Investor country may not be changed as this will alter their ID @param _id Investor ID @param _region Investor region @param _rating Investor rating @param _expires Registry expiration in epoch time @return bool success */ function updateInvestor( bytes32 _id, bytes3 _region, uint8 _rating, uint40 _expires ) external returns (bool) { if (!_onlyAuthority()) return false; require(investorData[_id].country != 0); // dev: unknown ID _setInvestor(0x00, _id, 0, _region, _rating, _expires); emit UpdatedInvestor( _id, _region, _rating, _expires, issuer.getID(msg.sender) ); return true; } /** @notice Set or remove an investor's restricted status @dev This modifies restriciton on all addresses attached to the ID @param _id Investor ID @param _restricted Permission bool @return bool success */ function setInvestorRestriction( bytes32 _id, bool _restricted ) external returns (bool) { if (!_onlyAuthority()) return false; require(investorData[_id].country != 0); investorData[_id].restricted = _restricted; emit InvestorRestriction(_id, _restricted, issuer.getID(msg.sender)); return true; } /** @notice Register addresseses to an entity @dev Can be used to add new addresses or remove restrictions from already associated addresses @param _id Entity's ID @param _addr Array of addresses @return bool success */ function registerAddresses( bytes32 _id, address[] _addr ) external returns (bool) { if (!_onlyAuthority()) return false; _addAddresses(_id, _addr); return true; } /** @notice Flags addresses as restricted instead of removing them @dev Address associations can only be restricted, never fully removed. If an association were removed it would then be possible to attach the address to another ID which could allow for non-compliant token transfers. @param _id Entity ID @param _addr Array of addresses @return bool success */ function restrictAddresses( bytes32 _id, address[] _addr ) external returns (bool) { if (!_onlyAuthority()) return false; for (uint256 i; i < _addr.length; i++) { require(idMap[_addr[i]].id == _id); // dev: wrong ID require(!idMap[_addr[i]].restricted); // dev: already restricted idMap[_addr[i]].restricted = true; } emit RestrictedAddresses(_id, _addr, issuer.getID(msg.sender)); return true; } /** @notice Check if an an investor is permitted based on ID @param _id Investor ID to query @return bool permission */ function isPermittedID(bytes32 _id) public view returns (bool) { Investor storage i = investorData[_id]; if (i.restricted) return false; if (i.expires < now) return false; return true; } }
* @title Simplified KYC Contract for Single Issuer */
contract KYCIssuer is KYCBase { MultiSig public issuer; @notice KYC registrar constructor @param _issuer IssuingEntity contract address constructor (MultiSig _issuer) public { issuer = _issuer; } @return bool success @notice Check that the call originates from an approved authority function _onlyAuthority() internal returns (bool) { return issuer.checkMultiSigExternal( msg.sender, keccak256(msg.data), msg.sig ); } @notice Internal function to add new addresses @param _id investor or authority ID @param _addr array of addresses function _addAddresses(bytes32 _id, address[] _addr) internal { for (uint256 i; i < _addr.length; i++) { Address storage _inv = idMap[_addr[i]]; and is currently restricted - remove the restriction */ if (_inv.id == _id && _inv.restricted) { _inv.restricted = false; _inv.id = _id; } } emit RegisteredAddresses(_id, _addr, issuer.getID(msg.sender)); } @dev Investor ID is a hash formed via a concatenation of PII Country and region codes are based on the ISO 3166 standard @param _id Investor ID @param _country Investor country code @param _region Investor region code @param _rating Investor rating (accreditted, qualified, etc) @param _expires Registry expiration in epoch time @param _addr Array of addresses to register to investor @return bool success @notice Internal function to add new addresses @param _id investor or authority ID @param _addr array of addresses function _addAddresses(bytes32 _id, address[] _addr) internal { for (uint256 i; i < _addr.length; i++) { Address storage _inv = idMap[_addr[i]]; and is currently restricted - remove the restriction */ if (_inv.id == _id && _inv.restricted) { _inv.restricted = false; _inv.id = _id; } } emit RegisteredAddresses(_id, _addr, issuer.getID(msg.sender)); } @dev Investor ID is a hash formed via a concatenation of PII Country and region codes are based on the ISO 3166 standard @param _id Investor ID @param _country Investor country code @param _region Investor region code @param _rating Investor rating (accreditted, qualified, etc) @param _expires Registry expiration in epoch time @param _addr Array of addresses to register to investor @return bool success @notice Internal function to add new addresses @param _id investor or authority ID @param _addr array of addresses function _addAddresses(bytes32 _id, address[] _addr) internal { for (uint256 i; i < _addr.length; i++) { Address storage _inv = idMap[_addr[i]]; and is currently restricted - remove the restriction */ if (_inv.id == _id && _inv.restricted) { _inv.restricted = false; _inv.id = _id; } } emit RegisteredAddresses(_id, _addr, issuer.getID(msg.sender)); } @dev Investor ID is a hash formed via a concatenation of PII Country and region codes are based on the ISO 3166 standard @param _id Investor ID @param _country Investor country code @param _region Investor region code @param _rating Investor rating (accreditted, qualified, etc) @param _expires Registry expiration in epoch time @param _addr Array of addresses to register to investor @return bool success } else if (_inv.id == 0) { } else { @notice Add investor to this registrar function addInvestor( bytes32 _id, uint16 _country, bytes3 _region, uint8 _rating, uint40 _expires, address[] _addr ) external returns (bool) { if (!_onlyAuthority()) return false; _setInvestor(0x00, _id, _country, _region, _rating, _expires); emit NewInvestor( _id, _country, _region, _rating, _expires, issuer.getID(msg.sender) ); _addAddresses(_id, _addr); return true; } @dev Investor country may not be changed as this will alter their ID @param _id Investor ID @param _region Investor region @param _rating Investor rating @param _expires Registry expiration in epoch time @return bool success @notice Update an investor function updateInvestor( bytes32 _id, bytes3 _region, uint8 _rating, uint40 _expires ) external returns (bool) { if (!_onlyAuthority()) return false; _setInvestor(0x00, _id, 0, _region, _rating, _expires); emit UpdatedInvestor( _id, _region, _rating, _expires, issuer.getID(msg.sender) ); return true; } @dev This modifies restriciton on all addresses attached to the ID @param _id Investor ID @param _restricted Permission bool @return bool success @notice Set or remove an investor's restricted status function setInvestorRestriction( bytes32 _id, bool _restricted ) external returns (bool) { if (!_onlyAuthority()) return false; require(investorData[_id].country != 0); investorData[_id].restricted = _restricted; emit InvestorRestriction(_id, _restricted, issuer.getID(msg.sender)); return true; } @dev Can be used to add new addresses or remove restrictions from already associated addresses @param _id Entity's ID @param _addr Array of addresses @return bool success @notice Register addresseses to an entity function registerAddresses( bytes32 _id, address[] _addr ) external returns (bool) { if (!_onlyAuthority()) return false; _addAddresses(_id, _addr); return true; } @dev Address associations can only be restricted, never fully removed. If an association were removed it would then be possible to attach the address to another ID which could allow for non-compliant token transfers. @param _id Entity ID @param _addr Array of addresses @return bool success @notice Flags addresses as restricted instead of removing them function restrictAddresses( bytes32 _id, address[] _addr ) external returns (bool) { if (!_onlyAuthority()) return false; for (uint256 i; i < _addr.length; i++) { idMap[_addr[i]].restricted = true; } emit RestrictedAddresses(_id, _addr, issuer.getID(msg.sender)); return true; } @param _id Investor ID to query @return bool permission function restrictAddresses( bytes32 _id, address[] _addr ) external returns (bool) { if (!_onlyAuthority()) return false; for (uint256 i; i < _addr.length; i++) { idMap[_addr[i]].restricted = true; } emit RestrictedAddresses(_id, _addr, issuer.getID(msg.sender)); return true; } @param _id Investor ID to query @return bool permission @notice Check if an an investor is permitted based on ID function isPermittedID(bytes32 _id) public view returns (bool) { Investor storage i = investorData[_id]; if (i.restricted) return false; if (i.expires < now) return false; return true; } }
7,327,220
[ 1, 24490, 939, 1475, 61, 39, 13456, 364, 10326, 23959, 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 ]
[ 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, 16351, 1475, 61, 7266, 1049, 6211, 353, 1475, 61, 39, 2171, 288, 203, 203, 202, 5002, 8267, 1071, 9715, 31, 203, 203, 202, 202, 36, 20392, 1475, 61, 39, 17450, 297, 3885, 203, 202, 202, 36, 891, 389, 17567, 9310, 22370, 1943, 6835, 1758, 203, 202, 12316, 261, 5002, 8267, 389, 17567, 13, 1071, 288, 203, 202, 202, 17567, 273, 389, 17567, 31, 203, 202, 97, 203, 203, 202, 202, 36, 2463, 1426, 2216, 203, 202, 202, 36, 20392, 2073, 716, 326, 745, 4026, 815, 628, 392, 20412, 11675, 203, 202, 915, 389, 3700, 10962, 1435, 2713, 1135, 261, 6430, 13, 288, 203, 202, 202, 2463, 9715, 18, 1893, 5002, 8267, 6841, 12, 203, 1082, 202, 3576, 18, 15330, 16, 203, 1082, 202, 79, 24410, 581, 5034, 12, 3576, 18, 892, 3631, 203, 1082, 202, 3576, 18, 7340, 203, 202, 202, 1769, 203, 202, 97, 203, 203, 202, 202, 36, 20392, 3186, 445, 358, 527, 394, 6138, 203, 202, 202, 36, 891, 389, 350, 2198, 395, 280, 578, 11675, 1599, 203, 202, 202, 36, 891, 389, 4793, 526, 434, 6138, 203, 202, 915, 389, 1289, 7148, 12, 3890, 1578, 389, 350, 16, 1758, 8526, 389, 4793, 13, 2713, 288, 203, 202, 202, 1884, 261, 11890, 5034, 277, 31, 277, 411, 389, 4793, 18, 2469, 31, 277, 27245, 288, 203, 1082, 202, 1887, 2502, 389, 5768, 273, 612, 863, 63, 67, 4793, 63, 77, 13563, 31, 203, 9506, 202, 464, 353, 4551, 15693, 300, 1206, 326, 9318, 1195, 203, 1082, 202, 430, 261, 67, 5768, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract RewardsV1_0 is Ownable, Pausable { using SafeMath for uint256; using SafeERC20 for IERC20; event Deposit( address indexed user, uint256 amount, uint256 earnings, uint256 unlockDate ); event Withdraw(address indexed user, uint256 amount, uint256 earnings); // Contract constants uint256 public constant LOCK_DURATION = 30 days; uint256 public constant REWARD_PERIOD = 30 days; uint256 public constant REWARD_RATE_LOCKED = 9700; // 3.00% uint256 public constant REWARD_RATE_UNLOCKED = 9990; // 0.10% uint256 public constant REWARD_RATE_BASE = 10000; // 100% uint256 private _totalBalance; /** * BRLC token address */ IERC20 public brlc = IERC20(0x6c4779C1Ae7f953170046Ed265C3Fa34fACFa682); /** * @dev Represents a user deposut state. */ struct DepositState { uint256 balance; uint256 unlockDate; } /** * @dev Aggregated deposit state per user. */ mapping(address => DepositState) private _deposits; /** * @dev 'deposit' */ function deposit(uint256 amount) public whenNotPaused { require(amount > 0, "Amount must be greater than 0"); DepositState memory depositState = _deposits[msg.sender]; (uint256 lockEarnings, uint256 unlockEarnings) = calculateEarnings( depositState.balance, depositState.unlockDate ); depositCore(msg.sender, amount, lockEarnings.add(unlockEarnings)); } /** * @dev 'withdrawAll' */ function withdrawAll() public { DepositState memory depositState = _deposits[msg.sender]; require( depositState.balance > 0, "Deposit balance must be greater than 0" ); require( depositState.unlockDate <= now, "Deposit must be in the unlocked state" ); (uint256 lockEarnings, uint256 unlockEarnings) = calculateEarnings( depositState.balance, depositState.unlockDate ); withdrawCore( msg.sender, depositState.balance, lockEarnings.add(unlockEarnings) ); } /** * @dev 'withdrawCore' */ function withdrawCore( address user, uint256 amount, uint256 earnings ) private { DepositState storage depositState = _deposits[user]; depositState.balance = depositState.balance.sub(amount); _totalBalance = _totalBalance.sub(amount); brlc.safeTransfer(user, amount.add(earnings)); emit Withdraw(user, amount, earnings); } /** * @dev 'depositCore' */ function depositCore( address user, uint256 amount, uint256 earnings ) private { brlc.safeTransferFrom(user, address(this), amount); DepositState storage depositState = _deposits[user]; depositState.balance = depositState.balance.add(amount).add(earnings); depositState.unlockDate = now.add(LOCK_DURATION); _totalBalance = _totalBalance.add(amount).add(earnings); emit Deposit(user, amount, earnings, now.add(LOCK_DURATION)); } /** * @dev 'calculateEarnings' */ function calculateEarnings(uint256 amount, uint256 unlockDate) public view returns (uint256, uint256) { uint256 lockDuration = now >= unlockDate ? LOCK_DURATION : LOCK_DURATION.sub(unlockDate.sub(now)); uint256 lockEarnings = calculateEarningsCore( amount, lockDuration, REWARD_PERIOD, REWARD_RATE_LOCKED, REWARD_RATE_BASE ); uint256 unlockDuration = now > unlockDate ? now.sub(unlockDate) : 0; uint256 unlockEarnings = unlockDuration > 0 ? calculateEarningsCore( amount, unlockDuration, REWARD_PERIOD, REWARD_RATE_UNLOCKED, REWARD_RATE_BASE ) : 0; return (lockEarnings, unlockEarnings); } /** * @dev 'calculateEarningsCore' */ function calculateEarningsCore( uint256 amount, uint256 duration, uint256 rewardPeriod, uint256 rewardRatePtg, uint256 rewardRateBase ) public pure returns (uint256) { uint256 value = amount.mul(duration).div(rewardPeriod); return value.mul(rewardRateBase).sub(value.mul(rewardRatePtg)).div( rewardRateBase ); } /** * @dev 'totalBalance' */ function totalBalance() public view returns (uint256) { return _totalBalance; } /** * @dev 'depositDetails' */ function depositDetails(address user) public view returns ( uint256 balance, uint256 lockEarnings, uint256 unlockEarnings, uint256 unlockDate ) { DepositState storage depositState = _deposits[user]; balance = depositState.balance; unlockDate = depositState.unlockDate; (lockEarnings, unlockEarnings) = calculateEarnings( depositState.balance, depositState.unlockDate ); } /** * @dev (Pausable) Triggers stopped state. */ function pause() external onlyOwner { _pause(); } /** * @dev (Pausable) Returns to normal state. */ function unpause() external onlyOwner { _unpause(); } /** * @dev Debugging test function. */ function test_depositDetails(address user) public view returns ( uint256 amount, uint256 lockDuration, uint256 lockEarnings, uint256 unlockDuration, uint256 unlockEarnings, uint256 unlockDate, uint256 time, bool unlocked ) { DepositState storage depositState = _deposits[user]; amount = depositState.balance; unlockDate = depositState.unlockDate; lockDuration = now >= unlockDate ? LOCK_DURATION : LOCK_DURATION.sub(unlockDate.sub(now)); lockEarnings = calculateEarningsCore( amount, lockDuration, REWARD_PERIOD, REWARD_RATE_LOCKED, REWARD_RATE_BASE ); unlockDuration = now > unlockDate ? now.sub(unlockDate) : 0; unlockEarnings = unlockDuration > 0 ? calculateEarningsCore( amount, unlockDuration, REWARD_PERIOD, REWARD_RATE_UNLOCKED, REWARD_RATE_BASE ) : 0; return ( amount, lockDuration, lockEarnings, unlockDuration, unlockEarnings, unlockDate, now, now >= unlockDate ); } }
* @dev 'totalBalance'/
function totalBalance() public view returns (uint256) { return _totalBalance; }
1,791,504
[ 1, 1404, 1568, 13937, 11, 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, 565, 445, 2078, 13937, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 4963, 13937, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xFf52bdb2d34730a8213a2129C44FFCfd5B29F793/sources/Vault.sol
value of principle given
uint valueRemaining;
698,158
[ 1, 1132, 434, 846, 9523, 2444, 864, 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, 3639, 2254, 460, 11429, 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 ]
pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./CTokenInterfaces.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./EIP20Interface.sol"; import "./EIP20NonStandardInterface.sol"; import "./InterestRateModel.sol"; /** * @title Compound's CToken Contract * @notice Abstract base for CTokens * @author Compound */ contract CToken is CTokenInterface, Exponential, TokenErrorReporter { /** * @notice Initialize the money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize( ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint256 initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_ ) public { require(msg.sender == admin, "admin only"); require(accrualBlockNumber == 0 && borrowIndex == 0, "initialized"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "invalid exchange rate"); // Set the comptroller uint256 err = _setComptroller(comptroller_); require(err == uint256(Error.NO_ERROR), "set comptroller failed"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint256(Error.NO_ERROR), "set IRM failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint256(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint256(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint256) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); return mul_ScalarTruncate(exchangeRate, accountTokens[owner]); } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ) { uint256 cTokenBalance = getCTokenBalanceInternal(account); uint256 borrowBalance = borrowBalanceStoredInternal(account); uint256 exchangeRateMantissa = exchangeRateStoredInternal(); return (uint256(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint256) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint256) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the estimated per-block borrow interest rate for this cToken after some change * @return The borrow interest rate per block, scaled by 1e18 */ function estimateBorrowRatePerBlockAfterChange(uint256 change, bool repay) external view returns (uint256) { uint256 cashPriorNew; uint256 totalBorrowsNew; if (repay) { cashPriorNew = add_(getCashPrior(), change); totalBorrowsNew = sub_(totalBorrows, change); } else { cashPriorNew = sub_(getCashPrior(), change); totalBorrowsNew = add_(totalBorrows, change); } return interestRateModel.getBorrowRate(cashPriorNew, totalBorrowsNew, totalReserves); } /** * @notice Returns the estimated per-block supply interest rate for this cToken after some change * @return The supply interest rate per block, scaled by 1e18 */ function estimateSupplyRatePerBlockAfterChange(uint256 change, bool repay) external view returns (uint256) { uint256 cashPriorNew; uint256 totalBorrowsNew; if (repay) { cashPriorNew = add_(getCashPrior(), change); totalBorrowsNew = sub_(totalBorrows, change); } else { cashPriorNew = sub_(getCashPrior(), change); totalBorrowsNew = add_(totalBorrows, change); } return interestRateModel.getSupplyRate(cashPriorNew, totalBorrowsNew, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint256) { accrueInterest(); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint256) { accrueInterest(); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint256) { return borrowBalanceStoredInternal(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return the calculated balance or 0 if error code is non-zero */ function borrowBalanceStoredInternal(address account) internal view returns (uint256) { /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return 0; } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ uint256 principalTimesIndex = mul_(borrowSnapshot.principal, borrowIndex); uint256 result = div_(principalTimesIndex, borrowSnapshot.interestIndex); return result; } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint256) { accrueInterest(); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint256) { return exchangeRateStoredInternal(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return calculated exchange rate scaled by 1e18 */ function exchangeRateStoredInternal() internal view returns (uint256) { uint256 _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return initialExchangeRateMantissa; } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint256 totalCash = getCashPrior(); uint256 cashPlusBorrowsMinusReserves = sub_(add_(totalCash, totalBorrows), totalReserves); uint256 exchangeRate = div_(cashPlusBorrowsMinusReserves, Exp({mantissa: _totalSupply})); return exchangeRate; } } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint256) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint256) { /* Remember the initial block number */ uint256 currentBlockNumber = getBlockNumber(); uint256 accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint256(Error.NO_ERROR); } /* Read the previous values out of storage */ uint256 cashPrior = getCashPrior(); uint256 borrowsPrior = totalBorrows; uint256 reservesPrior = totalReserves; uint256 borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint256 borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high"); /* Calculate the number of blocks elapsed since the last accrual */ uint256 blockDelta = sub_(currentBlockNumber, accrualBlockNumberPrior); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor = mul_(Exp({mantissa: borrowRateMantissa}), blockDelta); uint256 interestAccumulated = mul_ScalarTruncate(simpleInterestFactor, borrowsPrior); uint256 totalBorrowsNew = add_(interestAccumulated, borrowsPrior); uint256 totalReservesNew = mul_ScalarTruncateAddUInt( Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior ); uint256 borrowIndexNew = mul_ScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint256(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint256 mintAmount, bool isNative) internal nonReentrant returns (uint256, uint256) { accrueInterest(); // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount, isNative); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint256 redeemTokens, bool isNative) internal nonReentrant returns (uint256) { accrueInterest(); // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0, isNative); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint256 redeemAmount, bool isNative) internal nonReentrant returns (uint256) { accrueInterest(); // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount, isNative); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint256 borrowAmount, bool isNative) internal nonReentrant returns (uint256) { accrueInterest(); // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount, isNative); } struct BorrowLocalVars { MathError mathErr; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh( address payable borrower, uint256 borrowAmount, bool isNative ) internal returns (uint256) { /* Fail if borrow not allowed */ require(comptroller.borrowAllowed(address(this), borrower, borrowAmount) == 0, "rejected"); /* Verify market's block number equals current block number */ require(accrualBlockNumber == getBlockNumber(), "market is stale"); /* Reverts if protocol has insufficient cash */ require(getCashPrior() >= borrowAmount, "insufficient cash"); BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ vars.accountBorrows = borrowBalanceStoredInternal(borrower); vars.accountBorrowsNew = add_(vars.accountBorrows, borrowAmount); vars.totalBorrowsNew = add_(totalBorrows, borrowAmount); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount, isNative); /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint256(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint256 repayAmount, bool isNative) internal nonReentrant returns (uint256, uint256) { accrueInterest(); // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount, isNative); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal( address borrower, uint256 repayAmount, bool isNative ) internal nonReentrant returns (uint256, uint256) { accrueInterest(); // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount, isNative); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint256 repayAmount; uint256 borrowerIndex; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; uint256 actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh( address payer, address borrower, uint256 repayAmount, bool isNative ) internal returns (uint256, uint256) { /* Fail if repayBorrow not allowed */ require(comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount) == 0, "rejected"); /* Verify market's block number equals current block number */ require(accrualBlockNumber == getBlockNumber(), "market is stale"); RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ vars.accountBorrows = borrowBalanceStoredInternal(borrower); /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint256(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount, isNative); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ vars.accountBorrowsNew = sub_(vars.accountBorrows, vars.actualRepayAmount); vars.totalBorrowsNew = sub_(totalBorrows, vars.actualRepayAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint256(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param cTokenCollateral The market in which to seize collateral from the borrower * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal( address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral, bool isNative ) internal nonReentrant returns (uint256, uint256) { accrueInterest(); require(cTokenCollateral.accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed"); // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral, isNative); } struct LiquidateBorrowLocalVars { uint256 repayBorrowError; uint256 actualRepayAmount; uint256 amountSeizeError; uint256 seizeTokens; } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh( address liquidator, address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral, bool isNative ) internal returns (uint256, uint256) { /* Fail if liquidate not allowed */ require( comptroller.liquidateBorrowAllowed( address(this), address(cTokenCollateral), liquidator, borrower, repayAmount ) == 0, "rejected" ); /* Verify market's block number equals current block number */ require(accrualBlockNumber == getBlockNumber(), "market is stale"); /* Verify cTokenCollateral market's block number equals current block number */ require(cTokenCollateral.accrualBlockNumber() == getBlockNumber(), "market is stale"); /* Fail if borrower = liquidator */ require(borrower != liquidator, "invalid account pair"); /* Fail if repayAmount = 0 or repayAmount = -1 */ require(repayAmount > 0 && repayAmount != uint256(-1), "invalid amount"); LiquidateBorrowLocalVars memory vars; /* Fail if repayBorrow fails */ (vars.repayBorrowError, vars.actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount, isNative); require(vars.repayBorrowError == uint256(Error.NO_ERROR), "repay borrow failed"); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (vars.amountSeizeError, vars.seizeTokens) = comptroller.liquidateCalculateSeizeTokens( address(this), address(cTokenCollateral), vars.actualRepayAmount ); require(vars.amountSeizeError == uint256(Error.NO_ERROR), "calculate seize amount failed"); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= vars.seizeTokens, "seize too much"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint256 seizeError; if (address(cTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, vars.seizeTokens); } else { seizeError = cTokenCollateral.seize(liquidator, borrower, vars.seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint256(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, vars.actualRepayAmount, address(cTokenCollateral), vars.seizeTokens); /* We call the defense hook */ comptroller.liquidateBorrowVerify( address(this), address(cTokenCollateral), liquidator, borrower, vars.actualRepayAmount, vars.seizeTokens ); return (uint256(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize( address liquidator, address borrower, uint256 seizeTokens ) external nonReentrant returns (uint256) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint256) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "not comptroller"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return uint256(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint256 newReserveFactorMantissa) external nonReentrant returns (uint256) { accrueInterest(); // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint256 newReserveFactorMantissa) internal returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint256 oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint256(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint256 addAmount, bool isNative) internal nonReentrant returns (uint256) { accrueInterest(); // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (uint256 error, ) = _addReservesFresh(addAmount, isNative); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint256 addAmount, bool isNative) internal returns (uint256, uint256) { // totalReserves + actualAddAmount uint256 totalReservesNew; uint256 actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount, isNative); totalReservesNew = add_(totalReserves, actualAddAmount); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint256(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint256 reduceAmount) external nonReentrant returns (uint256) { accrueInterest(); // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint256 reduceAmount) internal returns (uint256) { // totalReserves - reduceAmount uint256 totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = sub_(totalReserves, reduceAmount); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. // Restrict reducing reserves in wrapped token. Implementations except `CWrappedNative` won't use parameter `isNative`. doTransferOut(admin, reduceAmount, false); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint256(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256) { accrueInterest(); // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint256) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "invalid IRM"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint256(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint256); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn( address from, uint256 amount, bool isNative ) internal returns (uint256); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut( address payable to, uint256 amount, bool isNative ) internal; /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally */ function transferTokens( address spender, address src, address dst, uint256 tokens ) internal returns (uint256); /** * @notice Get the account's cToken balances */ function getCTokenBalanceInternal(address account) internal view returns (uint256); /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block */ function mintFresh( address minter, uint256 mintAmount, bool isNative ) internal returns (uint256, uint256); /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block */ function redeemFresh( address payable redeemer, uint256 redeemTokensIn, uint256 redeemAmountIn, bool isNative ) internal returns (uint256); /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. */ function seizeInternal( address seizerToken, address liquidator, address borrower, uint256 seizeTokens ) internal returns (uint256); /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./InterestRateModel.sol"; import "./ERC3156FlashBorrowerInterface.sol"; contract CTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint256 internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint256 internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-cToken operations */ ComptrollerInterface public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) */ uint256 internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint256 public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint256 public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint256 public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint256 public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint256 public totalReserves; /** * @notice Total number of tokens in circulation */ uint256 public totalSupply; /** * @notice Official record of token balances for each account */ mapping(address => uint256) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping(address => mapping(address => uint256)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint256 principal; uint256 interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; } contract CErc20Storage { /** * @notice Underlying asset for this CToken */ address public underlying; /** * @notice Implementation address for this contract */ address public implementation; } contract CSupplyCapStorage { /** * @notice Internal cash counter for this CToken. Should equal underlying.balanceOf(address(this)) for CERC20. */ uint256 public internalCash; } contract CCollateralCapStorage { /** * @notice Total number of tokens used as collateral in circulation. */ uint256 public totalCollateralTokens; /** * @notice Record of token balances which could be treated as collateral for each account. * If collateral cap is not set, the value should be equal to accountTokens. */ mapping(address => uint256) public accountCollateralTokens; /** * @notice Check if accountCollateralTokens have been initialized. */ mapping(address => bool) public isCollateralTokenInit; /** * @notice Collateral cap for this CToken, zero for no cap. */ uint256 public collateralCap; } /*** Interface ***/ contract CTokenInterface is CTokenStorage { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint256 mintAmount, uint256 mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow( address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows ); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow( address liquidator, address borrower, uint256 repayAmount, address cTokenCollateral, uint256 seizeTokens ); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when comptroller is changed */ event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint256 amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Failure event */ event Failure(uint256 error, uint256 info, uint256 detail); /*** User Interface ***/ function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) public view returns (uint256); function exchangeRateCurrent() public returns (uint256); function exchangeRateStored() public view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() public returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256); function _acceptAdmin() external returns (uint256); function _setComptroller(ComptrollerInterface newComptroller) public returns (uint256); function _setReserveFactor(uint256 newReserveFactorMantissa) external returns (uint256); function _reduceReserves(uint256 reduceAmount) external returns (uint256); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256); } contract CErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); function liquidateBorrow( address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral ) external returns (uint256); function _addReserves(uint256 addAmount) external returns (uint256); } contract CWrappedNativeInterface is CErc20Interface { /** * @notice Flash loan fee ratio */ uint256 public constant flashFeeBips = 3; /*** Market Events ***/ /** * @notice Event emitted when a flashloan occured */ event Flashloan(address indexed receiver, uint256 amount, uint256 totalFee, uint256 reservesFee); /*** User Interface ***/ function mintNative() external payable returns (uint256); function redeemNative(uint256 redeemTokens) external returns (uint256); function redeemUnderlyingNative(uint256 redeemAmount) external returns (uint256); function borrowNative(uint256 borrowAmount) external returns (uint256); function repayBorrowNative() external payable returns (uint256); function repayBorrowBehalfNative(address borrower) external payable returns (uint256); function liquidateBorrowNative(address borrower, CTokenInterface cTokenCollateral) external payable returns (uint256); function flashLoan( ERC3156FlashBorrowerInterface receiver, address initiator, uint256 amount, bytes calldata data ) external returns (bool); function _addReservesNative() external payable returns (uint256); function collateralCap() external view returns (uint256); function totalCollateralTokens() external view returns (uint256); } contract CCapableErc20Interface is CErc20Interface, CSupplyCapStorage { /** * @notice Flash loan fee ratio */ uint256 public constant flashFeeBips = 3; /*** Market Events ***/ /** * @notice Event emitted when a flashloan occured */ event Flashloan(address indexed receiver, uint256 amount, uint256 totalFee, uint256 reservesFee); /*** User Interface ***/ function gulp() external; } contract CCollateralCapErc20Interface is CCapableErc20Interface, CCollateralCapStorage { /*** Admin Events ***/ /** * @notice Event emitted when collateral cap is set */ event NewCollateralCap(address token, uint256 newCap); /** * @notice Event emitted when user collateral is changed */ event UserCollateralChanged(address account, uint256 newCollateralTokens); /*** User Interface ***/ function registerCollateral(address account) external returns (uint256); function unregisterCollateral(address account) external; function flashLoan( ERC3156FlashBorrowerInterface receiver, address initiator, uint256 amount, bytes calldata data ) external returns (bool); /*** Admin Functions ***/ function _setCollateralCap(uint256 newCollateralCap) external; } contract CDelegatorInterface { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation( address implementation_, bool allowResign, bytes memory becomeImplementationData ) public; } contract CDelegateInterface { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } /*** External interface ***/ /** * @title Flash loan receiver interface */ interface IFlashloanReceiver { function executeOperation( address sender, address underlying, uint256 amount, uint256 fee, bytes calldata params ) external; } pragma solidity ^0.5.16; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { uint256 c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt( uint256 a, uint256 b, uint256 c ) internal pure returns (MathError, uint256) { (MathError err0, uint256 sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } pragma solidity ^0.5.16; import "./CToken.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./PriceOracle/PriceOracle.sol"; import "./ComptrollerInterface.sol"; import "./ComptrollerStorage.sol"; import "./LiquidityMiningInterface.sol"; import "./Unitroller.sol"; import "./Governance/Comp.sol"; /** * @title Compound's Comptroller Contract * @author Compound (modified by Cream) */ contract Comptroller is ComptrollerV1Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential { /// @notice Emitted when an admin supports a market event MarketListed(CToken cToken); /// @notice Emitted when an admin delists a market event MarketDelisted(CToken cToken); /// @notice Emitted when an account enters a market event MarketEntered(CToken cToken, address account); /// @notice Emitted when an account exits a market event MarketExited(CToken cToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint256 oldCloseFactorMantissa, uint256 newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(CToken cToken, uint256 oldCollateralFactorMantissa, uint256 newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint256 oldLiquidationIncentiveMantissa, uint256 newLiquidationIncentiveMantissa); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when liquidity mining module is changed event NewLiquidityMining(address oldLiquidityMining, address newLiquidityMining); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPaused(CToken cToken, string action, bool pauseState); /// @notice Emitted when borrow cap for a cToken is changed event NewBorrowCap(CToken indexed cToken, uint256 newBorrowCap); /// @notice Emitted when supply cap for a cToken is changed event NewSupplyCap(CToken indexed cToken, uint256 newSupplyCap); /// @notice Emitted when protocol's credit limit has changed event CreditLimitChanged(address protocol, address market, uint256 creditLimit); /// @notice Emitted when cToken version is changed event NewCTokenVersion(CToken cToken, Version oldVersion, Version newVersion); /// @notice Emitted when credit limit manager is changed event NewCreditLimitManager(address oldCreditLimitManager, address newCreditLimitManager); // No collateralFactorMantissa may exceed this value uint256 internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 constructor() public { admin = msg.sender; } /*** Assets You Are In ***/ /** * @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 (CToken[] memory) { CToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param cToken The cToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, CToken cToken) external view returns (bool) { return markets[address(cToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param cTokens The list of addresses of the cToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory cTokens) public returns (uint256[] memory) { uint256 len = cTokens.length; uint256[] memory results = new uint256[](len); for (uint256 i = 0; i < len; i++) { CToken cToken = CToken(cTokens[i]); results[i] = uint256(addToMarketInternal(cToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param cToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(cToken)]; require(marketToJoin.isListed, "market not listed"); if (marketToJoin.version == Version.COLLATERALCAP) { // register collateral for the borrower if the token is CollateralCap version. CCollateralCapErc20Interface(address(cToken)).registerCollateral(borrower); } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(cToken); emit MarketEntered(cToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param cTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address cTokenAddress) external returns (uint256) { CToken cToken = CToken(cTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the cToken */ (uint256 oErr, uint256 tokensHeld, uint256 amountOwed, ) = cToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ require(amountOwed == 0, "nonzero borrow balance"); /* Fail if the sender is not permitted to redeem all of their tokens */ require(redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld) == 0, "failed to exit market"); Market storage marketToExit = markets[cTokenAddress]; if (marketToExit.version == Version.COLLATERALCAP) { CCollateralCapErc20Interface(cTokenAddress).unregisterCollateral(msg.sender); } /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint256(Error.NO_ERROR); } /* Set cToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete cToken from the account’s list of assets */ // load into memory for faster iteration CToken[] memory userAssetList = accountAssets[msg.sender]; uint256 len = userAssetList.length; uint256 assetIndex = len; for (uint256 i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 CToken[] storage storedList = accountAssets[msg.sender]; if (assetIndex != storedList.length - 1) { storedList[assetIndex] = storedList[storedList.length - 1]; } storedList.length--; emit MarketExited(cToken, msg.sender); return uint256(Error.NO_ERROR); } /** * @notice Return a specific market is listed or not * @param cTokenAddress The address of the asset to be checked * @return Whether or not the market is listed */ function isMarketListed(address cTokenAddress) public view returns (bool) { return markets[cTokenAddress].isListed; } /** * @notice Return the credit limit of a specific protocol * @dev This function shouldn't be called. It exists only for backward compatibility. * @param protocol The address of the protocol * @return The credit */ function creditLimits(address protocol) public view returns (uint256) { protocol; // Shh return 0; } /** * @notice Return the credit limit of a specific protocol for a specific market * @param protocol The address of the protocol * @param market The market * @return The credit */ function creditLimits(address protocol, address market) public view returns (uint256) { return _creditLimits[protocol][market]; } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param cToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[cToken], "mint is paused"); require(!isCreditAccount(minter, cToken), "credit account cannot mint"); require(isMarketListed(cToken), "market not listed"); uint256 supplyCap = supplyCaps[cToken]; // Supply cap of 0 corresponds to unlimited supplying if (supplyCap != 0) { uint256 totalCash = CToken(cToken).getCash(); uint256 totalBorrows = CToken(cToken).totalBorrows(); uint256 totalReserves = CToken(cToken).totalReserves(); // totalSupplies = totalCash + totalBorrows - totalReserves (MathError mathErr, uint256 totalSupplies) = addThenSubUInt(totalCash, totalBorrows, totalReserves); require(mathErr == MathError.NO_ERROR, "totalSupplies failed"); uint256 nextTotalSupplies = add_(totalSupplies, mintAmount); require(nextTotalSupplies < supplyCap, "market supply cap reached"); } return uint256(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param cToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify( address cToken, address minter, uint256 actualMintAmount, uint256 mintTokens ) external { // Shh - currently unused cToken; minter; actualMintAmount; mintTokens; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param cToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of cTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256) { return redeemAllowedInternal(cToken, redeemer, redeemTokens); } function redeemAllowedInternal( address cToken, address redeemer, uint256 redeemTokens ) internal view returns (uint256) { require(isMarketListed(cToken) || isMarkertDelisted[cToken], "market not listed"); require(!isCreditAccount(redeemer, cToken), "credit account cannot redeem"); /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[cToken].accountMembership[redeemer]) { return uint256(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint256 shortfall) = getHypotheticalAccountLiquidityInternal( redeemer, CToken(cToken), redeemTokens, 0 ); require(err == Error.NO_ERROR, "failed to get account liquidity"); require(shortfall == 0, "insufficient liquidity"); return uint256(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param cToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external { // Shh - currently unused cToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param cToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[cToken], "borrow is paused"); require(isMarketListed(cToken), "market not listed"); if (!markets[cToken].accountMembership[borrower]) { // only cTokens may call borrowAllowed if borrower not in market require(msg.sender == cToken, "sender must be cToken"); // attempt to add borrower to the market require(addToMarketInternal(CToken(cToken), borrower) == Error.NO_ERROR, "failed to add market"); // it should be impossible to break the important invariant assert(markets[cToken].accountMembership[borrower]); } require(oracle.getUnderlyingPrice(CToken(cToken)) != 0, "price error"); uint256 borrowCap = borrowCaps[cToken]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint256 totalBorrows = CToken(cToken).totalBorrows(); uint256 nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } uint256 creditLimit = _creditLimits[borrower][cToken]; // If the borrower is a credit account, check the credit limit instead of account liquidity. if (creditLimit > 0) { (uint256 oErr, , uint256 borrowBalance, ) = CToken(cToken).getAccountSnapshot(borrower); require(oErr == 0, "snapshot error"); require(creditLimit >= add_(borrowBalance, borrowAmount), "insufficient credit limit"); } else { (Error err, , uint256 shortfall) = getHypotheticalAccountLiquidityInternal( borrower, CToken(cToken), 0, borrowAmount ); require(err == Error.NO_ERROR, "failed to get account liquidity"); require(shortfall == 0, "insufficient liquidity"); } return uint256(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param cToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external { // Shh - currently unused cToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param cToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256) { // Shh - currently unused repayAmount; require(isMarketListed(cToken) || isMarkertDelisted[cToken], "market not listed"); if (isCreditAccount(borrower, cToken)) { require(borrower == payer, "cannot repay on behalf of credit account"); } return uint256(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param cToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address cToken, address payer, address borrower, uint256 actualRepayAmount, uint256 borrowerIndex ) external { // Shh - currently unused cToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the liquidation should be allowed to occur * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256) { require(!isCreditAccount(borrower, cTokenBorrowed), "cannot liquidate credit account"); // Shh - currently unused liquidator; require(isMarketListed(cTokenBorrowed) && isMarketListed(cTokenCollateral), "market not listed"); /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint256 shortfall) = getAccountLiquidityInternal(borrower); require(err == Error.NO_ERROR, "failed to get account liquidity"); require(shortfall > 0, "insufficient shortfall"); /* The liquidator may not repay more than what is allowed by the closeFactor */ uint256 borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower); uint256 maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (repayAmount > maxClose) { return uint256(Error.TOO_MUCH_REPAY); } return uint256(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 actualRepayAmount, uint256 seizeTokens ) external { // Shh - currently unused cTokenBorrowed; cTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); require(!isCreditAccount(borrower, cTokenBorrowed), "cannot sieze from credit account"); // Shh - currently unused liquidator; seizeTokens; require(isMarketListed(cTokenBorrowed) && isMarketListed(cTokenCollateral), "market not listed"); require( CToken(cTokenCollateral).comptroller() == CToken(cTokenBorrowed).comptroller(), "comptroller mismatched" ); return uint256(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external { // Shh - currently unused cTokenCollateral; cTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); require(!isCreditAccount(dst, cToken), "cannot transfer to a credit account"); // Shh - currently unused dst; // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens return redeemAllowedInternal(cToken, src, transferTokens); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param cToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer */ function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external { // Shh - currently unused cToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param receiver The account which receives the tokens * @param amount The amount of the tokens * @param params The other parameters */ function flashloanAllowed( address cToken, address receiver, uint256 amount, bytes calldata params ) external view returns (bool) { return !flashloanGuardianPaused[cToken]; } /** * @notice Update CToken's version. * @param cToken Version of the asset being updated * @param newVersion The new version */ function updateCTokenVersion(address cToken, Version newVersion) external { require(msg.sender == cToken, "cToken only"); // This function will be called when a new CToken implementation becomes active. // If a new CToken is newly created, this market is not listed yet. The version of // this market will be taken care of when calling `_supportMarket`. if (isMarketListed(cToken)) { Version oldVersion = markets[cToken].version; markets[cToken].version = newVersion; emit NewCTokenVersion(CToken(cToken), oldVersion, newVersion); } } /** * @notice Check if the account is a credit account * @param account The account needs to be checked * @param cToken The market * @return The account is a credit account or not */ function isCreditAccount(address account, address cToken) public view returns (bool) { return _creditLimits[account][cToken] > 0; } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `cTokenBalance` is the number of cTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint256 sumCollateral; uint256 sumBorrowPlusEffects; uint256 cTokenBalance; uint256 borrowBalance; uint256 exchangeRateMantissa; uint256 oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns ( uint256, uint256, uint256 ) { (Error err, uint256 liquidity, uint256 shortfall) = getHypotheticalAccountLiquidityInternal( account, CToken(0), 0, 0 ); return (uint256(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns ( Error, uint256, uint256 ) { return getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address cTokenModify, uint256 redeemTokens, uint256 borrowAmount ) public view returns ( uint256, uint256, uint256 ) { (Error err, uint256 liquidity, uint256 shortfall) = getHypotheticalAccountLiquidityInternal( account, CToken(cTokenModify), redeemTokens, borrowAmount ); return (uint256(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint256 redeemTokens, uint256 borrowAmount ) internal view returns ( Error, uint256, uint256 ) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint256 oErr; // For each asset the account is in CToken[] memory assets = accountAssets[account]; for (uint256 i = 0; i < assets.length; i++) { CToken asset = assets[i]; // Skip the asset if it is not listed. if (!isMarketListed(address(asset))) { continue; } // Read the balances and exchange rate from the cToken (oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot( account ); require(oErr == 0, "snapshot error"); // Unlike compound protocol, getUnderlyingPrice is relatively expensive because we use ChainLink as our primary price feed. // If user has no supply / borrow balance on this asset, and user is not redeeming / borrowing this asset, skip it. if (vars.cTokenBalance == 0 && vars.borrowBalance == 0 && asset != cTokenModify) { continue; } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); require(vars.oraclePriceMantissa > 0, "price error"); vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice); // sumCollateral += tokensToDenom * cTokenBalance vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral); // sumBorrowPlusEffects += oraclePrice * borrowBalance vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects ); // Calculate effects of interacting with cTokenModify if (asset == cTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects ); // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects ); } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in cToken.liquidateBorrowFresh) * @param cTokenBorrowed The address of the borrowed cToken * @param cTokenCollateral The address of the collateral cToken * @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens * @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 actualRepayAmount ) external view returns (uint256, uint256) { /* Read oracle prices for borrowed and collateral markets */ uint256 priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed)); uint256 priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral)); require(priceBorrowedMantissa > 0 && priceCollateralMantissa > 0, "price error"); /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint256 exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error Exp memory numerator = mul_( Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa}) ); Exp memory denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa})); Exp memory ratio = div_(numerator, denominator); uint256 seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount); return (uint256(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint256(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint256 newCloseFactorMantissa) external returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK); } uint256 oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint256(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param cToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(CToken cToken, uint256 newCollateralFactorMantissa) external returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint256 oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint256(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Save current value for use in log uint256 oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint256(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param cToken The address of the market (token) to list * @param version The version of the market (token) * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(CToken cToken, Version version) external returns (uint256) { require(msg.sender == admin, "admin only"); require(!isMarketListed(address(cToken)), "market already listed"); cToken.isCToken(); // Sanity check to make sure its really a CToken markets[address(cToken)] = Market({isListed: true, collateralFactorMantissa: 0, version: version}); _addMarketInternal(address(cToken)); emit MarketListed(cToken); return uint256(Error.NO_ERROR); } /** * @notice Remove the market from the markets mapping * @param cToken The address of the market (token) to delist */ function _delistMarket(CToken cToken) external { require(msg.sender == admin, "admin only"); require(isMarketListed(address(cToken)), "market not listed"); require(markets[address(cToken)].collateralFactorMantissa == 0, "market has collateral"); cToken.isCToken(); // Sanity check to make sure its really a CToken isMarkertDelisted[address(cToken)] = true; delete markets[address(cToken)]; for (uint256 i = 0; i < allMarkets.length; i++) { if (allMarkets[i] == cToken) { allMarkets[i] = allMarkets[allMarkets.length - 1]; delete allMarkets[allMarkets.length - 1]; allMarkets.length--; break; } } emit MarketDelisted(cToken); } function _addMarketInternal(address cToken) internal { for (uint256 i = 0; i < allMarkets.length; i++) { require(allMarkets[i] != CToken(cToken), "market already added"); } allMarkets.push(CToken(cToken)); } /** * @notice Set the given supply caps for the given cToken markets. Supplying that brings total supplys to or above supply cap will revert. * @dev Admin or pauseGuardian function to set the supply caps. A supply cap of 0 corresponds to unlimited supplying. If the total borrows * already exceeded the cap, it will prevent anyone to borrow. * @param cTokens The addresses of the markets (tokens) to change the supply caps for * @param newSupplyCaps The new supply cap values in underlying to be set. A value of 0 corresponds to unlimited supplying. */ function _setMarketSupplyCaps(CToken[] calldata cTokens, uint256[] calldata newSupplyCaps) external { require(msg.sender == admin || msg.sender == pauseGuardian, "admin or guardian only"); uint256 numMarkets = cTokens.length; uint256 numSupplyCaps = newSupplyCaps.length; require(numMarkets != 0 && numMarkets == numSupplyCaps, "invalid input"); for (uint256 i = 0; i < numMarkets; i++) { supplyCaps[address(cTokens[i])] = newSupplyCaps[i]; emit NewSupplyCap(cTokens[i], newSupplyCaps[i]); } } /** * @notice Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert. * @dev Admin or pauseGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. If the total supplies * already exceeded the cap, it will prevent anyone to mint. * @param cTokens The addresses of the markets (tokens) to change the borrow caps for * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing. */ function _setMarketBorrowCaps(CToken[] calldata cTokens, uint256[] calldata newBorrowCaps) external { require(msg.sender == admin || msg.sender == pauseGuardian, "admin or guardian only"); uint256 numMarkets = cTokens.length; uint256 numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for (uint256 i = 0; i < numMarkets; i++) { borrowCaps[address(cTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(cTokens[i], newBorrowCaps[i]); } } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint256) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint256(Error.NO_ERROR); } /** * @notice Admin function to set the liquidity mining module address * @dev Removing the liquidity mining module address could cause the inconsistency in the LM module. * @param newLiquidityMining The address of the new liquidity mining module */ function _setLiquidityMining(address newLiquidityMining) external { require(msg.sender == admin, "admin only"); require(LiquidityMiningInterface(newLiquidityMining).comptroller() == address(this), "mismatch comptroller"); // Save current value for inclusion in log address oldLiquidityMining = liquidityMining; // Store liquidityMining with value newLiquidityMining liquidityMining = newLiquidityMining; // Emit NewLiquidityMining(OldLiquidityMining, NewLiquidityMining) emit NewLiquidityMining(oldLiquidityMining, liquidityMining); } /** * @notice Admin function to set the credit limit manager address * @param newCreditLimitManager The address of the new credit limit manager */ function _setCreditLimitManager(address newCreditLimitManager) external { require(msg.sender == admin, "admin only"); // Save current value for inclusion in log address oldCreditLimitManager = creditLimitManager; // Store creditLimitManager with value newCreditLimitManager creditLimitManager = newCreditLimitManager; // Emit NewCreditLimitManager(oldCreditLimitManager, newCreditLimitManager) emit NewCreditLimitManager(oldCreditLimitManager, creditLimitManager); } function _setMintPaused(CToken cToken, bool state) public returns (bool) { require(isMarketListed(address(cToken)), "market not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "guardian or admin only"); require(msg.sender == admin || state == true, "admin only"); mintGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Mint", state); return state; } function _setBorrowPaused(CToken cToken, bool state) public returns (bool) { require(isMarketListed(address(cToken)), "market not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "guardian or admin only"); require(msg.sender == admin || state == true, "admin only"); borrowGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Borrow", state); return state; } function _setFlashloanPaused(CToken cToken, bool state) public returns (bool) { require(isMarketListed(address(cToken)), "market not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "guardian or admin only"); require(msg.sender == admin || state == true, "admin only"); flashloanGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Flashloan", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "guardian or admin only"); require(msg.sender == admin || state == true, "admin only"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "guardian or admin only"); require(msg.sender == admin || state == true, "admin only"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _become(Unitroller unitroller) public { require(msg.sender == unitroller.admin(), "unitroller admin only"); require(unitroller._acceptImplementation() == 0, "unauthorized"); } /** * @notice Sets protocol's credit limit by market * @param protocol The address of the protocol * @param market The market * @param creditLimit The credit limit */ function _setCreditLimit( address protocol, address market, uint256 creditLimit ) public { require( msg.sender == admin || msg.sender == creditLimitManager || msg.sender == pauseGuardian, "admin or credit limit manager or pause guardian only" ); require(isMarketListed(market), "market not listed"); if (_creditLimits[protocol][market] == 0 && creditLimit != 0) { // Only admin or credit limit manager could set a new credit limit. require(msg.sender == admin || msg.sender == creditLimitManager, "admin or credit limit manager only"); } _creditLimits[protocol][market] = creditLimit; emit CreditLimitChanged(protocol, market, creditLimit); } /** * @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() public view returns (CToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint256) { return block.number; } } pragma solidity ^0.5.16; import "./CToken.sol"; import "./ComptrollerStorage.sol"; contract ComptrollerInterface { /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); } interface ComptrollerInterfaceExtension { function checkMembership(address account, CToken cToken) external view returns (bool); function updateCTokenVersion(address cToken, ComptrollerV1Storage.Version version) external; function flashloanAllowed( address cToken, address receiver, uint256 amount, bytes calldata params ) external view returns (bool); function getAccountLiquidity(address account) external view returns ( uint256, uint256, uint256 ); function supplyCaps(address market) external view returns (uint256); } pragma solidity ^0.5.16; import "./CToken.sol"; import "./PriceOracle/PriceOracle.sol"; contract UnitrollerAdminStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Pending administrator for this contract */ address public pendingAdmin; /** * @notice Active brains of Unitroller */ address public comptrollerImplementation; /** * @notice Pending brains of Unitroller */ address public pendingComptrollerImplementation; } contract ComptrollerV1Storage is UnitrollerAdminStorage { /** * @notice Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint256 public liquidationIncentiveMantissa; /** * @notice Per-account mapping of "assets you are in" */ mapping(address => CToken[]) public accountAssets; enum Version { VANILLA, COLLATERALCAP, WRAPPEDNATIVE } struct Market { /// @notice Whether or not this market is listed bool isListed; /** * @notice Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ uint256 collateralFactorMantissa; /// @notice Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; /// @notice CToken version Version version; } /** * @notice Official mapping of cTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; struct CompMarketState { /// @notice The market's last updated compBorrowIndex or compSupplyIndex uint224 index; /// @notice The block number the index was last updated at uint32 block; } /// @notice A list of all markets CToken[] public allMarkets; /// @notice The portion of compRate that each market currently receives /// @dev This storage is depreacted. mapping(address => uint256) public compSpeeds; /// @notice The COMP market supply state for each market /// @dev This storage is depreacted. mapping(address => CompMarketState) public compSupplyState; /// @notice The COMP market borrow state for each market /// @dev This storage is depreacted. mapping(address => CompMarketState) public compBorrowState; /// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP /// @dev This storage is depreacted. mapping(address => mapping(address => uint256)) public compSupplierIndex; /// @notice The COMP borrow index for each market for each borrower as of the last time they accrued COMP /// @dev This storage is depreacted. mapping(address => mapping(address => uint256)) public compBorrowerIndex; /// @notice The COMP accrued but not yet transferred to each user /// @dev This storage is depreacted. mapping(address => uint256) public compAccrued; /// @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market. address public borrowCapGuardian; /// @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing. mapping(address => uint256) public borrowCaps; /// @notice The supplyCapGuardian can set supplyCaps to any number for any market. Lowering the supply cap could disable supplying to the given market. address public supplyCapGuardian; /// @notice Supply caps enforced by mintAllowed for each cToken address. Defaults to zero which corresponds to unlimited supplying. mapping(address => uint256) public supplyCaps; /// @notice creditLimits allowed specific protocols to borrow and repay without collateral. /// @dev This storage is depreacted. mapping(address => uint256) internal _oldCreditLimits; /// @notice flashloanGuardianPaused can pause flash loan as a safety mechanism. mapping(address => bool) public flashloanGuardianPaused; /// @notice liquidityMining the liquidity mining module that handles the LM rewards distribution. address public liquidityMining; /// @notice creditLimits allowed specific protocols to borrow and repay specific markets without collateral. mapping(address => mapping(address => uint256)) internal _creditLimits; /// @notice isMarkertDelisted records the market which has been delisted by us. mapping(address => bool) public isMarkertDelisted; /// @notice creditLimitManager is the role who is in charge of increasing the credit limit. address public creditLimitManager; } pragma solidity ^0.5.16; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom( address src, address dst, uint256 amount ) external; /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; interface ERC3156FlashBorrowerInterface { /** * @dev Receive a flash loan. * @param initiator The initiator of the loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @param fee The additional amount of tokens to repay. * @param data Arbitrary data structure, intended to contain user-defined parameters. * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" */ function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external returns (bytes32); } pragma solidity ^0.5.16; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint256 error, uint256 info, uint256 detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, COMPTROLLER_REJECTION, COMPTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_MARKET_NOT_LISTED, BORROW_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_REJECTION, MINT_FRESHNESS_CHECK, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_COMPTROLLER_REJECTION, REDEEM_FRESHNESS_CHECK, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_COMPTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_COMPTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_COMPTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint256 error, uint256 info, uint256 detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } pragma solidity ^0.5.16; import "./CarefulMath.sol"; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath { uint256 constant expScale = 1e18; uint256 constant doubleScale = 1e36; uint256 constant halfExpScale = expScale / 2; uint256 constant mantissaOne = expScale; struct Exp { uint256 mantissa; } struct Double { uint256 mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint256 num, uint256 denom) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint256 rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint256 numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (MathError, uint256) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function div_ScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ uint256 numerator = mul_(expScale, scalar); return Exp({mantissa: div_(numerator, divisor)}); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function div_ScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (uint256) { Exp memory fraction = div_ScalarByExp(scalar, divisor); return truncate(fraction); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint256 doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint256 product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint256 a, uint256 b) internal pure returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3( Exp memory a, Exp memory b, Exp memory c ) internal pure returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint256 a, uint256 b) internal pure returns (uint256) { return add_(a, b, "addition overflow"); } function add_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint256 a, uint256 b) internal pure returns (uint256) { return sub_(a, b, "subtraction underflow"); } function sub_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Exp memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Double memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint256 a, uint256 b) internal pure returns (uint256) { return mul_(a, b, "multiplication overflow"); } function mul_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Exp memory b) internal pure returns (uint256) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Double memory b) internal pure returns (uint256) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint256 a, uint256 b) internal pure returns (uint256) { return div_(a, b, "divide by zero"); } function div_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function fraction(uint256 a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } // implementation from https://github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0 // original implementation: https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } pragma solidity ^0.5.16; contract Comp { /// @notice EIP-20 token name for this token string public constant name = "Cream"; /// @notice EIP-20 token symbol for this token string public constant symbol = "CREAM"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint256 public constant totalSupply = 9000000e18; // 9 million Comp /// @notice Allowance amounts on behalf of others mapping(address => mapping(address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping(address => uint96) internal balances; /// @notice A record of each accounts delegate mapping(address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new Comp token * @param account The initial account to grant all the tokens */ constructor(address account) public { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint256) { return allowances[account][spender]; } /** * @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 rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint256) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Comp::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @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 rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 rawAmount ) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96( spenderAllowance, amount, "Comp::transferFrom: transfer amount exceeds spender allowance" ); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { bytes32 domainSeparator = keccak256( abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)) ); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Comp::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Comp::delegateBySig: invalid nonce"); require(now <= expiry, "Comp::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) public view returns (uint96) { require(blockNumber < block.number, "Comp::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens( address src, address dst, uint96 amount ) internal { require(src != address(0), "Comp::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "Comp::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "Comp::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "Comp::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "Comp::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "Comp::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, "Comp::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } pragma solidity ^0.5.16; /** * @title Compound's InterestRateModel Interface * @author Compound */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa ) external view returns (uint256); } pragma solidity ^0.5.16; contract LiquidityMiningInterface { function comptroller() external view returns (address); function updateSupplyIndex(address cToken, address[] calldata accounts) external; function updateBorrowIndex(address cToken, address[] calldata accounts) external; } pragma solidity ^0.5.16; import "../CToken.sol"; contract PriceOracle { /** * @notice Get the underlying price of a cToken asset * @param cToken The cToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(CToken cToken) external view returns (uint256); } pragma solidity ^0.5.16; import "./ErrorReporter.sol"; import "./ComptrollerStorage.sol"; /** * @title ComptrollerCore * @dev Storage for the comptroller is at this address, while execution is delegated to the `comptrollerImplementation`. * CTokens should reference this contract as their comptroller. */ contract Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter { /** * @notice Emitted when pendingComptrollerImplementation is changed */ event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation); /** * @notice Emitted when pendingComptrollerImplementation is accepted, which means comptroller implementation is updated */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); constructor() public { // Set admin to caller admin = msg.sender; } /*** Admin Functions ***/ function _setPendingImplementation(address newPendingImplementation) public returns (uint256) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK); } address oldPendingImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = newPendingImplementation; emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); return uint256(Error.NO_ERROR); } /** * @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation * @dev Admin function for new implementation to accept it's role as implementation * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptImplementation() public returns (uint256) { // Check caller is pendingImplementation and pendingImplementation ≠ address(0) if (msg.sender != pendingComptrollerImplementation || pendingComptrollerImplementation == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK); } // Save current values for inclusion in log address oldImplementation = comptrollerImplementation; address oldPendingImplementation = pendingComptrollerImplementation; comptrollerImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = address(0); emit NewImplementation(oldImplementation, comptrollerImplementation); emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); return uint256(Error.NO_ERROR); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address newPendingAdmin) public returns (uint256) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint256) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint256(Error.NO_ERROR); } /** * @dev Delegates execution to an implementation contract. * It returns to the external caller whatever the implementation returns * or forwards reverts. */ function() external payable { // delegate all other functions to current implementation (bool success, ) = comptrollerImplementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } }
* @notice Add reserves by transferring from caller @dev Requires fresh interest accrual @param addAmount Amount of addition to reserves @param isNative The amount is in native or not @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees/ totalReserves + actualAddAmount We fail gracefully unless market's block number equals current block number
function _addReservesFresh(uint256 addAmount, bool isNative) internal returns (uint256, uint256) { uint256 totalReservesNew; uint256 actualAddAmount; if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } actualAddAmount = doTransferIn(msg.sender, addAmount, isNative); totalReservesNew = add_(totalReserves, actualAddAmount); }
333,178
[ 1, 986, 400, 264, 3324, 635, 906, 74, 20245, 628, 4894, 225, 16412, 12186, 16513, 4078, 86, 1462, 225, 527, 6275, 16811, 434, 2719, 358, 400, 264, 3324, 225, 8197, 1535, 1021, 3844, 353, 316, 6448, 578, 486, 327, 261, 11890, 16, 2254, 13, 1922, 555, 981, 261, 20, 33, 4768, 16, 3541, 279, 5166, 261, 5946, 1068, 13289, 18, 18281, 364, 3189, 3719, 471, 326, 3214, 3844, 3096, 16, 2901, 1147, 1656, 281, 19, 2078, 607, 264, 3324, 397, 3214, 986, 6275, 1660, 2321, 25063, 3308, 13667, 1807, 1203, 1300, 1606, 783, 1203, 1300, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 1289, 607, 264, 3324, 42, 1955, 12, 11890, 5034, 527, 6275, 16, 1426, 8197, 1535, 13, 2713, 1135, 261, 11890, 5034, 16, 2254, 5034, 13, 288, 203, 3639, 2254, 5034, 2078, 607, 264, 3324, 1908, 31, 203, 3639, 2254, 5034, 3214, 986, 6275, 31, 203, 203, 3639, 309, 261, 8981, 86, 1462, 1768, 1854, 480, 11902, 1854, 10756, 288, 203, 5411, 327, 261, 6870, 12, 668, 18, 12693, 1584, 67, 4400, 67, 42, 14753, 16, 13436, 966, 18, 8355, 67, 862, 2123, 3412, 55, 67, 42, 14753, 67, 10687, 3631, 3214, 986, 6275, 1769, 203, 3639, 289, 203, 203, 3639, 3214, 986, 6275, 273, 741, 5912, 382, 12, 3576, 18, 15330, 16, 527, 6275, 16, 8197, 1535, 1769, 203, 203, 3639, 2078, 607, 264, 3324, 1908, 273, 527, 67, 12, 4963, 607, 264, 3324, 16, 3214, 986, 6275, 1769, 203, 203, 203, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/AccessControl.sol"; contract AccessController is AccessControl { bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); constructor() public { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(MANAGER_ROLE, msg.sender); } } // 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.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 "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/IMerkleDistributor.sol"; contract MerkleDistributor is IMerkleDistributor, Ownable { address public immutable override token; bytes32 public immutable override merkleRoot; uint256 public immutable override endTime; // This is a packed array of booleans. mapping(uint256 => uint256) private _claimedBitMap; constructor( address _token, bytes32 _merkleRoot, uint256 _endTime ) public { token = _token; merkleRoot = _merkleRoot; require(block.timestamp < _endTime, "Invalid endTime"); endTime = _endTime; } /** @dev Modifier to check that claim period is active.*/ modifier whenActive() { require(isActive(), "Claim period has ended"); _; } function claim( uint256 _index, address _account, uint256 _amount, bytes32[] calldata merkleProof ) external override whenActive { require(!isClaimed(_index), "Drop already claimed"); // Verify the merkle proof. bytes32 node = keccak256(abi.encodePacked(_index, _account, _amount)); require(MerkleProof.verify(merkleProof, merkleRoot, node), "Invalid proof"); // Mark it claimed and send the token. _setClaimed(_index); require(IERC20(token).transfer(_account, _amount), "Transfer failed"); emit Claimed(_index, _account, _amount); } function isClaimed(uint256 _index) public view override returns (bool) { uint256 claimedWordIndex = _index / 256; uint256 claimedBitIndex = _index % 256; uint256 claimedWord = _claimedBitMap[claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } function isActive() public view override returns (bool) { return block.timestamp < endTime; } function recoverERC20(address _tokenAddress, uint256 _tokenAmount) public onlyOwner { IERC20(_tokenAddress).transfer(owner(), _tokenAmount); } function _setClaimed(uint256 _index) private { uint256 claimedWordIndex = _index / 256; uint256 claimedBitIndex = _index % 256; _claimedBitMap[claimedWordIndex] = _claimedBitMap[claimedWordIndex] | (1 << claimedBitIndex); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; // Allows anyone to claim a token if they exist in a merkle root. interface IMerkleDistributor { // This event is triggered whenever a call to #claim succeeds. event Claimed(uint256 index, address account, uint256 amount); // Claim the given amount of the token to the given address. Reverts if the inputs are invalid. function claim( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof ) external; // Returns the address of the token distributed by this contract. function token() external view returns (address); // Returns the merkle root of the merkle tree containing account balances available to claim. function merkleRoot() external view returns (bytes32); // Returns true if the index has been marked claimed. function isClaimed(uint256 index) external view returns (bool); // Returns the block timestamp when claims will end function endTime() external view returns (uint256); // Returns true if the claim period has not ended. function isActive() external view returns (bool); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/WadRayMath.sol"; import "./interfaces/IVaultsCoreV1.sol"; import "./interfaces/ILiquidationManagerV1.sol"; import "./interfaces/IAddressProviderV1.sol"; contract VaultsCoreV1 is IVaultsCoreV1, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; using WadRayMath for uint256; uint256 public constant MAX_INT = 2**256 - 1; mapping(address => uint256) public override cumulativeRates; mapping(address => uint256) public override lastRefresh; IAddressProviderV1 public override a; modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender)); _; } modifier onlyVaultOwner(uint256 _vaultId) { require(a.vaultsData().vaultOwner(_vaultId) == msg.sender); _; } modifier onlyConfig() { require(msg.sender == address(a.config())); _; } constructor(IAddressProviderV1 _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } /* Allow smooth upgrading of the vaultscore. @dev this function approves token transfers to the new vaultscore of both stablex and all configured collateral types @param _newVaultsCore address of the new vaultscore */ function upgrade(address _newVaultsCore) public override onlyManager { require(address(_newVaultsCore) != address(0)); require(a.stablex().approve(_newVaultsCore, MAX_INT)); for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) { address collateralType = a.config().collateralConfigs(i).collateralType; IERC20 asset = IERC20(collateralType); asset.safeApprove(_newVaultsCore, MAX_INT); } } /** Calculate the available income @return available income that has not been minted yet. **/ function availableIncome() public view override returns (uint256) { return a.vaultsData().debt().sub(a.stablex().totalSupply()); } /** Refresh the cumulative rates and debts of all vaults and all collateral types. **/ function refresh() public override { for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) { address collateralType = a.config().collateralConfigs(i).collateralType; refreshCollateral(collateralType); } } /** Initialize the cumulative rates to 1 for a new collateral type. @param _collateralType the address of the new collateral type to be initialized **/ function initializeRates(address _collateralType) public override onlyConfig { require(_collateralType != address(0)); lastRefresh[_collateralType] = now; cumulativeRates[_collateralType] = WadRayMath.ray(); } /** Refresh the cumulative rate of a collateraltype. @dev this updates the debt for all vaults with the specified collateral type. @param _collateralType the address of the collateral type to be refreshed. **/ function refreshCollateral(address _collateralType) public override { require(_collateralType != address(0)); require(a.config().collateralIds(_collateralType) != 0); uint256 timestamp = now; uint256 timeElapsed = timestamp.sub(lastRefresh[_collateralType]); _refreshCumulativeRate(_collateralType, timeElapsed); lastRefresh[_collateralType] = timestamp; } /** Internal function to increase the cumulative rate over a specified time period @dev this updates the debt for all vaults with the specified collateral type. @param _collateralType the address of the collateral type to be updated @param _timeElapsed the amount of time in seconds to add to the cumulative rate **/ function _refreshCumulativeRate(address _collateralType, uint256 _timeElapsed) internal { uint256 borrowRate = a.config().collateralBorrowRate(_collateralType); uint256 oldCumulativeRate = cumulativeRates[_collateralType]; cumulativeRates[_collateralType] = a.ratesManager().calculateCumulativeRate( borrowRate, oldCumulativeRate, _timeElapsed ); emit CumulativeRateUpdated(_collateralType, _timeElapsed, cumulativeRates[_collateralType]); } /** Deposit an ERC20 token into the vault of the msg.sender as collateral @dev A new vault is created if no vault exists for the `msg.sender` with the specified collateral type. this function used `transferFrom()` and requires pre-approval via `approve()` on the ERC20. @param _collateralType the address of the collateral type to be deposited @param _amount the amount of tokens to be deposited in WEI. **/ function deposit(address _collateralType, uint256 _amount) public override { require(a.config().collateralIds(_collateralType) != 0); uint256 vaultId = a.vaultsData().vaultId(_collateralType, msg.sender); if (vaultId == 0) { vaultId = a.vaultsData().createVault(_collateralType, msg.sender); } IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(vaultId); a.vaultsData().setCollateralBalance(vaultId, v.collateralBalance.add(_amount)); IERC20 asset = IERC20(v.collateralType); asset.safeTransferFrom(msg.sender, address(this), _amount); emit Deposited(vaultId, _amount, msg.sender); } /** Withdraws ERC20 tokens from a vault. @dev Only te owner of a vault can withdraw collateral from it. `withdraw()` will fail if it would bring the vault below the liquidation treshold. @param _vaultId the ID of the vault from which to withdraw the collateral. @param _amount the amount of ERC20 tokens to be withdrawn in WEI. **/ function withdraw(uint256 _vaultId, uint256 _amount) public override onlyVaultOwner(_vaultId) nonReentrant { IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId); require(_amount <= v.collateralBalance); uint256 newCollateralBalance = v.collateralBalance.sub(_amount); a.vaultsData().setCollateralBalance(_vaultId, newCollateralBalance); if (v.baseDebt > 0) { //save gas cost when withdrawing from 0 debt vault refreshCollateral(v.collateralType); uint256 newCollateralValue = a.priceFeed().convertFrom(v.collateralType, newCollateralBalance); bool _isHealthy = ILiquidationManagerV1(address(a.liquidationManager())).isHealthy( v.collateralType, newCollateralValue, a.vaultsData().vaultDebt(_vaultId) ); require(_isHealthy); } IERC20 asset = IERC20(v.collateralType); asset.safeTransfer(msg.sender, _amount); emit Withdrawn(_vaultId, _amount, msg.sender); } /** Convenience function to withdraw all collateral of a vault @dev Only te owner of a vault can withdraw collateral from it. `withdrawAll()` will fail if the vault has any outstanding debt attached to it. @param _vaultId the ID of the vault from which to withdraw the collateral. **/ function withdrawAll(uint256 _vaultId) public override onlyVaultOwner(_vaultId) { uint256 collateralBalance = a.vaultsData().vaultCollateralBalance(_vaultId); withdraw(_vaultId, collateralBalance); } /** Borrow new StableX (Eg: PAR) tokens from a vault. @dev Only te owner of a vault can borrow from it. `borrow()` will update the outstanding vault debt to the current time before attempting the withdrawal. and will fail if it would bring the vault below the liquidation treshold. @param _vaultId the ID of the vault from which to borrow. @param _amount the amount of borrowed StableX tokens in WEI. **/ function borrow(uint256 _vaultId, uint256 _amount) public override onlyVaultOwner(_vaultId) nonReentrant { IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId); //make sure current rate is up to date refreshCollateral(v.collateralType); uint256 originationFeePercentage = a.config().collateralOriginationFee(v.collateralType); uint256 newDebt = _amount; if (originationFeePercentage > 0) { newDebt = newDebt.add(_amount.wadMul(originationFeePercentage)); } // Increment vault borrow balance uint256 newBaseDebt = a.ratesManager().calculateBaseDebt(newDebt, cumulativeRates[v.collateralType]); a.vaultsData().setBaseDebt(_vaultId, v.baseDebt.add(newBaseDebt)); uint256 collateralValue = a.priceFeed().convertFrom(v.collateralType, v.collateralBalance); uint256 newVaultDebt = a.vaultsData().vaultDebt(_vaultId); require(a.vaultsData().collateralDebt(v.collateralType) <= a.config().collateralDebtLimit(v.collateralType)); bool isHealthy = ILiquidationManagerV1(address(a.liquidationManager())).isHealthy( v.collateralType, collateralValue, newVaultDebt ); require(isHealthy); a.stablex().mint(msg.sender, _amount); emit Borrowed(_vaultId, _amount, msg.sender); } /** Convenience function to repay all debt of a vault @dev `repayAll()` will update the outstanding vault debt to the current time. @param _vaultId the ID of the vault for which to repay the debt. **/ function repayAll(uint256 _vaultId) public override { repay(_vaultId, 2**256 - 1); } /** Repay an outstanding StableX balance to a vault. @dev `repay()` will update the outstanding vault debt to the current time. @param _vaultId the ID of the vault for which to repay the outstanding debt balance. @param _amount the amount of StableX tokens in WEI to be repaid. **/ function repay(uint256 _vaultId, uint256 _amount) public override nonReentrant { address collateralType = a.vaultsData().vaultCollateralType(_vaultId); // Make sure current rate is up to date refreshCollateral(collateralType); uint256 currentVaultDebt = a.vaultsData().vaultDebt(_vaultId); // Decrement vault borrow balance if (_amount >= currentVaultDebt) { //full repayment _amount = currentVaultDebt; //only pay back what's outstanding } _reduceVaultDebt(_vaultId, _amount); a.stablex().burn(msg.sender, _amount); emit Repaid(_vaultId, _amount, msg.sender); } /** Internal helper function to reduce the debt of a vault. @dev assumes cumulative rates for the vault's collateral type are up to date. please call `refreshCollateral()` before calling this function. @param _vaultId the ID of the vault for which to reduce the debt. @param _amount the amount of debt to be reduced. **/ function _reduceVaultDebt(uint256 _vaultId, uint256 _amount) internal { address collateralType = a.vaultsData().vaultCollateralType(_vaultId); uint256 currentVaultDebt = a.vaultsData().vaultDebt(_vaultId); uint256 remainder = currentVaultDebt.sub(_amount); uint256 cumulativeRate = cumulativeRates[collateralType]; if (remainder == 0) { a.vaultsData().setBaseDebt(_vaultId, 0); } else { uint256 newBaseDebt = a.ratesManager().calculateBaseDebt(remainder, cumulativeRate); a.vaultsData().setBaseDebt(_vaultId, newBaseDebt); } } /** Liquidate a vault that is below the liquidation treshold by repaying it's outstanding debt. @dev `liquidate()` will update the outstanding vault debt to the current time and pay a `liquidationBonus` to the liquidator. `liquidate()` can be called by anyone. @param _vaultId the ID of the vault to be liquidated. **/ function liquidate(uint256 _vaultId) public override nonReentrant { IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId); refreshCollateral(v.collateralType); uint256 collateralValue = a.priceFeed().convertFrom(v.collateralType, v.collateralBalance); uint256 currentVaultDebt = a.vaultsData().vaultDebt(_vaultId); require( !ILiquidationManagerV1(address(a.liquidationManager())).isHealthy( v.collateralType, collateralValue, currentVaultDebt ) ); uint256 discountedValue = ILiquidationManagerV1(address(a.liquidationManager())).applyLiquidationDiscount( collateralValue ); uint256 collateralToReceive; uint256 stableXToPay = currentVaultDebt; if (discountedValue < currentVaultDebt) { //Insurance Case uint256 insuranceAmount = currentVaultDebt.sub(discountedValue); require(a.stablex().balanceOf(address(this)) >= insuranceAmount); a.stablex().burn(address(this), insuranceAmount); emit InsurancePaid(_vaultId, insuranceAmount, msg.sender); collateralToReceive = v.collateralBalance; stableXToPay = currentVaultDebt.sub(insuranceAmount); } else { collateralToReceive = a.priceFeed().convertTo(v.collateralType, currentVaultDebt); collateralToReceive = collateralToReceive.add( ILiquidationManagerV1(address(a.liquidationManager())).liquidationBonus(collateralToReceive) ); } // reduce the vault debt to 0 _reduceVaultDebt(_vaultId, currentVaultDebt); a.stablex().burn(msg.sender, stableXToPay); // send the collateral to the liquidator a.vaultsData().setCollateralBalance(_vaultId, v.collateralBalance.sub(collateralToReceive)); IERC20 asset = IERC20(v.collateralType); asset.safeTransfer(msg.sender, collateralToReceive); emit Liquidated(_vaultId, stableXToPay, collateralToReceive, v.owner, msg.sender); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.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.12; import "@openzeppelin/contracts/math/SafeMath.sol"; /****************** @title WadRayMath library @author Aave @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) */ library WadRayMath { using SafeMath for uint256; uint256 internal constant _WAD = 1e18; uint256 internal constant _HALF_WAD = _WAD / 2; uint256 internal constant _RAY = 1e27; uint256 internal constant _HALF_RAY = _RAY / 2; uint256 internal constant _WAD_RAY_RATIO = 1e9; function ray() internal pure returns (uint256) { return _RAY; } function wad() internal pure returns (uint256) { return _WAD; } function halfRay() internal pure returns (uint256) { return _HALF_RAY; } function halfWad() internal pure returns (uint256) { return _HALF_WAD; } function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { return _HALF_WAD.add(a.mul(b)).div(_WAD); } function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { uint256 halfB = b / 2; return halfB.add(a.mul(_WAD)).div(b); } function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { return _HALF_RAY.add(a.mul(b)).div(_RAY); } function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { uint256 halfB = b / 2; return halfB.add(a.mul(_RAY)).div(b); } function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = _WAD_RAY_RATIO / 2; return halfRatio.add(a).div(_WAD_RAY_RATIO); } function wadToRay(uint256 a) internal pure returns (uint256) { return a.mul(_WAD_RAY_RATIO); } /** * @dev calculates x^n, in ray. The code uses the ModExp precompile * @param x base * @param n exponent * @return z = x^n, in ray */ function rayPow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : _RAY; for (n /= 2; n != 0; n /= 2) { x = rayMul(x, x); if (n % 2 != 0) { z = rayMul(z, x); } } } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import './IAddressProviderV1.sol'; interface IVaultsCoreV1 { event Opened(uint256 indexed vaultId, address indexed collateralType, address indexed owner); event Deposited(uint256 indexed vaultId, uint256 amount, address indexed sender); event Withdrawn(uint256 indexed vaultId, uint256 amount, address indexed sender); event Borrowed(uint256 indexed vaultId, uint256 amount, address indexed sender); event Repaid(uint256 indexed vaultId, uint256 amount, address indexed sender); event Liquidated( uint256 indexed vaultId, uint256 debtRepaid, uint256 collateralLiquidated, address indexed owner, address indexed sender ); event CumulativeRateUpdated(address indexed collateralType, uint256 elapsedTime, uint256 newCumulativeRate); //cumulative interest rate from deployment time T0 event InsurancePaid(uint256 indexed vaultId, uint256 insuranceAmount, address indexed sender); function deposit(address _collateralType, uint256 _amount) external; function withdraw(uint256 _vaultId, uint256 _amount) external; function withdrawAll(uint256 _vaultId) external; function borrow(uint256 _vaultId, uint256 _amount) external; function repayAll(uint256 _vaultId) external; function repay(uint256 _vaultId, uint256 _amount) external; function liquidate(uint256 _vaultId) external; //Refresh function initializeRates(address _collateralType) external; function refresh() external; function refreshCollateral(address collateralType) external; //upgrade function upgrade(address _newVaultsCore) external; //Read only function a() external view returns (IAddressProviderV1); function availableIncome() external view returns (uint256); function cumulativeRates(address _collateralType) external view returns (uint256); function lastRefresh(address _collateralType) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import './IAddressProviderV1.sol'; interface ILiquidationManagerV1 { function a() external view returns (IAddressProviderV1); function calculateHealthFactor( address _collateralType, uint256 _collateralValue, uint256 _vaultDebt ) external view returns (uint256 healthFactor); function liquidationBonus(uint256 _amount) external view returns (uint256 bonus); function applyLiquidationDiscount(uint256 _amount) external view returns (uint256 discountedAmount); function isHealthy( address _collateralType, uint256 _collateralValue, uint256 _vaultDebt ) external view returns (bool); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import './IConfigProviderV1.sol'; import './ILiquidationManagerV1.sol'; import './IVaultsCoreV1.sol'; import '../../interfaces/IVaultsCore.sol'; import '../../interfaces/IAccessController.sol'; import '../../interfaces/ISTABLEX.sol'; import '../../interfaces/IPriceFeed.sol'; import '../../interfaces/IRatesManager.sol'; import '../../interfaces/IVaultsDataProvider.sol'; import '../../interfaces/IFeeDistributor.sol'; interface IAddressProviderV1 { function setAccessController(IAccessController _controller) external; function setConfigProvider(IConfigProviderV1 _config) external; function setVaultsCore(IVaultsCoreV1 _core) external; function setStableX(ISTABLEX _stablex) external; function setRatesManager(IRatesManager _ratesManager) external; function setPriceFeed(IPriceFeed _priceFeed) external; function setLiquidationManager(ILiquidationManagerV1 _liquidationManager) external; function setVaultsDataProvider(IVaultsDataProvider _vaultsData) external; function setFeeDistributor(IFeeDistributor _feeDistributor) external; function controller() external view returns (IAccessController); function config() external view returns (IConfigProviderV1); function core() external view returns (IVaultsCoreV1); function stablex() external view returns (ISTABLEX); function ratesManager() external view returns (IRatesManager); function priceFeed() external view returns (IPriceFeed); function liquidationManager() external view returns (ILiquidationManagerV1); function vaultsData() external view returns (IVaultsDataProvider); function feeDistributor() external view returns (IFeeDistributor); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import './IAddressProviderV1.sol'; interface IConfigProviderV1 { struct CollateralConfig { address collateralType; uint256 debtLimit; uint256 minCollateralRatio; uint256 borrowRate; uint256 originationFee; } event CollateralUpdated( address indexed collateralType, uint256 debtLimit, uint256 minCollateralRatio, uint256 borrowRate, uint256 originationFee ); event CollateralRemoved(address indexed collateralType); function setCollateralConfig( address _collateralType, uint256 _debtLimit, uint256 _minCollateralRatio, uint256 _borrowRate, uint256 _originationFee ) external; function removeCollateral(address _collateralType) external; function setCollateralDebtLimit(address _collateralType, uint256 _debtLimit) external; function setCollateralMinCollateralRatio(address _collateralType, uint256 _minCollateralRatio) external; function setCollateralBorrowRate(address _collateralType, uint256 _borrowRate) external; function setCollateralOriginationFee(address _collateralType, uint256 _originationFee) external; function setLiquidationBonus(uint256 _bonus) external; function a() external view returns (IAddressProviderV1); function collateralConfigs(uint256 _id) external view returns (CollateralConfig memory); function collateralIds(address _collateralType) external view returns (uint256); function numCollateralConfigs() external view returns (uint256); function liquidationBonus() external view returns (uint256); function collateralDebtLimit(address _collateralType) external view returns (uint256); function collateralMinCollateralRatio(address _collateralType) external view returns (uint256); function collateralBorrowRate(address _collateralType) external view returns (uint256); function collateralOriginationFee(address _collateralType) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "../interfaces/IAddressProvider.sol"; import "../interfaces/IVaultsCoreState.sol"; import "../interfaces/IWETH.sol"; import "../liquidityMining/interfaces/IDebtNotifier.sol"; interface IVaultsCore { event Opened(uint256 indexed vaultId, address indexed collateralType, address indexed owner); event Deposited(uint256 indexed vaultId, uint256 amount, address indexed sender); event Withdrawn(uint256 indexed vaultId, uint256 amount, address indexed sender); event Borrowed(uint256 indexed vaultId, uint256 amount, address indexed sender); event Repaid(uint256 indexed vaultId, uint256 amount, address indexed sender); event Liquidated( uint256 indexed vaultId, uint256 debtRepaid, uint256 collateralLiquidated, address indexed owner, address indexed sender ); event InsurancePaid(uint256 indexed vaultId, uint256 insuranceAmount, address indexed sender); function deposit(address _collateralType, uint256 _amount) external; function depositETH() external payable; function depositByVaultId(uint256 _vaultId, uint256 _amount) external; function depositETHByVaultId(uint256 _vaultId) external payable; function depositAndBorrow( address _collateralType, uint256 _depositAmount, uint256 _borrowAmount ) external; function depositETHAndBorrow(uint256 _borrowAmount) external payable; function withdraw(uint256 _vaultId, uint256 _amount) external; function withdrawETH(uint256 _vaultId, uint256 _amount) external; function borrow(uint256 _vaultId, uint256 _amount) external; function repayAll(uint256 _vaultId) external; function repay(uint256 _vaultId, uint256 _amount) external; function liquidate(uint256 _vaultId) external; function liquidatePartial(uint256 _vaultId, uint256 _amount) external; function upgrade(address payable _newVaultsCore) external; function acceptUpgrade(address payable _oldVaultsCore) external; function setDebtNotifier(IDebtNotifier _debtNotifier) external; //Read only function a() external view returns (IAddressProvider); function WETH() external view returns (IWETH); function debtNotifier() external view returns (IDebtNotifier); function state() external view returns (IVaultsCoreState); function cumulativeRates(address _collateralType) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IAccessController { event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; function MANAGER_ROLE() external view returns (bytes32); function MINTER_ROLE() external view returns (bytes32); function hasRole(bytes32 role, address account) external view returns (bool); function getRoleMemberCount(bytes32 role) external view returns (uint256); function getRoleMember(bytes32 role, uint256 index) external view returns (address); function getRoleAdmin(bytes32 role) external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IAddressProvider.sol"; interface ISTABLEX is IERC20 { function mint(address account, uint256 amount) external; function burn(address account, uint256 amount) external; function a() external view returns (IAddressProvider); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../chainlink/AggregatorV3Interface.sol"; import "../interfaces/IAddressProvider.sol"; interface IPriceFeed { event OracleUpdated(address indexed asset, address oracle, address sender); event EurOracleUpdated(address oracle, address sender); function setAssetOracle(address _asset, address _oracle) external; function setEurOracle(address _oracle) external; function a() external view returns (IAddressProvider); function assetOracles(address _asset) external view returns (AggregatorV3Interface); function eurOracle() external view returns (AggregatorV3Interface); function getAssetPrice(address _asset) external view returns (uint256); function convertFrom(address _asset, uint256 _amount) external view returns (uint256); function convertTo(address _asset, uint256 _amount) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "../interfaces/IAddressProvider.sol"; interface IRatesManager { function a() external view returns (IAddressProvider); //current annualized borrow rate function annualizedBorrowRate(uint256 _currentBorrowRate) external pure returns (uint256); //uses current cumulative rate to calculate totalDebt based on baseDebt at time T0 function calculateDebt(uint256 _baseDebt, uint256 _cumulativeRate) external pure returns (uint256); //uses current cumulative rate to calculate baseDebt at time T0 function calculateBaseDebt(uint256 _debt, uint256 _cumulativeRate) external pure returns (uint256); //calculate a new cumulative rate function calculateCumulativeRate( uint256 _borrowRate, uint256 _cumulativeRate, uint256 _timeElapsed ) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "../interfaces/IAddressProvider.sol"; interface IVaultsDataProvider { struct Vault { // borrowedType support USDX / PAR address collateralType; address owner; uint256 collateralBalance; uint256 baseDebt; uint256 createdAt; } //Write function createVault(address _collateralType, address _owner) external returns (uint256); function setCollateralBalance(uint256 _id, uint256 _balance) external; function setBaseDebt(uint256 _id, uint256 _newBaseDebt) external; // Read function a() external view returns (IAddressProvider); function baseDebt(address _collateralType) external view returns (uint256); function vaultCount() external view returns (uint256); function vaults(uint256 _id) external view returns (Vault memory); function vaultOwner(uint256 _id) external view returns (address); function vaultCollateralType(uint256 _id) external view returns (address); function vaultCollateralBalance(uint256 _id) external view returns (uint256); function vaultBaseDebt(uint256 _id) external view returns (uint256); function vaultId(address _collateralType, address _owner) external view returns (uint256); function vaultExists(uint256 _id) external view returns (bool); function vaultDebt(uint256 _vaultId) external view returns (uint256); function debt() external view returns (uint256); function collateralDebt(address _collateralType) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../interfaces/IAddressProvider.sol"; interface IFeeDistributor { event PayeeAdded(address indexed account, uint256 shares); event FeeReleased(uint256 income, uint256 releasedAt); function release() external; function changePayees(address[] memory _payees, uint256[] memory _shares) external; function a() external view returns (IAddressProvider); function lastReleasedAt() external view returns (uint256); function getPayees() external view returns (address[] memory); function totalShares() external view returns (uint256); function shares(address payee) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "./IAccessController.sol"; import "./IConfigProvider.sol"; import "./ISTABLEX.sol"; import "./IPriceFeed.sol"; import "./IRatesManager.sol"; import "./ILiquidationManager.sol"; import "./IVaultsCore.sol"; import "./IVaultsDataProvider.sol"; import "./IFeeDistributor.sol"; interface IAddressProvider { function setAccessController(IAccessController _controller) external; function setConfigProvider(IConfigProvider _config) external; function setVaultsCore(IVaultsCore _core) external; function setStableX(ISTABLEX _stablex) external; function setRatesManager(IRatesManager _ratesManager) external; function setPriceFeed(IPriceFeed _priceFeed) external; function setLiquidationManager(ILiquidationManager _liquidationManager) external; function setVaultsDataProvider(IVaultsDataProvider _vaultsData) external; function setFeeDistributor(IFeeDistributor _feeDistributor) external; function controller() external view returns (IAccessController); function config() external view returns (IConfigProvider); function core() external view returns (IVaultsCore); function stablex() external view returns (ISTABLEX); function ratesManager() external view returns (IRatesManager); function priceFeed() external view returns (IPriceFeed); function liquidationManager() external view returns (ILiquidationManager); function vaultsData() external view returns (IVaultsDataProvider); function feeDistributor() external view returns (IFeeDistributor); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "./IAddressProvider.sol"; import "../v1/interfaces/IVaultsCoreV1.sol"; interface IVaultsCoreState { event CumulativeRateUpdated(address indexed collateralType, uint256 elapsedTime, uint256 newCumulativeRate); //cumulative interest rate from deployment time T0 function initializeRates(address _collateralType) external; function refresh() external; function refreshCollateral(address collateralType) external; function syncState(IVaultsCoreState _stateAddress) external; function syncStateFromV1(IVaultsCoreV1 _core) external; //Read only function a() external view returns (IAddressProvider); function availableIncome() external view returns (uint256); function cumulativeRates(address _collateralType) external view returns (uint256); function lastRefresh(address _collateralType) external view returns (uint256); function synced() external view returns (bool); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256 wad) external; } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import '../../governance/interfaces/IGovernanceAddressProvider.sol'; import './ISupplyMiner.sol'; interface IDebtNotifier { function debtChanged(uint256 _vaultId) external; function setCollateralSupplyMiner(address collateral, ISupplyMiner supplyMiner) external; function a() external view returns (IGovernanceAddressProvider); function collateralSupplyMinerMapping(address collateral) external view returns (ISupplyMiner); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "../interfaces/IAddressProvider.sol"; interface IConfigProvider { struct CollateralConfig { address collateralType; uint256 debtLimit; uint256 liquidationRatio; uint256 minCollateralRatio; uint256 borrowRate; uint256 originationFee; uint256 liquidationBonus; uint256 liquidationFee; } event CollateralUpdated( address indexed collateralType, uint256 debtLimit, uint256 liquidationRatio, uint256 minCollateralRatio, uint256 borrowRate, uint256 originationFee, uint256 liquidationBonus, uint256 liquidationFee ); event CollateralRemoved(address indexed collateralType); function setCollateralConfig( address _collateralType, uint256 _debtLimit, uint256 _liquidationRatio, uint256 _minCollateralRatio, uint256 _borrowRate, uint256 _originationFee, uint256 _liquidationBonus, uint256 _liquidationFee ) external; function removeCollateral(address _collateralType) external; function setCollateralDebtLimit(address _collateralType, uint256 _debtLimit) external; function setCollateralLiquidationRatio(address _collateralType, uint256 _liquidationRatio) external; function setCollateralMinCollateralRatio(address _collateralType, uint256 _minCollateralRatio) external; function setCollateralBorrowRate(address _collateralType, uint256 _borrowRate) external; function setCollateralOriginationFee(address _collateralType, uint256 _originationFee) external; function setCollateralLiquidationBonus(address _collateralType, uint256 _liquidationBonus) external; function setCollateralLiquidationFee(address _collateralType, uint256 _liquidationFee) external; function setMinVotingPeriod(uint256 _minVotingPeriod) external; function setMaxVotingPeriod(uint256 _maxVotingPeriod) external; function setVotingQuorum(uint256 _votingQuorum) external; function setProposalThreshold(uint256 _proposalThreshold) external; function a() external view returns (IAddressProvider); function collateralConfigs(uint256 _id) external view returns (CollateralConfig memory); function collateralIds(address _collateralType) external view returns (uint256); function numCollateralConfigs() external view returns (uint256); function minVotingPeriod() external view returns (uint256); function maxVotingPeriod() external view returns (uint256); function votingQuorum() external view returns (uint256); function proposalThreshold() external view returns (uint256); function collateralDebtLimit(address _collateralType) external view returns (uint256); function collateralLiquidationRatio(address _collateralType) external view returns (uint256); function collateralMinCollateralRatio(address _collateralType) external view returns (uint256); function collateralBorrowRate(address _collateralType) external view returns (uint256); function collateralOriginationFee(address _collateralType) external view returns (uint256); function collateralLiquidationBonus(address _collateralType) external view returns (uint256); function collateralLiquidationFee(address _collateralType) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "../interfaces/IAddressProvider.sol"; interface ILiquidationManager { function a() external view returns (IAddressProvider); function calculateHealthFactor( uint256 _collateralValue, uint256 _vaultDebt, uint256 _minRatio ) external view returns (uint256 healthFactor); function liquidationBonus(address _collateralType, uint256 _amount) external view returns (uint256 bonus); function applyLiquidationDiscount(address _collateralType, uint256 _amount) external view returns (uint256 discountedAmount); function isHealthy( uint256 _collateralValue, uint256 _vaultDebt, uint256 _minRatio ) external view returns (bool); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); 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: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import './IGovernorAlpha.sol'; import './ITimelock.sol'; import './IVotingEscrow.sol'; import '../../interfaces/IAccessController.sol'; import '../../interfaces/IAddressProvider.sol'; import '../../liquidityMining/interfaces/IMIMO.sol'; import '../../liquidityMining/interfaces/IDebtNotifier.sol'; interface IGovernanceAddressProvider { function setParallelAddressProvider(IAddressProvider _parallel) external; function setMIMO(IMIMO _mimo) external; function setDebtNotifier(IDebtNotifier _debtNotifier) external; function setGovernorAlpha(IGovernorAlpha _governorAlpha) external; function setTimelock(ITimelock _timelock) external; function setVotingEscrow(IVotingEscrow _votingEscrow) external; function controller() external view returns (IAccessController); function parallel() external view returns (IAddressProvider); function mimo() external view returns (IMIMO); function debtNotifier() external view returns (IDebtNotifier); function governorAlpha() external view returns (IGovernorAlpha); function timelock() external view returns (ITimelock); function votingEscrow() external view returns (IVotingEscrow); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; interface ISupplyMiner { function baseDebtChanged(address user, uint256 newBaseDebt) external; } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; interface IGovernorAlpha { /// @notice Possible states that a proposal may be in enum ProposalState { Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } struct Proposal { // Unique id for looking up a proposal uint256 id; // Creator of the proposal address proposer; // The timestamp that the proposal will be available for execution, set once the vote succeeds uint256 eta; // the ordered list of target addresses for calls to be made address[] targets; // The ordered list of values (i.e. msg.value) to be passed to the calls to be made uint256[] values; // The ordered list of function signatures to be called string[] signatures; // The ordered list of calldata to be passed to each call bytes[] calldatas; // The timestamp at which voting begins: holders must delegate their votes prior to this timestamp uint256 startTime; // The timestamp at which voting ends: votes must be cast prior to this timestamp uint256 endTime; // Current number of votes in favor of this proposal uint256 forVotes; // Current number of votes in opposition to this proposal uint256 againstVotes; // Flag marking whether the proposal has been canceled bool canceled; // Flag marking whether the proposal has been executed bool executed; // Receipts of ballots for the entire set of voters mapping(address => Receipt) receipts; } /// @notice Ballot receipt record for a voter struct Receipt { // Whether or not a vote has been cast bool hasVoted; // Whether or not the voter supports the proposal bool support; // The number of votes the voter had, which were cast uint256 votes; } /// @notice An event emitted when a new proposal is created event ProposalCreated( uint256 id, address proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 startTime, uint256 endTime, string description ); /// @notice An event emitted when a vote has been cast on a proposal event VoteCast(address voter, uint256 proposalId, bool support, uint256 votes); /// @notice An event emitted when a proposal has been canceled event ProposalCanceled(uint256 id); /// @notice An event emitted when a proposal has been queued in the Timelock event ProposalQueued(uint256 id, uint256 eta); /// @notice An event emitted when a proposal has been executed in the Timelock event ProposalExecuted(uint256 id); function propose( address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description, uint256 endTime ) external returns (uint256); function queue(uint256 proposalId) external; function execute(uint256 proposalId) external payable; function cancel(uint256 proposalId) external; function castVote(uint256 proposalId, bool support) external; function getActions(uint256 proposalId) external view returns ( address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas ); function getReceipt(uint256 proposalId, address voter) external view returns (Receipt memory); function state(uint256 proposalId) external view returns (ProposalState); function quorumVotes() external view returns (uint256); function proposalThreshold() external view returns (uint256); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.6.12; interface ITimelock { event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint256 indexed newDelay); event CancelTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); event ExecuteTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); event QueueTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); function acceptAdmin() external; function queueTransaction( address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta ) external returns (bytes32); function cancelTransaction( address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta ) external; function executeTransaction( address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta ) external payable returns (bytes memory); function delay() external view returns (uint256); function GRACE_PERIOD() external view returns (uint256); function queuedTransactions(bytes32 hash) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '../../liquidityMining/interfaces/IGenericMiner.sol'; interface IVotingEscrow { enum LockAction { CREATE_LOCK, INCREASE_LOCK_AMOUNT, INCREASE_LOCK_TIME } struct LockedBalance { uint256 amount; uint256 end; } /** Shared Events */ event Deposit(address indexed provider, uint256 value, uint256 locktime, LockAction indexed action, uint256 ts); event Withdraw(address indexed provider, uint256 value, uint256 ts); event Expired(); function createLock(uint256 _value, uint256 _unlockTime) external; function increaseLockAmount(uint256 _value) external; function increaseLockLength(uint256 _unlockTime) external; function withdraw() external; function expireContract() external; function setMiner(IGenericMiner _miner) external; function setMinimumLockTime(uint256 _minimumLockTime) external; function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint256); function balanceOf(address _owner) external view returns (uint256); function balanceOfAt(address _owner, uint256 _blockTime) external view returns (uint256); function stakingToken() external view returns (IERC20); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IMIMO is IERC20 { function burn(address account, uint256 amount) external; function mint(address account, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import '@openzeppelin/contracts/math/SafeMath.sol'; import '../../interfaces/IAddressProvider.sol'; import '../../governance/interfaces/IGovernanceAddressProvider.sol'; interface IGenericMiner { struct UserInfo { uint256 stake; uint256 accAmountPerShare; // User's accAmountPerShare } /// @dev This emit when a users' productivity has changed /// It emits with the user's address and the the value after the change. event StakeIncreased(address indexed user, uint256 stake); /// @dev This emit when a users' productivity has changed /// It emits with the user's address and the the value after the change. event StakeDecreased(address indexed user, uint256 stake); function releaseMIMO(address _user) external; function a() external view returns (IGovernanceAddressProvider); function stake(address _user) external view returns (uint256); function pendingMIMO(address _user) external view returns (uint256); function totalStake() external view returns (uint256); function userInfo(address _user) external view returns (UserInfo memory); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IVaultsDataProviderV1.sol"; import "./interfaces/IAddressProviderV1.sol"; contract VaultsDataProviderV1 is IVaultsDataProviderV1 { using SafeMath for uint256; IAddressProviderV1 public override a; uint256 public override vaultCount = 0; mapping(address => uint256) public override baseDebt; mapping(uint256 => Vault) private _vaults; mapping(address => mapping(address => uint256)) private _vaultOwners; modifier onlyVaultsCore() { require(msg.sender == address(a.core()), "Caller is not VaultsCore"); _; } constructor(IAddressProviderV1 _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } /** Opens a new vault. @dev only the vaultsCore module can call this function @param _collateralType address to the collateral asset e.g. WETH @param _owner the owner of the new vault. */ function createVault(address _collateralType, address _owner) public override onlyVaultsCore returns (uint256) { require(_collateralType != address(0)); require(_owner != address(0)); uint256 newId = ++vaultCount; require(_collateralType != address(0), "collateralType unknown"); Vault memory v = Vault({ collateralType: _collateralType, owner: _owner, collateralBalance: 0, baseDebt: 0, createdAt: block.timestamp }); _vaults[newId] = v; _vaultOwners[_owner][_collateralType] = newId; return newId; } /** Set the collateral balance of a vault. @dev only the vaultsCore module can call this function @param _id Vault ID of which the collateral balance will be updated @param _balance the new balance of the vault. */ function setCollateralBalance(uint256 _id, uint256 _balance) public override onlyVaultsCore { require(vaultExists(_id), "Vault not found."); Vault storage v = _vaults[_id]; v.collateralBalance = _balance; } /** Set the base debt of a vault. @dev only the vaultsCore module can call this function @param _id Vault ID of which the base debt will be updated @param _newBaseDebt the new base debt of the vault. */ function setBaseDebt(uint256 _id, uint256 _newBaseDebt) public override onlyVaultsCore { Vault storage _vault = _vaults[_id]; if (_newBaseDebt > _vault.baseDebt) { uint256 increase = _newBaseDebt.sub(_vault.baseDebt); baseDebt[_vault.collateralType] = baseDebt[_vault.collateralType].add(increase); } else { uint256 decrease = _vault.baseDebt.sub(_newBaseDebt); baseDebt[_vault.collateralType] = baseDebt[_vault.collateralType].sub(decrease); } _vault.baseDebt = _newBaseDebt; } /** Get a vault by vault ID. @param _id The vault's ID to be retrieved */ function vaults(uint256 _id) public view override returns (Vault memory) { Vault memory v = _vaults[_id]; return v; } /** Get the owner of a vault. @param _id the ID of the vault @return owner of the vault */ function vaultOwner(uint256 _id) public view override returns (address) { return _vaults[_id].owner; } /** Get the collateral type of a vault. @param _id the ID of the vault @return address for the collateral type of the vault */ function vaultCollateralType(uint256 _id) public view override returns (address) { return _vaults[_id].collateralType; } /** Get the collateral balance of a vault. @param _id the ID of the vault @return collateral balance of the vault */ function vaultCollateralBalance(uint256 _id) public view override returns (uint256) { return _vaults[_id].collateralBalance; } /** Get the base debt of a vault. @param _id the ID of the vault @return base debt of the vault */ function vaultBaseDebt(uint256 _id) public view override returns (uint256) { return _vaults[_id].baseDebt; } /** Retrieve the vault id for a specified owner and collateral type. @dev returns 0 for non-existing vaults @param _collateralType address of the collateral type (Eg: WETH) @param _owner address of the owner of the vault @return vault id of the vault or 0 */ function vaultId(address _collateralType, address _owner) public view override returns (uint256) { return _vaultOwners[_owner][_collateralType]; } /** Checks if a specified vault exists. @param _id the ID of the vault @return boolean if the vault exists */ function vaultExists(uint256 _id) public view override returns (bool) { Vault memory v = _vaults[_id]; return v.collateralType != address(0); } /** Calculated the total outstanding debt for all vaults and all collateral types. @dev uses the existing cumulative rate. Call `refresh()` on `VaultsCore` to make sure it's up to date. @return total debt of the platform */ function debt() public view override returns (uint256) { uint256 total = 0; for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) { address collateralType = a.config().collateralConfigs(i).collateralType; total = total.add(collateralDebt(collateralType)); } return total; } /** Calculated the total outstanding debt for all vaults of a specific collateral type. @dev uses the existing cumulative rate. Call `refreshCollateral()` on `VaultsCore` to make sure it's up to date. @param _collateralType address of the collateral type (Eg: WETH) @return total debt of the platform of one collateral type */ function collateralDebt(address _collateralType) public view override returns (uint256) { return a.ratesManager().calculateDebt(baseDebt[_collateralType], a.core().cumulativeRates(_collateralType)); } /** Calculated the total outstanding debt for a specific vault. @dev uses the existing cumulative rate. Call `refreshCollateral()` on `VaultsCore` to make sure it's up to date. @param _vaultId the ID of the vault @return total debt of one vault */ function vaultDebt(uint256 _vaultId) public view override returns (uint256) { IVaultsDataProviderV1.Vault memory v = vaults(_vaultId); return a.ratesManager().calculateDebt(v.baseDebt, a.core().cumulativeRates(v.collateralType)); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import './IAddressProviderV1.sol'; interface IVaultsDataProviderV1 { struct Vault { // borrowedType support USDX / PAR address collateralType; address owner; uint256 collateralBalance; uint256 baseDebt; uint256 createdAt; } //Write function createVault(address _collateralType, address _owner) external returns (uint256); function setCollateralBalance(uint256 _id, uint256 _balance) external; function setBaseDebt(uint256 _id, uint256 _newBaseDebt) external; function a() external view returns (IAddressProviderV1); // Read function baseDebt(address _collateralType) external view returns (uint256); function vaultCount() external view returns (uint256); function vaults(uint256 _id) external view returns (Vault memory); function vaultOwner(uint256 _id) external view returns (address); function vaultCollateralType(uint256 _id) external view returns (address); function vaultCollateralBalance(uint256 _id) external view returns (uint256); function vaultBaseDebt(uint256 _id) external view returns (uint256); function vaultId(address _collateralType, address _owner) external view returns (uint256); function vaultExists(uint256 _id) external view returns (bool); function vaultDebt(uint256 _vaultId) external view returns (uint256); function debt() external view returns (uint256); function collateralDebt(address _collateralType) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/WadRayMath.sol"; import "./interfaces/IAddressProviderV1.sol"; import "./interfaces/IConfigProviderV1.sol"; import "./interfaces/ILiquidationManagerV1.sol"; contract LiquidationManagerV1 is ILiquidationManagerV1, ReentrancyGuard { using SafeMath for uint256; using WadRayMath for uint256; IAddressProviderV1 public override a; uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; // 1 uint256 public constant FULL_LIQUIDIATION_TRESHOLD = 100e18; // 100 USDX, vaults below 100 USDX can be liquidated in full constructor(IAddressProviderV1 _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } /** Check if the health factor is above or equal to 1. @param _collateralType address of the collateral type @param _collateralValue value of the collateral in stableX currency @param _vaultDebt outstanding debt to which the collateral balance shall be compared @return boolean if the health factor is >= 1. */ function isHealthy( address _collateralType, uint256 _collateralValue, uint256 _vaultDebt ) public view override returns (bool) { uint256 healthFactor = calculateHealthFactor(_collateralType, _collateralValue, _vaultDebt); return healthFactor >= HEALTH_FACTOR_LIQUIDATION_THRESHOLD; } /** Calculate the healthfactor of a debt balance @param _collateralType address of the collateral type @param _collateralValue value of the collateral in stableX currency @param _vaultDebt outstanding debt to which the collateral balance shall be compared @return healthFactor */ function calculateHealthFactor( address _collateralType, uint256 _collateralValue, uint256 _vaultDebt ) public view override returns (uint256 healthFactor) { if (_vaultDebt == 0) return WadRayMath.wad(); // CurrentCollateralizationRatio = deposited ETH in USD / debt in USD uint256 collateralizationRatio = _collateralValue.wadDiv(_vaultDebt); // Healthfactor = CurrentCollateralizationRatio / MinimumCollateralizationRatio uint256 collateralId = a.config().collateralIds(_collateralType); require(collateralId > 0, "collateral not supported"); uint256 minRatio = a.config().collateralConfigs(collateralId).minCollateralRatio; if (minRatio > 0) { return collateralizationRatio.wadDiv(minRatio); } return 1e18; // 1 } /** Calculate the liquidation bonus for a specified amount @param _amount amount for which the liquidation bonus shall be calculated @return bonus the liquidation bonus to pay out */ function liquidationBonus(uint256 _amount) public view override returns (uint256 bonus) { return _amount.wadMul(IConfigProviderV1(address(a.config())).liquidationBonus()); } /** Apply the liquidation bonus to a balance as a discount. @param _amount the balance on which to apply to liquidation bonus as a discount. @return discountedAmount */ function applyLiquidationDiscount(uint256 _amount) public view override returns (uint256 discountedAmount) { return _amount.wadDiv(IConfigProviderV1(address(a.config())).liquidationBonus().add(WadRayMath.wad())); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "../interfaces/IAddressProvider.sol"; import "../interfaces/IVaultsCore.sol"; import "../interfaces/IAccessController.sol"; import "../interfaces/IConfigProvider.sol"; import "../interfaces/ISTABLEX.sol"; import "../interfaces/IPriceFeed.sol"; import "../interfaces/IRatesManager.sol"; import "../interfaces/IVaultsDataProvider.sol"; import "./interfaces/IConfigProviderV1.sol"; import "./interfaces/ILiquidationManagerV1.sol"; import "./interfaces/IVaultsCoreV1.sol"; contract AddressProviderV1 is IAddressProvider { IAccessController public override controller; IConfigProvider public override config; IVaultsCore public override core; ISTABLEX public override stablex; IRatesManager public override ratesManager; IPriceFeed public override priceFeed; ILiquidationManager public override liquidationManager; IVaultsDataProvider public override vaultsData; IFeeDistributor public override feeDistributor; constructor(IAccessController _controller) public { controller = _controller; } modifier onlyManager() { require(controller.hasRole(controller.MANAGER_ROLE(), msg.sender), "Caller is not a Manager"); _; } function setAccessController(IAccessController _controller) public override onlyManager { require(address(_controller) != address(0)); controller = _controller; } function setConfigProvider(IConfigProvider _config) public override onlyManager { require(address(_config) != address(0)); config = _config; } function setVaultsCore(IVaultsCore _core) public override onlyManager { require(address(_core) != address(0)); core = _core; } function setStableX(ISTABLEX _stablex) public override onlyManager { require(address(_stablex) != address(0)); stablex = _stablex; } function setRatesManager(IRatesManager _ratesManager) public override onlyManager { require(address(_ratesManager) != address(0)); ratesManager = _ratesManager; } function setLiquidationManager(ILiquidationManager _liquidationManager) public override onlyManager { require(address(_liquidationManager) != address(0)); liquidationManager = _liquidationManager; } function setPriceFeed(IPriceFeed _priceFeed) public override onlyManager { require(address(_priceFeed) != address(0)); priceFeed = _priceFeed; } function setVaultsDataProvider(IVaultsDataProvider _vaultsData) public override onlyManager { require(address(_vaultsData) != address(0)); vaultsData = _vaultsData; } function setFeeDistributor(IFeeDistributor _feeDistributor) public override onlyManager { require(address(_feeDistributor) != address(0)); feeDistributor = _feeDistributor; } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "../libraries/WadRayMath.sol"; import "./interfaces/IConfigProviderV1.sol"; import "./interfaces/IAddressProviderV1.sol"; import "./interfaces/IVaultsCoreV1.sol"; contract ConfigProviderV1 is IConfigProviderV1 { IAddressProviderV1 public override a; mapping(uint256 => CollateralConfig) private _collateralConfigs; //indexing starts at 1 mapping(address => uint256) public override collateralIds; uint256 public override numCollateralConfigs; uint256 public override liquidationBonus = 5e16; // 5% constructor(IAddressProviderV1 _addresses) public { a = _addresses; } modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not a Manager"); _; } /** Creates or overwrites an existing config for a collateral type @param _collateralType address of the collateral type @param _debtLimit the debt ceiling for the collateral type @param _minCollateralRatio the minimum ratio to maintain to avoid liquidation @param _borrowRate the borrowing rate specified in 1 second interval in RAY accuracy. @param _originationFee an optional origination fee for newly created debt. Can be 0. */ function setCollateralConfig( address _collateralType, uint256 _debtLimit, uint256 _minCollateralRatio, uint256 _borrowRate, uint256 _originationFee ) public override onlyManager { require(address(_collateralType) != address(0)); if (collateralIds[_collateralType] == 0) { //new collateral IVaultsCoreV1(address(a.core())).initializeRates(_collateralType); CollateralConfig memory config = CollateralConfig({ collateralType: _collateralType, debtLimit: _debtLimit, minCollateralRatio: _minCollateralRatio, borrowRate: _borrowRate, originationFee: _originationFee }); numCollateralConfigs++; _collateralConfigs[numCollateralConfigs] = config; collateralIds[_collateralType] = numCollateralConfigs; } else { // Update collateral config IVaultsCoreV1(address(a.core())).refreshCollateral(_collateralType); uint256 id = collateralIds[_collateralType]; _collateralConfigs[id].collateralType = _collateralType; _collateralConfigs[id].debtLimit = _debtLimit; _collateralConfigs[id].minCollateralRatio = _minCollateralRatio; _collateralConfigs[id].borrowRate = _borrowRate; _collateralConfigs[id].originationFee = _originationFee; } emit CollateralUpdated(_collateralType, _debtLimit, _minCollateralRatio, _borrowRate, _originationFee); } function _emitUpdateEvent(address _collateralType) internal { emit CollateralUpdated( _collateralType, _collateralConfigs[collateralIds[_collateralType]].debtLimit, _collateralConfigs[collateralIds[_collateralType]].minCollateralRatio, _collateralConfigs[collateralIds[_collateralType]].borrowRate, _collateralConfigs[collateralIds[_collateralType]].originationFee ); } /** Remove the config for a collateral type @param _collateralType address of the collateral type */ function removeCollateral(address _collateralType) public override onlyManager { uint256 id = collateralIds[_collateralType]; require(id != 0, "collateral does not exist"); collateralIds[_collateralType] = 0; _collateralConfigs[id] = _collateralConfigs[numCollateralConfigs]; //move last entry forward collateralIds[_collateralConfigs[id].collateralType] = id; //update id for last entry delete _collateralConfigs[numCollateralConfigs]; numCollateralConfigs--; emit CollateralRemoved(_collateralType); } /** Sets the debt limit for a collateral type @param _collateralType address of the collateral type @param _debtLimit the new debt limit */ function setCollateralDebtLimit(address _collateralType, uint256 _debtLimit) public override onlyManager { _collateralConfigs[collateralIds[_collateralType]].debtLimit = _debtLimit; _emitUpdateEvent(_collateralType); } /** Sets the minimum collateralization ratio for a collateral type @dev this is the liquidation treshold under which a vault is considered open for liquidation. @param _collateralType address of the collateral type @param _minCollateralRatio the new minimum collateralization ratio */ function setCollateralMinCollateralRatio(address _collateralType, uint256 _minCollateralRatio) public override onlyManager { _collateralConfigs[collateralIds[_collateralType]].minCollateralRatio = _minCollateralRatio; _emitUpdateEvent(_collateralType); } /** Sets the borrowing rate for a collateral type @dev borrowing rate is specified for a 1 sec interval and accurancy is in RAY. @param _collateralType address of the collateral type @param _borrowRate the new borrowing rate for a 1 sec interval */ function setCollateralBorrowRate(address _collateralType, uint256 _borrowRate) public override onlyManager { IVaultsCoreV1(address(a.core())).refreshCollateral(_collateralType); _collateralConfigs[collateralIds[_collateralType]].borrowRate = _borrowRate; _emitUpdateEvent(_collateralType); } /** Sets the origiation fee for a collateral type @dev this rate is applied as a one time fee for new borrowing and is specified in WAD @param _collateralType address of the collateral type @param _originationFee new origination fee in WAD */ function setCollateralOriginationFee(address _collateralType, uint256 _originationFee) public override onlyManager { _collateralConfigs[collateralIds[_collateralType]].originationFee = _originationFee; _emitUpdateEvent(_collateralType); } /** Get the debt limit for a collateral type @dev this is a platform wide limit for new debt issuance against a specific collateral type @param _collateralType address of the collateral type */ function collateralDebtLimit(address _collateralType) public view override returns (uint256) { return _collateralConfigs[collateralIds[_collateralType]].debtLimit; } /** Get the minimum collateralization ratio for a collateral type @dev this is the liquidation treshold under which a vault is considered open for liquidation. @param _collateralType address of the collateral type */ function collateralMinCollateralRatio(address _collateralType) public view override returns (uint256) { return _collateralConfigs[collateralIds[_collateralType]].minCollateralRatio; } /** Get the borrowing rate for a collateral type @dev borrowing rate is specified for a 1 sec interval and accurancy is in RAY. @param _collateralType address of the collateral type */ function collateralBorrowRate(address _collateralType) public view override returns (uint256) { return _collateralConfigs[collateralIds[_collateralType]].borrowRate; } /** Get the origiation fee for a collateral type @dev this rate is applied as a one time fee for new borrowing and is specified in WAD @param _collateralType address of the collateral type */ function collateralOriginationFee(address _collateralType) public view override returns (uint256) { return _collateralConfigs[collateralIds[_collateralType]].originationFee; } /** Set the platform wide incentive for liquidations. @dev the liquidation bonus is specified in WAD @param _bonus the liquidation bonus to be paid to liquidators */ function setLiquidationBonus(uint256 _bonus) public override onlyManager { liquidationBonus = _bonus; } /** Retreives the entire config for a specific config id. @param _id the ID of the conifg to be returned */ function collateralConfigs(uint256 _id) public view override returns (CollateralConfig memory) { require(_id <= numCollateralConfigs, "Invalid config id"); return _collateralConfigs[_id]; } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../v1/interfaces/IConfigProviderV1.sol"; import "../v1/interfaces/IVaultsCoreV1.sol"; import "../v1/interfaces/IFeeDistributorV1.sol"; import "../interfaces/IAddressProvider.sol"; import "../interfaces/IVaultsCore.sol"; import "../interfaces/IVaultsCoreState.sol"; import "../interfaces/ILiquidationManager.sol"; import "../interfaces/IConfigProvider.sol"; import "../interfaces/IFeeDistributor.sol"; import "../liquidityMining/interfaces/IDebtNotifier.sol"; contract Upgrade { using SafeMath for uint256; uint256 public constant LIQUIDATION_BONUS = 5e16; // 5% IAddressProvider public a; IVaultsCore public core; IVaultsCoreState public coreState; ILiquidationManager public liquidationManager; IConfigProvider public config; IFeeDistributor public feeDistributor; IDebtNotifier public debtNotifier; IPriceFeed public priceFeed; address public bpool; modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender)); _; } constructor( IAddressProvider _addresses, IVaultsCore _core, IVaultsCoreState _coreState, ILiquidationManager _liquidationManager, IConfigProvider _config, IFeeDistributor _feeDistributor, IDebtNotifier _debtNotifier, IPriceFeed _priceFeed, address _bpool ) public { require(address(_addresses) != address(0)); require(address(_core) != address(0)); require(address(_coreState) != address(0)); require(address(_liquidationManager) != address(0)); require(address(_config) != address(0)); require(address(_feeDistributor) != address(0)); require(address(_debtNotifier) != address(0)); require(address(_priceFeed) != address(0)); require(_bpool != address(0)); a = _addresses; core = _core; coreState = _coreState; liquidationManager = _liquidationManager; config = _config; feeDistributor = _feeDistributor; debtNotifier = _debtNotifier; priceFeed = _priceFeed; bpool = _bpool; } function upgrade() public onlyManager { IConfigProviderV1 oldConfig = IConfigProviderV1(address(a.config())); IPriceFeed oldPriceFeed = IPriceFeed(address(a.priceFeed())); IVaultsCoreV1 oldCore = IVaultsCoreV1(address(a.core())); IFeeDistributorV1 oldFeeDistributor = IFeeDistributorV1(address(a.feeDistributor())); bytes32 MINTER_ROLE = a.controller().MINTER_ROLE(); bytes32 MANAGER_ROLE = a.controller().MANAGER_ROLE(); bytes32 DEFAULT_ADMIN_ROLE = 0x0000000000000000000000000000000000000000000000000000000000000000; a.controller().grantRole(MANAGER_ROLE, address(this)); a.controller().grantRole(MINTER_ROLE, address(core)); a.controller().grantRole(MINTER_ROLE, address(feeDistributor)); oldCore.refresh(); if (oldCore.availableIncome() > 0) { oldFeeDistributor.release(); } a.controller().revokeRole(MINTER_ROLE, address(a.core())); a.controller().revokeRole(MINTER_ROLE, address(a.feeDistributor())); oldCore.upgrade(payable(address(core))); a.setVaultsCore(core); a.setConfigProvider(config); a.setLiquidationManager(liquidationManager); a.setFeeDistributor(feeDistributor); a.setPriceFeed(priceFeed); priceFeed.setEurOracle(address(oldPriceFeed.eurOracle())); uint256 numCollateralConfigs = oldConfig.numCollateralConfigs(); for (uint256 i = 1; i <= numCollateralConfigs; i++) { IConfigProviderV1.CollateralConfig memory collateralConfig = oldConfig.collateralConfigs(i); config.setCollateralConfig( collateralConfig.collateralType, collateralConfig.debtLimit, collateralConfig.minCollateralRatio, collateralConfig.minCollateralRatio, collateralConfig.borrowRate, collateralConfig.originationFee, LIQUIDATION_BONUS, 0 ); priceFeed.setAssetOracle( collateralConfig.collateralType, address(oldPriceFeed.assetOracles(collateralConfig.collateralType)) ); } coreState.syncStateFromV1(oldCore); core.acceptUpgrade(payable(address(oldCore))); core.setDebtNotifier(debtNotifier); debtNotifier.a().setDebtNotifier(debtNotifier); address[] memory payees = new address[](2); payees[0] = bpool; payees[1] = address(core); uint256[] memory shares = new uint256[](2); shares[0] = uint256(90); shares[1] = uint256(10); feeDistributor.changePayees(payees, shares); a.controller().revokeRole(MANAGER_ROLE, address(this)); a.controller().revokeRole(DEFAULT_ADMIN_ROLE, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import './IAddressProviderV1.sol'; interface IFeeDistributorV1 { event PayeeAdded(address indexed account, uint256 shares); event FeeReleased(uint256 income, uint256 releasedAt); function release() external; function changePayees(address[] memory _payees, uint256[] memory _shares) external; function a() external view returns (IAddressProviderV1); function lastReleasedAt() external view returns (uint256); function getPayees() external view returns (address[] memory); function totalShares() external view returns (uint256); function shares(address payee) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../liquidityMining/interfaces/IMIMO.sol"; import "../liquidityMining/interfaces/IMIMODistributor.sol"; import "../liquidityMining/interfaces/ISupplyMiner.sol"; import "../liquidityMining/interfaces/IDemandMiner.sol"; import "../liquidityMining/interfaces/IDebtNotifier.sol"; import "../libraries/WadRayMath.sol"; import "../governance/interfaces/IGovernanceAddressProvider.sol"; import "../governance/interfaces/IVotingEscrow.sol"; import "../interfaces/IAddressProvider.sol"; contract MIMODeployment { IGovernanceAddressProvider public ga; IMIMO public mimo; IMIMODistributor public mimoDistributor; ISupplyMiner public wethSupplyMiner; ISupplyMiner public wbtcSupplyMiner; ISupplyMiner public usdcSupplyMiner; IDemandMiner public demandMiner; IDebtNotifier public debtNotifier; IVotingEscrow public votingEscrow; address public weth; address public wbtc; address public usdc; modifier onlyManager() { require(ga.controller().hasRole(ga.controller().MANAGER_ROLE(), msg.sender), "Caller is not Manager"); _; } constructor( IGovernanceAddressProvider _ga, IMIMO _mimo, IMIMODistributor _mimoDistributor, ISupplyMiner _wethSupplyMiner, ISupplyMiner _wbtcSupplyMiner, ISupplyMiner _usdcSupplyMiner, IDemandMiner _demandMiner, IDebtNotifier _debtNotifier, IVotingEscrow _votingEscrow, address _weth, address _wbtc, address _usdc ) public { require(address(_ga) != address(0)); require(address(_mimo) != address(0)); require(address(_mimoDistributor) != address(0)); require(address(_wethSupplyMiner) != address(0)); require(address(_wbtcSupplyMiner) != address(0)); require(address(_usdcSupplyMiner) != address(0)); require(address(_demandMiner) != address(0)); require(address(_debtNotifier) != address(0)); require(address(_votingEscrow) != address(0)); require(_weth != address(0)); require(_wbtc != address(0)); require(_usdc != address(0)); ga = _ga; mimo = _mimo; mimoDistributor = _mimoDistributor; wethSupplyMiner = _wethSupplyMiner; wbtcSupplyMiner = _wbtcSupplyMiner; usdcSupplyMiner = _usdcSupplyMiner; demandMiner = _demandMiner; debtNotifier = _debtNotifier; votingEscrow = _votingEscrow; weth = _weth; wbtc = _wbtc; usdc = _usdc; } function setup() public onlyManager { //IAddressProvider parallel = a.parallel(); //bytes32 MIMO_MINTER_ROLE = keccak256("MIMO_MINTER_ROLE"); //bytes32 DEFAULT_ADMIN_ROLE = 0x0000000000000000000000000000000000000000000000000000000000000000; ga.setMIMO(mimo); ga.setVotingEscrow(votingEscrow); debtNotifier.setCollateralSupplyMiner(weth, wethSupplyMiner); debtNotifier.setCollateralSupplyMiner(wbtc, wbtcSupplyMiner); debtNotifier.setCollateralSupplyMiner(usdc, usdcSupplyMiner); address[] memory payees = new address[](4); payees[0] = address(wethSupplyMiner); payees[1] = address(wbtcSupplyMiner); payees[2] = address(usdcSupplyMiner); payees[3] = address(demandMiner); uint256[] memory shares = new uint256[](4); shares[0] = uint256(20); shares[1] = uint256(25); shares[2] = uint256(5); shares[3] = uint256(50); mimoDistributor.changePayees(payees, shares); bytes32 MANAGER_ROLE = ga.controller().MANAGER_ROLE(); ga.controller().renounceRole(MANAGER_ROLE, address(this)); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import '../../governance/interfaces/IGovernanceAddressProvider.sol'; import './IBaseDistributor.sol'; interface IMIMODistributorExtension { function startTime() external view returns (uint256); function currentIssuance() external view returns (uint256); function weeklyIssuanceAt(uint256 timestamp) external view returns (uint256); function totalSupplyAt(uint256 timestamp) external view returns (uint256); } interface IMIMODistributor is IBaseDistributor, IMIMODistributorExtension {} // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IDemandMiner { function deposit(uint256 amount) external; function withdraw(uint256 amount) external; function token() external view returns (IERC20); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import '../../governance/interfaces/IGovernanceAddressProvider.sol'; interface IBaseDistributor { event PayeeAdded(address account, uint256 shares); event TokensReleased(uint256 newTokens, uint256 releasedAt); /** Public function to release the accumulated new MIMO tokens to the payees. @dev anyone can call this. */ function release() external; /** Updates the payee configuration to a new one. @dev will release existing fees before the update. @param _payees Array of payees @param _shares Array of shares for each payee */ function changePayees(address[] memory _payees, uint256[] memory _shares) external; function totalShares() external view returns (uint256); function shares(address) external view returns (uint256); function a() external view returns (IGovernanceAddressProvider); function mintableTokens() external view returns (uint256); /** Get current configured payees. @return array of current payees. */ function getPayees() external view returns (address[] memory); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/IAddressProvider.sol"; import "../interfaces/IVaultsDataProvider.sol"; import "../interfaces/IVaultsCore.sol"; contract RepayVault { using SafeERC20 for IERC20; using SafeMath for uint256; uint256 public constant REPAY_PER_VAULT = 10 ether; IAddressProvider public a; constructor(IAddressProvider _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not Manager"); _; } function repay() public onlyManager { IVaultsCore core = a.core(); IVaultsDataProvider vaultsData = a.vaultsData(); uint256 vaultCount = a.vaultsData().vaultCount(); for (uint256 vaultId = 1; vaultId <= vaultCount; vaultId++) { uint256 baseDebt = vaultsData.vaultBaseDebt(vaultId); //if (vaultId==28 || vaultId==29 || vaultId==30 || vaultId==31 || vaultId==32 || vaultId==33 || vaultId==35){ // continue; //} if (baseDebt == 0) { continue; } core.repay(vaultId, REPAY_PER_VAULT); } IERC20 par = IERC20(a.stablex()); par.safeTransfer(msg.sender, par.balanceOf(address(this))); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/WadRayMath.sol"; import "../interfaces/IVaultsCore.sol"; import "../interfaces/IAddressProvider.sol"; import "../interfaces/IWETH.sol"; import "../interfaces/IVaultsCoreState.sol"; import "../liquidityMining/interfaces/IDebtNotifier.sol"; contract VaultsCore is IVaultsCore, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; using WadRayMath for uint256; uint256 internal constant _MAX_INT = 2**256 - 1; IAddressProvider public override a; IWETH public override WETH; IVaultsCoreState public override state; IDebtNotifier public override debtNotifier; modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender)); _; } modifier onlyVaultOwner(uint256 _vaultId) { require(a.vaultsData().vaultOwner(_vaultId) == msg.sender); _; } constructor( IAddressProvider _addresses, IWETH _IWETH, IVaultsCoreState _vaultsCoreState ) public { require(address(_addresses) != address(0)); require(address(_IWETH) != address(0)); require(address(_vaultsCoreState) != address(0)); a = _addresses; WETH = _IWETH; state = _vaultsCoreState; } // For a contract to receive ETH, it needs to have a payable fallback function // https://ethereum.stackexchange.com/a/47415 receive() external payable { require(msg.sender == address(WETH)); } /* Allow smooth upgrading of the vaultscore. @dev this function approves token transfers to the new vaultscore of both stablex and all configured collateral types @param _newVaultsCore address of the new vaultscore */ function upgrade(address payable _newVaultsCore) public override onlyManager { require(address(_newVaultsCore) != address(0)); require(a.stablex().approve(_newVaultsCore, _MAX_INT)); for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) { address collateralType = a.config().collateralConfigs(i).collateralType; IERC20 asset = IERC20(collateralType); asset.safeApprove(_newVaultsCore, _MAX_INT); } } /* Allow smooth upgrading of the VaultsCore. @dev this function transfers both PAR and all configured collateral types to the new vaultscore. */ function acceptUpgrade(address payable _oldVaultsCore) public override onlyManager { IERC20 stableX = IERC20(a.stablex()); stableX.safeTransferFrom(_oldVaultsCore, address(this), stableX.balanceOf(_oldVaultsCore)); for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) { address collateralType = a.config().collateralConfigs(i).collateralType; IERC20 asset = IERC20(collateralType); asset.safeTransferFrom(_oldVaultsCore, address(this), asset.balanceOf(_oldVaultsCore)); } } /** Configure the debt notifier. @param _debtNotifier the new DebtNotifier module address. **/ function setDebtNotifier(IDebtNotifier _debtNotifier) public override onlyManager { require(address(_debtNotifier) != address(0)); debtNotifier = _debtNotifier; } /** Deposit an ERC20 token into the vault of the msg.sender as collateral @dev A new vault is created if no vault exists for the `msg.sender` with the specified collateral type. this function uses `transferFrom()` and requires pre-approval via `approve()` on the ERC20. @param _collateralType the address of the collateral type to be deposited @param _amount the amount of tokens to be deposited in WEI. **/ function deposit(address _collateralType, uint256 _amount) public override { require(a.config().collateralIds(_collateralType) != 0); IERC20 asset = IERC20(_collateralType); asset.safeTransferFrom(msg.sender, address(this), _amount); _addCollateralToVault(_collateralType, _amount); } /** Wraps ETH and deposits WETH into the vault of the msg.sender as collateral @dev A new vault is created if no WETH vault exists **/ function depositETH() public payable override { WETH.deposit{ value: msg.value }(); _addCollateralToVault(address(WETH), msg.value); } /** Deposit an ERC20 token into the specified vault as collateral @dev this function uses `transferFrom()` and requires pre-approval via `approve()` on the ERC20. @param _vaultId the address of the collateral type to be deposited @param _amount the amount of tokens to be deposited in WEI. **/ function depositByVaultId(uint256 _vaultId, uint256 _amount) public override { IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId); require(v.collateralType != address(0)); IERC20 asset = IERC20(v.collateralType); asset.safeTransferFrom(msg.sender, address(this), _amount); _addCollateralToVaultById(_vaultId, _amount); } /** Wraps ETH and deposits WETH into the specified vault as collateral @dev this function uses `transferFrom()` and requires pre-approval via `approve()` on the ERC20. @param _vaultId the address of the collateral type to be deposited **/ function depositETHByVaultId(uint256 _vaultId) public payable override { IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId); require(v.collateralType == address(WETH)); WETH.deposit{ value: msg.value }(); _addCollateralToVaultById(_vaultId, msg.value); } /** Deposit an ERC20 token into the vault of the msg.sender as collateral and borrows the specified amount of tokens in WEI @dev see deposit() and borrow() @param _collateralType the address of the collateral type to be deposited @param _depositAmount the amount of tokens to be deposited in WEI. @param _borrowAmount the amount of borrowed StableX tokens in WEI. **/ function depositAndBorrow( address _collateralType, uint256 _depositAmount, uint256 _borrowAmount ) public override { deposit(_collateralType, _depositAmount); uint256 vaultId = a.vaultsData().vaultId(_collateralType, msg.sender); borrow(vaultId, _borrowAmount); } /** Wraps ETH and deposits WETH into the vault of the msg.sender as collateral and borrows the specified amount of tokens in WEI @dev see depositETH() and borrow() @param _borrowAmount the amount of borrowed StableX tokens in WEI. **/ function depositETHAndBorrow(uint256 _borrowAmount) public payable override { depositETH(); uint256 vaultId = a.vaultsData().vaultId(address(WETH), msg.sender); borrow(vaultId, _borrowAmount); } function _addCollateralToVault(address _collateralType, uint256 _amount) internal { uint256 vaultId = a.vaultsData().vaultId(_collateralType, msg.sender); if (vaultId == 0) { vaultId = a.vaultsData().createVault(_collateralType, msg.sender); } _addCollateralToVaultById(vaultId, _amount); } function _addCollateralToVaultById(uint256 _vaultId, uint256 _amount) internal { IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId); a.vaultsData().setCollateralBalance(_vaultId, v.collateralBalance.add(_amount)); emit Deposited(_vaultId, _amount, msg.sender); } /** Withdraws ERC20 tokens from a vault. @dev Only the owner of a vault can withdraw collateral from it. `withdraw()` will fail if it would bring the vault below the minimum collateralization treshold. @param _vaultId the ID of the vault from which to withdraw the collateral. @param _amount the amount of ERC20 tokens to be withdrawn in WEI. **/ function withdraw(uint256 _vaultId, uint256 _amount) public override onlyVaultOwner(_vaultId) nonReentrant { _removeCollateralFromVault(_vaultId, _amount); IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId); IERC20 asset = IERC20(v.collateralType); asset.safeTransfer(msg.sender, _amount); } /** Withdraws ETH from a WETH vault. @dev Only the owner of a vault can withdraw collateral from it. `withdraw()` will fail if it would bring the vault below the minimum collateralization treshold. @param _vaultId the ID of the vault from which to withdraw the collateral. @param _amount the amount of ETH to be withdrawn in WEI. **/ function withdrawETH(uint256 _vaultId, uint256 _amount) public override onlyVaultOwner(_vaultId) nonReentrant { _removeCollateralFromVault(_vaultId, _amount); IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId); require(v.collateralType == address(WETH)); WETH.withdraw(_amount); msg.sender.transfer(_amount); } function _removeCollateralFromVault(uint256 _vaultId, uint256 _amount) internal { IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId); require(_amount <= v.collateralBalance); uint256 newCollateralBalance = v.collateralBalance.sub(_amount); a.vaultsData().setCollateralBalance(_vaultId, newCollateralBalance); if (v.baseDebt > 0) { // Save gas cost when withdrawing from 0 debt vault state.refreshCollateral(v.collateralType); uint256 newCollateralValue = a.priceFeed().convertFrom(v.collateralType, newCollateralBalance); require( a.liquidationManager().isHealthy( newCollateralValue, a.vaultsData().vaultDebt(_vaultId), a.config().collateralConfigs(a.config().collateralIds(v.collateralType)).minCollateralRatio ) ); } emit Withdrawn(_vaultId, _amount, msg.sender); } /** Borrow new PAR tokens from a vault. @dev Only the owner of a vault can borrow from it. `borrow()` will update the outstanding vault debt to the current time before attempting the withdrawal. `borrow()` will fail if it would bring the vault below the minimum collateralization treshold. @param _vaultId the ID of the vault from which to borrow. @param _amount the amount of borrowed PAR tokens in WEI. **/ function borrow(uint256 _vaultId, uint256 _amount) public override onlyVaultOwner(_vaultId) nonReentrant { IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId); // Make sure current rate is up to date state.refreshCollateral(v.collateralType); uint256 originationFeePercentage = a.config().collateralOriginationFee(v.collateralType); uint256 newDebt = _amount; if (originationFeePercentage > 0) { newDebt = newDebt.add(_amount.wadMul(originationFeePercentage)); } // Increment vault borrow balance uint256 newBaseDebt = a.ratesManager().calculateBaseDebt(newDebt, cumulativeRates(v.collateralType)); a.vaultsData().setBaseDebt(_vaultId, v.baseDebt.add(newBaseDebt)); uint256 collateralValue = a.priceFeed().convertFrom(v.collateralType, v.collateralBalance); uint256 newVaultDebt = a.vaultsData().vaultDebt(_vaultId); require(a.vaultsData().collateralDebt(v.collateralType) <= a.config().collateralDebtLimit(v.collateralType)); bool isHealthy = a.liquidationManager().isHealthy( collateralValue, newVaultDebt, a.config().collateralConfigs(a.config().collateralIds(v.collateralType)).minCollateralRatio ); require(isHealthy); a.stablex().mint(msg.sender, _amount); debtNotifier.debtChanged(_vaultId); emit Borrowed(_vaultId, _amount, msg.sender); } /** Convenience function to repay all debt of a vault @dev `repayAll()` will update the outstanding vault debt to the current time. @param _vaultId the ID of the vault for which to repay the debt. **/ function repayAll(uint256 _vaultId) public override { repay(_vaultId, _MAX_INT); } /** Repay an outstanding PAR balance to a vault. @dev `repay()` will update the outstanding vault debt to the current time. @param _vaultId the ID of the vault for which to repay the outstanding debt balance. @param _amount the amount of PAR tokens in WEI to be repaid. **/ function repay(uint256 _vaultId, uint256 _amount) public override nonReentrant { address collateralType = a.vaultsData().vaultCollateralType(_vaultId); // Make sure current rate is up to date state.refreshCollateral(collateralType); uint256 currentVaultDebt = a.vaultsData().vaultDebt(_vaultId); // Decrement vault borrow balance if (_amount >= currentVaultDebt) { //full repayment _amount = currentVaultDebt; //only pay back what's outstanding } _reduceVaultDebt(_vaultId, _amount); a.stablex().burn(msg.sender, _amount); debtNotifier.debtChanged(_vaultId); emit Repaid(_vaultId, _amount, msg.sender); } /** Internal helper function to reduce the debt of a vault. @dev assumes cumulative rates for the vault's collateral type are up to date. please call `refreshCollateral()` before calling this function. @param _vaultId the ID of the vault for which to reduce the debt. @param _amount the amount of debt to be reduced. **/ function _reduceVaultDebt(uint256 _vaultId, uint256 _amount) internal { address collateralType = a.vaultsData().vaultCollateralType(_vaultId); uint256 currentVaultDebt = a.vaultsData().vaultDebt(_vaultId); uint256 remainder = currentVaultDebt.sub(_amount); uint256 cumulativeRate = cumulativeRates(collateralType); if (remainder == 0) { a.vaultsData().setBaseDebt(_vaultId, 0); } else { uint256 newBaseDebt = a.ratesManager().calculateBaseDebt(remainder, cumulativeRate); a.vaultsData().setBaseDebt(_vaultId, newBaseDebt); } } /** Liquidate a vault that is below the liquidation treshold by repaying its outstanding debt. @dev `liquidate()` will update the outstanding vault debt to the current time and pay a `liquidationBonus` to the liquidator. `liquidate()` can be called by anyone. @param _vaultId the ID of the vault to be liquidated. **/ function liquidate(uint256 _vaultId) public override { liquidatePartial(_vaultId, _MAX_INT); } /** Liquidate a vault partially that is below the liquidation treshold by repaying part of its outstanding debt. @dev `liquidatePartial()` will update the outstanding vault debt to the current time and pay a `liquidationBonus` to the liquidator. A LiquidationFee will be applied to the borrower during the liquidation. This means that the change in outstanding debt can be smaller than the repaid amount. `liquidatePartial()` can be called by anyone. @param _vaultId the ID of the vault to be liquidated. @param _amount the amount of debt+liquidationFee to repay. **/ function liquidatePartial(uint256 _vaultId, uint256 _amount) public override nonReentrant { IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId); state.refreshCollateral(v.collateralType); uint256 collateralValue = a.priceFeed().convertFrom(v.collateralType, v.collateralBalance); uint256 currentVaultDebt = a.vaultsData().vaultDebt(_vaultId); require( !a.liquidationManager().isHealthy( collateralValue, currentVaultDebt, a.config().collateralConfigs(a.config().collateralIds(v.collateralType)).liquidationRatio ) ); uint256 repaymentAfterLiquidationFeeRatio = WadRayMath.wad().sub( a.config().collateralLiquidationFee(v.collateralType) ); uint256 maxLiquiditionCost = currentVaultDebt.wadDiv(repaymentAfterLiquidationFeeRatio); uint256 repayAmount; if (_amount > maxLiquiditionCost) { _amount = maxLiquiditionCost; repayAmount = currentVaultDebt; } else { repayAmount = _amount.wadMul(repaymentAfterLiquidationFeeRatio); } // collateral value to be received by the liquidator is based on the total amount repaid (including the liquidationFee). uint256 collateralValueToReceive = _amount.add(a.liquidationManager().liquidationBonus(v.collateralType, _amount)); uint256 insuranceAmount = 0; if (collateralValueToReceive >= collateralValue) { // Not enough collateral for debt & liquidation fee collateralValueToReceive = collateralValue; uint256 discountedCollateralValue = a.liquidationManager().applyLiquidationDiscount( v.collateralType, collateralValue ); if (currentVaultDebt > discountedCollateralValue) { // Not enough collateral for debt alone insuranceAmount = currentVaultDebt.sub(discountedCollateralValue); require(a.stablex().balanceOf(address(this)) >= insuranceAmount); a.stablex().burn(address(this), insuranceAmount); // Insurance uses local reserves to pay down debt emit InsurancePaid(_vaultId, insuranceAmount, msg.sender); } repayAmount = currentVaultDebt.sub(insuranceAmount); _amount = discountedCollateralValue; } // reduce the vault debt by repayAmount _reduceVaultDebt(_vaultId, repayAmount.add(insuranceAmount)); a.stablex().burn(msg.sender, _amount); // send the claimed collateral to the liquidator uint256 collateralToReceive = a.priceFeed().convertTo(v.collateralType, collateralValueToReceive); a.vaultsData().setCollateralBalance(_vaultId, v.collateralBalance.sub(collateralToReceive)); IERC20 asset = IERC20(v.collateralType); asset.safeTransfer(msg.sender, collateralToReceive); debtNotifier.debtChanged(_vaultId); emit Liquidated(_vaultId, repayAmount, collateralToReceive, v.owner, msg.sender); } /** Returns the cumulativeRate of a collateral type. This function exists for backwards compatibility with the VaultsDataProvider. @param _collateralType the address of the collateral type. **/ function cumulativeRates(address _collateralType) public view override returns (uint256) { return state.cumulativeRates(_collateralType); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/WadRayMath.sol"; import "../interfaces/IAddressProvider.sol"; import "../interfaces/IVaultsCoreState.sol"; import "../v1/interfaces/IVaultsCoreV1.sol"; contract VaultsCoreState is IVaultsCoreState { using SafeMath for uint256; using WadRayMath for uint256; uint256 internal constant _MAX_INT = 2**256 - 1; bool public override synced = false; IAddressProvider public override a; mapping(address => uint256) public override cumulativeRates; mapping(address => uint256) public override lastRefresh; modifier onlyConfig() { require(msg.sender == address(a.config())); _; } modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender)); _; } modifier notSynced() { require(!synced); _; } constructor(IAddressProvider _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } /** Calculate the available income @return available income that has not been minted yet. **/ function availableIncome() public view override returns (uint256) { return a.vaultsData().debt().sub(a.stablex().totalSupply()); } /** Refresh the cumulative rates and debts of all vaults and all collateral types. @dev anyone can call this. **/ function refresh() public override { for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) { address collateralType = a.config().collateralConfigs(i).collateralType; refreshCollateral(collateralType); } } /** Sync state with another instance. This is used during version upgrade to keep V2 in sync with V2. @dev This call will read the state via `cumulativeRates(address collateralType)` and `lastRefresh(address collateralType)`. @param _stateAddress address from which the state is to be copied. **/ function syncState(IVaultsCoreState _stateAddress) public override onlyManager notSynced { for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) { address collateralType = a.config().collateralConfigs(i).collateralType; cumulativeRates[collateralType] = _stateAddress.cumulativeRates(collateralType); lastRefresh[collateralType] = _stateAddress.lastRefresh(collateralType); } synced = true; } /** Sync state with v1 core. This is used during version upgrade to keep V2 in sync with V1. @dev This call will read the state via `cumulativeRates(address collateralType)` and `lastRefresh(address collateralType)`. @param _core address of core v1 from which the state is to be copied. **/ function syncStateFromV1(IVaultsCoreV1 _core) public override onlyManager notSynced { for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) { address collateralType = a.config().collateralConfigs(i).collateralType; cumulativeRates[collateralType] = _core.cumulativeRates(collateralType); lastRefresh[collateralType] = _core.lastRefresh(collateralType); } synced = true; } /** Initialize the cumulative rates to 1 for a new collateral type. @param _collateralType the address of the new collateral type to be initialized **/ function initializeRates(address _collateralType) public override onlyConfig { require(_collateralType != address(0)); lastRefresh[_collateralType] = block.timestamp; cumulativeRates[_collateralType] = WadRayMath.ray(); } /** Refresh the cumulative rate of a collateraltype. @dev this updates the debt for all vaults with the specified collateral type. @param _collateralType the address of the collateral type to be refreshed. **/ function refreshCollateral(address _collateralType) public override { require(_collateralType != address(0)); require(a.config().collateralIds(_collateralType) != 0); uint256 timestamp = block.timestamp; uint256 timeElapsed = timestamp.sub(lastRefresh[_collateralType]); _refreshCumulativeRate(_collateralType, timeElapsed); lastRefresh[_collateralType] = timestamp; } /** Internal function to increase the cumulative rate over a specified time period @dev this updates the debt for all vaults with the specified collateral type. @param _collateralType the address of the collateral type to be updated @param _timeElapsed the amount of time in seconds to add to the cumulative rate **/ function _refreshCumulativeRate(address _collateralType, uint256 _timeElapsed) internal { uint256 borrowRate = a.config().collateralBorrowRate(_collateralType); uint256 oldCumulativeRate = cumulativeRates[_collateralType]; cumulativeRates[_collateralType] = a.ratesManager().calculateCumulativeRate( borrowRate, oldCumulativeRate, _timeElapsed ); emit CumulativeRateUpdated(_collateralType, _timeElapsed, cumulativeRates[_collateralType]); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "../libraries/WadRayMath.sol"; import "../interfaces/ISTABLEX.sol"; import "./interfaces/IFeeDistributorV1.sol"; import "./interfaces/IAddressProviderV1.sol"; contract FeeDistributorV1 is IFeeDistributorV1, ReentrancyGuard { using SafeMath for uint256; event PayeeAdded(address account, uint256 shares); event FeeReleased(uint256 income, uint256 releasedAt); uint256 public override lastReleasedAt; IAddressProviderV1 public override a; uint256 public override totalShares; mapping(address => uint256) public override shares; address[] public payees; modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not Manager"); _; } constructor(IAddressProviderV1 _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } /** Public function to release the accumulated fee income to the payees. @dev anyone can call this. */ function release() public override nonReentrant { uint256 income = a.core().availableIncome(); require(income > 0, "income is 0"); require(payees.length > 0, "Payees not configured yet"); lastReleasedAt = now; // Mint USDX to all receivers for (uint256 i = 0; i < payees.length; i++) { address payee = payees[i]; _release(income, payee); } emit FeeReleased(income, lastReleasedAt); } /** Get current configured payees. @return array of current payees. */ function getPayees() public view override returns (address[] memory) { return payees; } /** Internal function to release a percentage of income to a specific payee @dev uses totalShares to calculate correct share @param _totalIncomeReceived Total income for all payees, will be split according to shares @param _payee The address of the payee to whom to distribute the fees. */ function _release(uint256 _totalIncomeReceived, address _payee) internal { uint256 payment = _totalIncomeReceived.mul(shares[_payee]).div(totalShares); a.stablex().mint(_payee, payment); } /** Internal function to add a new payee. @dev will update totalShares and therefore reduce the relative share of all other payees. @param _payee The address of the payee to add. @param _shares The number of shares owned by the payee. */ function _addPayee(address _payee, uint256 _shares) internal { require(_payee != address(0), "payee is the zero address"); require(_shares > 0, "shares are 0"); require(shares[_payee] == 0, "payee already has shares"); payees.push(_payee); shares[_payee] = _shares; totalShares = totalShares.add(_shares); emit PayeeAdded(_payee, _shares); } /** Updates the payee configuration to a new one. @dev will release existing fees before the update. @param _payees Array of payees @param _shares Array of shares for each payee */ function changePayees(address[] memory _payees, uint256[] memory _shares) public override onlyManager { require(_payees.length == _shares.length, "Payees and shares mismatched"); require(_payees.length > 0, "No payees"); uint256 income = a.core().availableIncome(); if (income > 0 && payees.length > 0) { release(); } for (uint256 i = 0; i < payees.length; i++) { delete shares[payees[i]]; } delete payees; totalShares = 0; for (uint256 i = 0; i < _payees.length; i++) { _addPayee(_payees[i], _shares[i]); } } } // solium-disable security/no-block-members // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../interfaces/IAddressProvider.sol"; import "../interfaces/ISTABLEX.sol"; /** * @title USDX * @notice Stablecoin which can be minted against collateral in a vault */ contract USDX is ISTABLEX, ERC20("USD Stablecoin", "USDX") { IAddressProvider public override a; constructor(IAddressProvider _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } function mint(address account, uint256 amount) public override onlyMinter { _mint(account, amount); } function burn(address account, uint256 amount) public override onlyMinter { _burn(account, amount); } modifier onlyMinter() { require(a.controller().hasRole(a.controller().MINTER_ROLE(), msg.sender), "Caller is not a minter"); _; } } // 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 { } } // solium-disable security/no-block-members // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../interfaces/IAddressProvider.sol"; import "../interfaces/ISTABLEX.sol"; /** * @title PAR * @notice Stablecoin which can be minted against collateral in a vault */ contract PAR is ISTABLEX, ERC20("PAR Stablecoin", "PAR") { IAddressProvider public override a; constructor(IAddressProvider _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } function mint(address account, uint256 amount) public override onlyMinter { _mint(account, amount); } function burn(address account, uint256 amount) public override onlyMinter { _burn(account, amount); } modifier onlyMinter() { require(a.controller().hasRole(a.controller().MINTER_ROLE(), msg.sender), "Caller is not a minter"); _; } } // solium-disable security/no-block-members // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../governance/interfaces/IGovernanceAddressProvider.sol"; /** * @title MIMO * @notice MIMO Governance token */ contract MIMO is ERC20("MIMO Parallel Governance Token", "MIMO") { IGovernanceAddressProvider public a; bytes32 public constant MIMO_MINTER_ROLE = keccak256("MIMO_MINTER_ROLE"); constructor(IGovernanceAddressProvider _a) public { require(address(_a) != address(0)); a = _a; } modifier onlyMIMOMinter() { require(a.controller().hasRole(MIMO_MINTER_ROLE, msg.sender), "Caller is not MIMO Minter"); _; } function mint(address account, uint256 amount) public onlyMIMOMinter { _mint(account, amount); } function burn(address account, uint256 amount) public onlyMIMOMinter { _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../token/MIMO.sol"; import "../governance/interfaces/IGovernanceAddressProvider.sol"; import "../liquidityMining/interfaces/IMIMODistributor.sol"; contract PreUseAirdrop { using SafeERC20 for IERC20; struct Payout { address recipient; uint256 amount; } Payout[] public payouts; IGovernanceAddressProvider public ga; IMIMODistributor public mimoDistributor; modifier onlyManager() { require(ga.controller().hasRole(ga.controller().MANAGER_ROLE(), msg.sender), "Caller is not a Manager"); _; } constructor(IGovernanceAddressProvider _ga, IMIMODistributor _mimoDistributor) public { require(address(_ga) != address(0)); require(address(_mimoDistributor) != address(0)); ga = _ga; mimoDistributor = _mimoDistributor; payouts.push(Payout(0xBBd92c75C6f8B0FFe9e5BCb2e56a5e2600871a10, 271147720731494841509243076)); payouts.push(Payout(0xcc8793d5eB95fAa707ea4155e09b2D3F44F33D1E, 210989402066696530434956148)); payouts.push(Payout(0x185f19B43d818E10a31BE68f445ef8EDCB8AFB83, 22182938994846641176273320)); payouts.push(Payout(0xDeD9F901D40A96C3Ee558E6885bcc7eFC51ad078, 13678603288816593264718593)); payouts.push(Payout(0x0B3890bbF2553Bd098B45006aDD734d6Fbd6089E, 8416873402881706143143730)); payouts.push(Payout(0x3F41a1CFd3C8B8d9c162dE0f42307a0095A6e5DF, 7159719590701445955473554)); payouts.push(Payout(0x9115BaDce4873d58fa73b08279529A796550999a, 5632453715407980754075398)); payouts.push(Payout(0x7BC8C0B66d7f0E2193ED11eeCAAfE7c1837b926f, 5414893264683531027764823)); payouts.push(Payout(0xE7809aaaaa78E5a24E059889E561f598F3a4664c, 4712320945661497844704387)); payouts.push(Payout(0xf4D3566729f257edD0D4bF365d8f0Db7bF56e1C6, 2997276841876706895655431)); payouts.push(Payout(0x6Cf9AA65EBaD7028536E353393630e2340ca6049, 2734992792750385321760387)); payouts.push(Payout(0x74386381Cb384CC0FBa0Ac669d22f515FfC147D2, 1366427847282177615773594)); payouts.push(Payout(0x9144b150f28437E06Ab5FF5190365294eb1E87ec, 1363226310703652991601514)); payouts.push(Payout(0x5691d53685e8e219329bD8ADf62b1A0A17df9D11, 702790464733701088417744)); payouts.push(Payout(0x2B91B4f5223a0a1f5c7e1D139dDdD6B5B57C7A51, 678663683269882192090830)); payouts.push(Payout(0x8ddBad507F3b20239516810C308Ba4f3BaeAf3a1, 635520835923336863138335)); payouts.push(Payout(0xc3874A2C59b9779A75874Be6B5f0b578120A8701, 488385391000796390198744)); payouts.push(Payout(0x0A22C160f7E57F2e7d88b2fa1B1B03571bdE6128, 297735186117080365383063)); payouts.push(Payout(0x0a1aa2b65832fC0c71f2Ba488c84BeE0b9DB9692, 132688033756581498940995)); payouts.push(Payout(0xAf7b7AbC272a3aE6dD6dA41b9832C758477a85f2, 130254714680714068405131)); payouts.push(Payout(0xCDb17d9bCbA8E3bab6F68D59065efe784700Bee1, 71018627162763037055295)); payouts.push(Payout(0x4Dec19003F9Bb01A4c0D089605618b2d76deE30d, 69655357581389001902516)); payouts.push(Payout(0x31AacA1940C82130c2D4407E609e626E87A7BC18, 21678478730854029506989)); payouts.push(Payout(0xBc77AB8dd8BAa6ddf0D0c241d31b2e30bcEC127d, 21573657481017931484432)); payouts.push(Payout(0x1c25cDD83Cd7106C3dcB361230eC9E6930Aadd30, 14188368728356337446426)); payouts.push(Payout(0xf1B78ed53fa2f9B8cFfa677Ad8023aCa92109d08, 13831474058511281838532)); payouts.push(Payout(0xd27962455de27561e62345a516931F2392997263, 6968208393315527988941)); payouts.push(Payout(0xD8A4411C623aD361E98bC9D98cA33eE1cF308Bca, 4476771187861728227997)); payouts.push(Payout(0x1f06fA59809ee23Ee06e533D67D29C6564fC1964, 3358338614042115121460)); payouts.push(Payout(0xeDccc1501e3BCC8b3973B9BE33f6Bd7072d28388, 2328788070517256560738)); payouts.push(Payout(0xD738A884B2aFE625d372260E57e86E3eB4d5e1D7, 466769668474372743140)); payouts.push(Payout(0x6942b1b6526Fa05035d47c09B419039c00Ef7545, 442736084997163005698)); } function airdrop() public onlyManager { MIMO mimo = MIMO(address(ga.mimo())); for (uint256 i = 0; i < payouts.length; i++) { Payout memory payout = payouts[i]; mimo.mint(payout.recipient, payout.amount); } require(mimoDistributor.mintableTokens() > 0); bytes32 MIMO_MINTER_ROLE = mimo.MIMO_MINTER_ROLE(); ga.controller().renounceRole(MIMO_MINTER_ROLE, address(this)); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/WadRayMath.sol"; import "../governance/interfaces/IGovernanceAddressProvider.sol"; import "./interfaces/IMIMODistributor.sol"; import "./BaseDistributor.sol"; contract MIMODistributorV2 is BaseDistributor, IMIMODistributorExtension { using SafeMath for uint256; using WadRayMath for uint256; uint256 private constant _SECONDS_PER_YEAR = 365 days; uint256 private constant _SECONDS_PER_WEEK = 7 days; uint256 private constant _WEEKLY_R = 986125e21; // -1.3875% per week (-5.55% / 4) uint256 private _FIRST_WEEK_TOKENS; uint256 public override startTime; uint256 public alreadyMinted; constructor( IGovernanceAddressProvider _a, uint256 _startTime, IMIMODistributor _mimoDistributor ) public { require(address(_a) != address(0)); require(address(_mimoDistributor) != address(0)); a = _a; startTime = _startTime; alreadyMinted = _mimoDistributor.totalSupplyAt(startTime); uint256 weeklyIssuanceV1 = _mimoDistributor.weeklyIssuanceAt(startTime); _FIRST_WEEK_TOKENS = weeklyIssuanceV1 / 4; // reduce weeky issuance by 4 } /** Get current monthly issuance of new MIMO tokens. @return number of monthly issued tokens currently`. */ function currentIssuance() public view override returns (uint256) { return weeklyIssuanceAt(now); } /** Get monthly issuance of new MIMO tokens at `timestamp`. @dev invalid for timestamps before deployment @param timestamp for which to calculate the monthly issuance @return number of monthly issued tokens at `timestamp`. */ function weeklyIssuanceAt(uint256 timestamp) public view override returns (uint256) { uint256 elapsedSeconds = timestamp.sub(startTime); uint256 elapsedWeeks = elapsedSeconds.div(_SECONDS_PER_WEEK); return _WEEKLY_R.rayPow(elapsedWeeks).rayMul(_FIRST_WEEK_TOKENS); } /** Calculates how many MIMO tokens can be minted since the last time tokens were minted @return number of mintable tokens available right now. */ function mintableTokens() public view override returns (uint256) { return totalSupplyAt(now).sub(a.mimo().totalSupply()); } /** Calculates the totalSupply for any point after `startTime` @param timestamp for which to calculate the totalSupply @return totalSupply at timestamp. */ function totalSupplyAt(uint256 timestamp) public view override returns (uint256) { uint256 elapsedSeconds = timestamp.sub(startTime); uint256 elapsedWeeks = elapsedSeconds.div(_SECONDS_PER_WEEK); uint256 lastWeekSeconds = elapsedSeconds % _SECONDS_PER_WEEK; uint256 one = WadRayMath.ray(); uint256 fullWeeks = one.sub(_WEEKLY_R.rayPow(elapsedWeeks)).rayMul(_FIRST_WEEK_TOKENS).rayDiv(one.sub(_WEEKLY_R)); uint256 currentWeekIssuance = weeklyIssuanceAt(timestamp); uint256 partialWeek = currentWeekIssuance.mul(lastWeekSeconds).div(_SECONDS_PER_WEEK); return alreadyMinted.add(fullWeeks.add(partialWeek)); } /** Internal function to release a percentage of newTokens to a specific payee @dev uses totalShares to calculate correct share @param _totalnewTokensReceived Total newTokens for all payees, will be split according to shares @param _payee The address of the payee to whom to distribute the fees. */ function _release(uint256 _totalnewTokensReceived, address _payee) internal override { uint256 payment = _totalnewTokensReceived.mul(shares[_payee]).div(totalShares); a.mimo().mint(_payee, payment); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/WadRayMath.sol"; import "../governance/interfaces/IGovernanceAddressProvider.sol"; import "./interfaces/IBaseDistributor.sol"; /* Distribution Formula: 55.5m MIMO in first week -5.55% redution per week total(timestamp) = _SECONDS_PER_WEEK * ( (1-weeklyR^(timestamp/_SECONDS_PER_WEEK)) / (1-weeklyR) ) + timestamp % _SECONDS_PER_WEEK * (1-weeklyR^(timestamp/_SECONDS_PER_WEEK) */ abstract contract BaseDistributor is IBaseDistributor { using SafeMath for uint256; using WadRayMath for uint256; uint256 public override totalShares; mapping(address => uint256) public override shares; address[] public payees; IGovernanceAddressProvider public override a; modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not Manager"); _; } /** Public function to release the accumulated new MIMO tokens to the payees. @dev anyone can call this. */ function release() public override { uint256 newTokens = mintableTokens(); require(newTokens > 0, "newTokens is 0"); require(payees.length > 0, "Payees not configured yet"); // Mint MIMO to all receivers for (uint256 i = 0; i < payees.length; i++) { address payee = payees[i]; _release(newTokens, payee); } emit TokensReleased(newTokens, now); } /** Updates the payee configuration to a new one. @dev will release existing fees before the update. @param _payees Array of payees @param _shares Array of shares for each payee */ function changePayees(address[] memory _payees, uint256[] memory _shares) public override onlyManager { require(_payees.length == _shares.length, "Payees and shares mismatched"); require(_payees.length > 0, "No payees"); if (payees.length > 0 && mintableTokens() > 0) { release(); } for (uint256 i = 0; i < payees.length; i++) { delete shares[payees[i]]; } delete payees; totalShares = 0; for (uint256 i = 0; i < _payees.length; i++) { _addPayee(_payees[i], _shares[i]); } } /** Get current configured payees. @return array of current payees. */ function getPayees() public view override returns (address[] memory) { return payees; } /** Calculates how many MIMO tokens can be minted since the last time tokens were minted @return number of mintable tokens available right now. */ function mintableTokens() public view virtual override returns (uint256); /** Internal function to release a percentage of newTokens to a specific payee @dev uses totalShares to calculate correct share @param _totalnewTokensReceived Total newTokens for all payees, will be split according to shares @param _payee The address of the payee to whom to distribute the fees. */ function _release(uint256 _totalnewTokensReceived, address _payee) internal virtual; /** Internal function to add a new payee. @dev will update totalShares and therefore reduce the relative share of all other payees. @param _payee The address of the payee to add. @param _shares The number of shares owned by the payee. */ function _addPayee(address _payee, uint256 _shares) internal { require(_payee != address(0), "payee is the zero address"); require(_shares > 0, "shares are 0"); require(shares[_payee] == 0, "payee already has shares"); payees.push(_payee); shares[_payee] = _shares; totalShares = totalShares.add(_shares); emit PayeeAdded(_payee, _shares); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/interfaces/IRootChainManager.sol"; import "../governance/interfaces/IGovernanceAddressProvider.sol"; import "./BaseDistributor.sol"; contract PolygonDistributor is BaseDistributor { using SafeMath for uint256; IRootChainManager public rootChainManager; address public erc20Predicate; constructor( IGovernanceAddressProvider _a, IRootChainManager _rootChainManager, address _erc20Predicate ) public { require(address(_a) != address(0)); require(address(_rootChainManager) != address(0)); require(_erc20Predicate != address(0)); a = _a; rootChainManager = _rootChainManager; erc20Predicate = _erc20Predicate; } /** Calculates how many MIMO tokens can be minted since the last time tokens were minted @return number of mintable tokens available right now. */ function mintableTokens() public view override returns (uint256) { return a.mimo().balanceOf(address(this)); } /** Internal function to release a percentage of newTokens to a specific payee @dev uses totalShares to calculate correct share @param _totalnewTokensReceived Total newTokens for all payees, will be split according to shares @param _payee The address of the payee to whom to distribute the fees. */ function _release(uint256 _totalnewTokensReceived, address _payee) internal override { uint256 payment = _totalnewTokensReceived.mul(shares[_payee]).div(totalShares); a.mimo().approve(erc20Predicate, payment); rootChainManager.depositFor(_payee, address(a.mimo()), abi.encode(payment)); } } pragma solidity 0.6.12; interface IRootChainManager { event TokenMapped(address indexed rootToken, address indexed childToken, bytes32 indexed tokenType); event PredicateRegistered(bytes32 indexed tokenType, address indexed predicateAddress); function registerPredicate(bytes32 tokenType, address predicateAddress) external; function mapToken( address rootToken, address childToken, bytes32 tokenType ) external; function depositEtherFor(address user) external payable; function depositFor( address user, address rootToken, bytes calldata depositData ) external; function exit(bytes calldata inputData) external; } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "../liquidityMining/GenericMiner.sol"; import "../governance/interfaces/IGovernanceAddressProvider.sol"; contract MockGenericMiner is GenericMiner { constructor(IGovernanceAddressProvider _addresses) public GenericMiner(_addresses) {} function increaseStake(address user, uint256 value) public { _increaseStake(user, value); } function decreaseStake(address user, uint256 value) public { _decreaseStake(user, value); } } //SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/WadRayMath.sol"; import "./interfaces/IGenericMiner.sol"; /* GenericMiner is based on ERC2917. https://github.com/gnufoo/ERC2917-Proposal The Objective of GenericMiner is to implement a decentralized staking mechanism, which calculates _users' share by accumulating stake * time. And calculates _users revenue from anytime t0 to t1 by the formula below: user_accumulated_stake(time1) - user_accumulated_stake(time0) _____________________________________________________________________________ * (gross_stake(t1) - gross_stake(t0)) total_accumulated_stake(time1) - total_accumulated_stake(time0) */ contract GenericMiner is IGenericMiner { using SafeMath for uint256; using WadRayMath for uint256; mapping(address => UserInfo) internal _users; uint256 public override totalStake; IGovernanceAddressProvider public override a; uint256 internal _balanceTracker; uint256 internal _accAmountPerShare; constructor(IGovernanceAddressProvider _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } /** Releases the outstanding MIMO balance to the user. @param _user the address of the user for which the MIMO tokens will be released. */ function releaseMIMO(address _user) public virtual override { UserInfo storage userInfo = _users[_user]; _refresh(); uint256 pending = userInfo.stake.rayMul(_accAmountPerShare.sub(userInfo.accAmountPerShare)); _balanceTracker = _balanceTracker.sub(pending); userInfo.accAmountPerShare = _accAmountPerShare; require(a.mimo().transfer(_user, pending)); } /** Returns the number of tokens a user has staked. @param _user the address of the user. @return number of staked tokens */ function stake(address _user) public view override returns (uint256) { return _users[_user].stake; } /** Returns the number of tokens a user can claim via `releaseMIMO`. @param _user the address of the user. @return number of MIMO tokens that the user can claim */ function pendingMIMO(address _user) public view override returns (uint256) { uint256 currentBalance = a.mimo().balanceOf(address(this)); uint256 reward = currentBalance.sub(_balanceTracker); uint256 accAmountPerShare = _accAmountPerShare.add(reward.rayDiv(totalStake)); return _users[_user].stake.rayMul(accAmountPerShare.sub(_users[_user].accAmountPerShare)); } /** Returns the userInfo stored of a user. @param _user the address of the user. @return `struct UserInfo { uint256 stake; uint256 rewardDebt; }` **/ function userInfo(address _user) public view override returns (UserInfo memory) { return _users[_user]; } /** Refreshes the global state and subsequently decreases the stake a user has. This is an internal call and meant to be called within derivative contracts. @param user the address of the user @param value the amount by which the stake will be reduced */ function _decreaseStake(address user, uint256 value) internal { require(value > 0, "STAKE_MUST_BE_GREATER_THAN_ZERO"); //TODO cleanup error message UserInfo storage userInfo = _users[user]; require(userInfo.stake >= value, "INSUFFICIENT_STAKE_FOR_USER"); //TODO cleanup error message _refresh(); uint256 pending = userInfo.stake.rayMul(_accAmountPerShare.sub(userInfo.accAmountPerShare)); _balanceTracker = _balanceTracker.sub(pending); userInfo.stake = userInfo.stake.sub(value); userInfo.accAmountPerShare = _accAmountPerShare; totalStake = totalStake.sub(value); require(a.mimo().transfer(user, pending)); emit StakeDecreased(user, value); } /** Refreshes the global state and subsequently increases a user's stake. This is an internal call and meant to be called within derivative contracts. @param user the address of the user @param value the amount by which the stake will be increased */ function _increaseStake(address user, uint256 value) internal { require(value > 0, "STAKE_MUST_BE_GREATER_THAN_ZERO"); //TODO cleanup error message UserInfo storage userInfo = _users[user]; _refresh(); uint256 pending; if (userInfo.stake > 0) { pending = userInfo.stake.rayMul(_accAmountPerShare.sub(userInfo.accAmountPerShare)); _balanceTracker = _balanceTracker.sub(pending); } totalStake = totalStake.add(value); userInfo.stake = userInfo.stake.add(value); userInfo.accAmountPerShare = _accAmountPerShare; if (pending > 0) { require(a.mimo().transfer(user, pending)); } emit StakeIncreased(user, value); } /** Refreshes the global state and subsequently updates a user's stake. This is an internal call and meant to be called within derivative contracts. @param user the address of the user @param stake the new amount of stake for the user */ function _updateStake(address user, uint256 stake) internal returns (bool) { uint256 oldStake = _users[user].stake; if (stake > oldStake) { _increaseStake(user, stake.sub(oldStake)); } if (stake < oldStake) { _decreaseStake(user, oldStake.sub(stake)); } } /** Internal read function to calculate the number of MIMO tokens that have accumulated since the last token release. @dev This is an internal call and meant to be called within derivative contracts. @return newly accumulated token balance */ function _newTokensReceived() internal view returns (uint256) { return a.mimo().balanceOf(address(this)).sub(_balanceTracker); } /** Updates the internal state variables after accounting for newly received MIMO tokens. */ function _refresh() internal { if (totalStake == 0) { return; } uint256 currentBalance = a.mimo().balanceOf(address(this)); uint256 reward = currentBalance.sub(_balanceTracker); _balanceTracker = currentBalance; _accAmountPerShare = _accAmountPerShare.add(reward.rayDiv(totalStake)); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "./GenericMiner.sol"; import "./interfaces/IVotingMiner.sol"; import "../governance/interfaces/IGovernanceAddressProvider.sol"; import "../governance/interfaces/IVotingEscrow.sol"; contract VotingMiner is IVotingMiner, GenericMiner { constructor(IGovernanceAddressProvider _addresses) public GenericMiner(_addresses) {} /** Releases the outstanding MIMO balance to the user. @param _user the address of the user for which the MIMO tokens will be released. */ function releaseMIMO(address _user) public override { IVotingEscrow votingEscrow = a.votingEscrow(); require((msg.sender == _user) || (msg.sender == address(votingEscrow))); UserInfo storage userInfo = _users[_user]; _refresh(); uint256 pending = userInfo.stake.rayMul(_accAmountPerShare.sub(userInfo.accAmountPerShare)); _balanceTracker = _balanceTracker.sub(pending); userInfo.accAmountPerShare = _accAmountPerShare; uint256 votingPower = votingEscrow.balanceOf(_user); totalStake = totalStake.add(votingPower).sub(userInfo.stake); userInfo.stake = votingPower; if (pending > 0) { require(a.mimo().transfer(_user, pending)); } } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; interface IVotingMiner {} // SPDX-License-Identifier: AGPL-3.0 /* solium-disable security/no-block-members */ pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IVotingEscrow.sol"; import "./interfaces/IGovernanceAddressProvider.sol"; import "../liquidityMining/interfaces/IGenericMiner.sol"; /** * @title VotingEscrow * @notice Lockup GOV, receive vGOV (voting weight that decays over time) * @dev Supports: * 1) Tracking MIMO Locked up * 2) Decaying voting weight lookup * 3) Closure of contract */ contract VotingEscrow is IVotingEscrow, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public constant MAXTIME = 1460 days; // 365 * 4 years uint256 public minimumLockTime = 1 days; bool public expired = false; IERC20 public override stakingToken; mapping(address => LockedBalance) public locked; string public override name; string public override symbol; // solhint-disable-next-line uint256 public constant override decimals = 18; // AddressProvider IGovernanceAddressProvider public a; IGenericMiner public miner; constructor( IERC20 _stakingToken, IGovernanceAddressProvider _a, IGenericMiner _miner, string memory _name, string memory _symbol ) public { require(address(_stakingToken) != address(0)); require(address(_a) != address(0)); require(address(_miner) != address(0)); stakingToken = _stakingToken; a = _a; miner = _miner; name = _name; symbol = _symbol; } modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not a Manager"); _; } /** @dev Modifier to ensure contract has not yet expired */ modifier contractNotExpired() { require(!expired, "Contract is expired"); _; } /** * @dev Creates a new lock * @param _value Total units of StakingToken to lockup * @param _unlockTime Time at which the stake should unlock */ function createLock(uint256 _value, uint256 _unlockTime) external override nonReentrant contractNotExpired { LockedBalance memory locked_ = LockedBalance({ amount: locked[msg.sender].amount, end: locked[msg.sender].end }); require(_value > 0, "Must stake non zero amount"); require(locked_.amount == 0, "Withdraw old tokens first"); require(_unlockTime > block.timestamp, "Can only lock until time in the future"); require(_unlockTime.sub(block.timestamp) > minimumLockTime, "Lock duration should be larger than minimum locktime"); _depositFor(msg.sender, _value, _unlockTime, locked_, LockAction.CREATE_LOCK); } /** * @dev Increases amount of stake thats locked up & resets decay * @param _value Additional units of StakingToken to add to exiting stake */ function increaseLockAmount(uint256 _value) external override nonReentrant contractNotExpired { LockedBalance memory locked_ = LockedBalance({ amount: locked[msg.sender].amount, end: locked[msg.sender].end }); require(_value > 0, "Must stake non zero amount"); require(locked_.amount > 0, "No existing lock found"); require(locked_.end > block.timestamp, "Cannot add to expired lock. Withdraw"); _depositFor(msg.sender, _value, 0, locked_, LockAction.INCREASE_LOCK_AMOUNT); } /** * @dev Increases length of lockup & resets decay * @param _unlockTime New unlocktime for lockup */ function increaseLockLength(uint256 _unlockTime) external override nonReentrant contractNotExpired { LockedBalance memory locked_ = LockedBalance({ amount: locked[msg.sender].amount, end: locked[msg.sender].end }); require(locked_.amount > 0, "Nothing is locked"); require(locked_.end > block.timestamp, "Lock expired"); require(_unlockTime > locked_.end, "Can only increase lock time"); require(_unlockTime.sub(locked_.end) > minimumLockTime, "Lock duration should be larger than minimum locktime"); _depositFor(msg.sender, 0, _unlockTime, locked_, LockAction.INCREASE_LOCK_TIME); } /** * @dev Withdraws all the senders stake, providing lockup is over */ function withdraw() external override { _withdraw(msg.sender); } /** * @dev Ends the contract, unlocking all stakes. * No more staking can happen. Only withdraw. */ function expireContract() external override onlyManager contractNotExpired { expired = true; emit Expired(); } /** * @dev Set miner address. * @param _miner new miner contract address */ function setMiner(IGenericMiner _miner) external override onlyManager contractNotExpired { miner = _miner; } /** * @dev Set minimumLockTime. * @param _minimumLockTime minimum lockTime */ function setMinimumLockTime(uint256 _minimumLockTime) external override onlyManager contractNotExpired { minimumLockTime = _minimumLockTime; } /*************************************** GETTERS ****************************************/ /** * @dev Gets the user's votingWeight at the current time. * @param _owner User for which to return the votingWeight * @return uint256 Balance of user */ function balanceOf(address _owner) public view override returns (uint256) { return balanceOfAt(_owner, block.timestamp); } /** * @dev Gets a users votingWeight at a given block timestamp * @param _owner User for which to return the balance * @param _blockTime Timestamp for which to calculate balance. Can not be in the past * @return uint256 Balance of user */ function balanceOfAt(address _owner, uint256 _blockTime) public view override returns (uint256) { require(_blockTime >= block.timestamp, "Must pass block timestamp in the future"); LockedBalance memory currentLock = locked[_owner]; if (currentLock.end <= _blockTime) return 0; uint256 remainingLocktime = currentLock.end.sub(_blockTime); if (remainingLocktime > MAXTIME) { remainingLocktime = MAXTIME; } return currentLock.amount.mul(remainingLocktime).div(MAXTIME); } /** * @dev Deposits or creates a stake for a given address * @param _addr User address to assign the stake * @param _value Total units of StakingToken to lockup * @param _unlockTime Time at which the stake should unlock * @param _oldLocked Previous amount staked by this user * @param _action See LockAction enum */ function _depositFor( address _addr, uint256 _value, uint256 _unlockTime, LockedBalance memory _oldLocked, LockAction _action ) internal { LockedBalance memory newLocked = LockedBalance({ amount: _oldLocked.amount, end: _oldLocked.end }); // Adding to existing lock, or if a lock is expired - creating a new one newLocked.amount = newLocked.amount.add(_value); if (_unlockTime != 0) { newLocked.end = _unlockTime; } locked[_addr] = newLocked; if (_value != 0) { stakingToken.safeTransferFrom(_addr, address(this), _value); } miner.releaseMIMO(_addr); emit Deposit(_addr, _value, newLocked.end, _action, block.timestamp); } /** * @dev Withdraws a given users stake, providing the lockup has finished * @param _addr User for which to withdraw */ function _withdraw(address _addr) internal nonReentrant { LockedBalance memory oldLock = LockedBalance({ end: locked[_addr].end, amount: locked[_addr].amount }); require(block.timestamp >= oldLock.end || expired, "The lock didn't expire"); require(oldLock.amount > 0, "Must have something to withdraw"); uint256 value = uint256(oldLock.amount); LockedBalance memory currentLock = LockedBalance({ end: 0, amount: 0 }); locked[_addr] = currentLock; stakingToken.safeTransfer(_addr, value); miner.releaseMIMO(_addr); emit Withdraw(_addr, value, block.timestamp); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/WadRayMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IMIMO.sol"; import "./interfaces/IGenericMiner.sol"; import "hardhat/console.sol"; contract PARMiner { using SafeMath for uint256; using WadRayMath for uint256; using SafeERC20 for IERC20; struct UserInfo { uint256 stake; uint256 accAmountPerShare; uint256 accParAmountPerShare; } event StakeIncreased(address indexed user, uint256 stake); event StakeDecreased(address indexed user, uint256 stake); IERC20 public par; mapping(address => UserInfo) internal _users; uint256 public totalStake; IGovernanceAddressProvider public a; uint256 internal _balanceTracker; uint256 internal _accAmountPerShare; uint256 internal _parBalanceTracker; uint256 internal _accParAmountPerShare; constructor(IGovernanceAddressProvider _addresses) public { require(address(_addresses) != address(0)); a = _addresses; par = IERC20(_addresses.parallel().stablex()); } /** Deposit an ERC20 pool token for staking @dev this function uses `transferFrom()` and requires pre-approval via `approve()` on the ERC20. @param amount the amount of tokens to be deposited. Unit is in WEI. **/ function deposit(uint256 amount) public { par.safeTransferFrom(msg.sender, address(this), amount); _increaseStake(msg.sender, amount); } /** Withdraw staked ERC20 pool tokens. Will fail if user does not have enough tokens staked. @param amount the amount of tokens to be withdrawn. Unit is in WEI. **/ function withdraw(uint256 amount) public { par.safeTransfer(msg.sender, amount); _decreaseStake(msg.sender, amount); } /** Releases the outstanding MIMO balance to the user. @param _user the address of the user for which the MIMO tokens will be released. */ function releaseMIMO(address _user) public virtual { UserInfo storage userInfo = _users[_user]; _refresh(); _refreshPAR(totalStake); uint256 pending = userInfo.stake.rayMul(_accAmountPerShare.sub(userInfo.accAmountPerShare)); _balanceTracker = _balanceTracker.sub(pending); userInfo.accAmountPerShare = _accAmountPerShare; require(a.mimo().transfer(_user, pending)); } /** Releases the outstanding PAR reward balance to the user. @param _user the address of the user for which the PAR tokens will be released. */ function releasePAR(address _user) public virtual { UserInfo storage userInfo = _users[_user]; _refresh(); _refreshPAR(totalStake); uint256 pending = userInfo.stake.rayMul(_accParAmountPerShare.sub(userInfo.accParAmountPerShare)); _parBalanceTracker = _parBalanceTracker.sub(pending); userInfo.accParAmountPerShare = _accParAmountPerShare; require(par.transfer(_user, pending)); } /** Restakes the outstanding PAR reward balance to the user. Instead of sending the PAR to the user, it will be added to their stake @param _user the address of the user for which the PAR tokens will be restaked. */ function restakePAR(address _user) public virtual { UserInfo storage userInfo = _users[_user]; _refresh(); _refreshPAR(totalStake); uint256 pending = userInfo.stake.rayMul(_accParAmountPerShare.sub(userInfo.accParAmountPerShare)); _parBalanceTracker = _parBalanceTracker.sub(pending); userInfo.accParAmountPerShare = _accParAmountPerShare; _increaseStake(_user, pending); } /** Returns the number of tokens a user has staked. @param _user the address of the user. @return number of staked tokens */ function stake(address _user) public view returns (uint256) { return _users[_user].stake; } /** Returns the number of tokens a user can claim via `releaseMIMO`. @param _user the address of the user. @return number of MIMO tokens that the user can claim */ function pendingMIMO(address _user) public view returns (uint256) { uint256 currentBalance = a.mimo().balanceOf(address(this)); uint256 reward = currentBalance.sub(_balanceTracker); uint256 accAmountPerShare = _accAmountPerShare.add(reward.rayDiv(totalStake)); return _users[_user].stake.rayMul(accAmountPerShare.sub(_users[_user].accAmountPerShare)); } /** Returns the number of PAR tokens the user has earned as a reward @param _user the address of the user. @return nnumber of PAR tokens that will be sent automatically when staking/unstaking */ function pendingPAR(address _user) public view returns (uint256) { uint256 currentBalance = par.balanceOf(address(this)).sub(totalStake); uint256 reward = currentBalance.sub(_parBalanceTracker); uint256 accParAmountPerShare = _accParAmountPerShare.add(reward.rayDiv(totalStake)); return _users[_user].stake.rayMul(accParAmountPerShare.sub(_users[_user].accParAmountPerShare)); } /** Returns the userInfo stored of a user. @param _user the address of the user. @return `struct UserInfo { uint256 stake; uint256 rewardDebt; }` **/ function userInfo(address _user) public view returns (UserInfo memory) { return _users[_user]; } /** Refreshes the global state and subsequently decreases the stake a user has. This is an internal call and meant to be called within derivative contracts. @param user the address of the user @param value the amount by which the stake will be reduced */ function _decreaseStake(address user, uint256 value) internal { require(value > 0, "STAKE_MUST_BE_GREATER_THAN_ZERO"); //TODO cleanup error message UserInfo storage userInfo = _users[user]; require(userInfo.stake >= value, "INSUFFICIENT_STAKE_FOR_USER"); //TODO cleanup error message _refresh(); uint256 newTotalStake = totalStake.sub(value); _refreshPAR(newTotalStake); uint256 pending = userInfo.stake.rayMul(_accAmountPerShare.sub(userInfo.accAmountPerShare)); _balanceTracker = _balanceTracker.sub(pending); userInfo.accAmountPerShare = _accAmountPerShare; uint256 pendingPAR = userInfo.stake.rayMul(_accParAmountPerShare.sub(userInfo.accParAmountPerShare)); _parBalanceTracker = _parBalanceTracker.sub(pendingPAR); userInfo.accParAmountPerShare = _accParAmountPerShare; userInfo.stake = userInfo.stake.sub(value); totalStake = newTotalStake; if (pending > 0) { require(a.mimo().transfer(user, pending)); } if (pendingPAR > 0) { require(par.transfer(user, pendingPAR)); } emit StakeDecreased(user, value); } /** Refreshes the global state and subsequently increases a user's stake. This is an internal call and meant to be called within derivative contracts. @param user the address of the user @param value the amount by which the stake will be increased */ function _increaseStake(address user, uint256 value) internal { require(value > 0, "STAKE_MUST_BE_GREATER_THAN_ZERO"); //TODO cleanup error message UserInfo storage userInfo = _users[user]; _refresh(); uint256 newTotalStake = totalStake.add(value); _refreshPAR(newTotalStake); uint256 pending; uint256 pendingPAR; if (userInfo.stake > 0) { pending = userInfo.stake.rayMul(_accAmountPerShare.sub(userInfo.accAmountPerShare)); _balanceTracker = _balanceTracker.sub(pending); // maybe we should add the accumulated PAR to the stake of the user instead? pendingPAR = userInfo.stake.rayMul(_accParAmountPerShare.sub(userInfo.accParAmountPerShare)); _parBalanceTracker = _parBalanceTracker.sub(pendingPAR); } totalStake = newTotalStake; userInfo.stake = userInfo.stake.add(value); userInfo.accAmountPerShare = _accAmountPerShare; userInfo.accParAmountPerShare = _accParAmountPerShare; if (pendingPAR > 0) { // add pendingPAR balance to stake and totalStake instead of sending it back userInfo.stake = userInfo.stake.add(pendingPAR); totalStake = totalStake.add(pendingPAR); } if (pending > 0) { require(a.mimo().transfer(user, pending)); } emit StakeIncreased(user, value.add(pendingPAR)); } /** Refreshes the global state and subsequently updates a user's stake. This is an internal call and meant to be called within derivative contracts. @param user the address of the user @param stake the new amount of stake for the user */ function _updateStake(address user, uint256 stake) internal returns (bool) { uint256 oldStake = _users[user].stake; if (stake > oldStake) { _increaseStake(user, stake.sub(oldStake)); } if (stake < oldStake) { _decreaseStake(user, oldStake.sub(stake)); } } /** Updates the internal state variables after accounting for newly received MIMO tokens. */ function _refresh() internal { if (totalStake == 0) { return; } uint256 currentBalance = a.mimo().balanceOf(address(this)); uint256 reward = currentBalance.sub(_balanceTracker); _balanceTracker = currentBalance; _accAmountPerShare = _accAmountPerShare.add(reward.rayDiv(totalStake)); } /** Updates the internal state variables after accounting for newly received PAR tokens. */ function _refreshPAR(uint256 newTotalStake) internal { if (totalStake == 0) { return; } uint256 currentParBalance = par.balanceOf(address(this)).sub(newTotalStake); uint256 parReward = currentParBalance.sub(_parBalanceTracker); _parBalanceTracker = currentParBalance; _accParAmountPerShare = _accParAmountPerShare.add(parReward.rayDiv(totalStake)); } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./GenericMiner.sol"; import "./interfaces/IMIMO.sol"; import "./interfaces/IDemandMiner.sol"; contract DemandMiner is IDemandMiner, GenericMiner { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public override token; constructor(IGovernanceAddressProvider _addresses, IERC20 _token) public GenericMiner(_addresses) { require(address(_token) != address(0)); require(address(_token) != address(_addresses.mimo())); token = _token; } /** Deposit an ERC20 pool token for staking @dev this function uses `transferFrom()` and requires pre-approval via `approve()` on the ERC20. @param amount the amount of tokens to be deposited. Unit is in WEI. **/ function deposit(uint256 amount) public override { token.safeTransferFrom(msg.sender, address(this), amount); _increaseStake(msg.sender, amount); } /** Withdraw staked ERC20 pool tokens. Will fail if user does not have enough tokens staked. @param amount the amount of tokens to be withdrawn. Unit is in WEI. **/ function withdraw(uint256 amount) public override { token.safeTransfer(msg.sender, amount); _decreaseStake(msg.sender, amount); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../governance/interfaces/IGovernanceAddressProvider.sol"; import "./BaseDistributor.sol"; contract EthereumDistributor is BaseDistributor { using SafeMath for uint256; using SafeERC20 for IERC20; constructor(IGovernanceAddressProvider _a) public { require(address(_a) != address(0)); a = _a; } /** Calculates how many MIMO tokens can be minted since the last time tokens were minted @return number of mintable tokens available right now. */ function mintableTokens() public view override returns (uint256) { return a.mimo().balanceOf(address(this)); } /** Internal function to release a percentage of newTokens to a specific payee @dev uses totalShares to calculate correct share @param _totalnewTokensReceived Total newTokens for all payees, will be split according to shares @param _payee The address of the payee to whom to distribute the fees. */ function _release(uint256 _totalnewTokensReceived, address _payee) internal override { uint256 payment = _totalnewTokensReceived.mul(shares[_payee]).div(totalShares); IERC20(a.mimo()).safeTransfer(_payee, payment); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "./interfaces/IGovernanceAddressProvider.sol"; import "./interfaces/IGovernorAlpha.sol"; import "./interfaces/ITimelock.sol"; import "./interfaces/IVotingEscrow.sol"; import "../interfaces/IAccessController.sol"; import "../liquidityMining/interfaces/IDebtNotifier.sol"; import "../liquidityMining/interfaces/IMIMO.sol"; contract GovernanceAddressProvider is IGovernanceAddressProvider { IAddressProvider public override parallel; IMIMO public override mimo; IDebtNotifier public override debtNotifier; IGovernorAlpha public override governorAlpha; ITimelock public override timelock; IVotingEscrow public override votingEscrow; constructor(IAddressProvider _parallel) public { require(address(_parallel) != address(0)); parallel = _parallel; } modifier onlyManager() { require(controller().hasRole(controller().MANAGER_ROLE(), msg.sender), "Caller is not a Manager"); _; } /** Update the `AddressProvider` address that points to main AddressProvider used in the Parallel Protocol @dev only manager can call this. @param _parallel the address of the new `AddressProvider` address. */ function setParallelAddressProvider(IAddressProvider _parallel) public override onlyManager { require(address(_parallel) != address(0)); parallel = _parallel; } /** Update the `MIMO` ERC20 token address @dev only manager can call this. @param _mimo the address of the new `MIMO` token address. */ function setMIMO(IMIMO _mimo) public override onlyManager { require(address(_mimo) != address(0)); mimo = _mimo; } /** Update the `DebtNotifier` address @dev only manager can call this. @param _debtNotifier the address of the new `DebtNotifier`. */ function setDebtNotifier(IDebtNotifier _debtNotifier) public override onlyManager { require(address(_debtNotifier) != address(0)); debtNotifier = _debtNotifier; } /** Update the `GovernorAlpha` address @dev only manager can call this. @param _governorAlpha the address of the new `GovernorAlpha`. */ function setGovernorAlpha(IGovernorAlpha _governorAlpha) public override onlyManager { require(address(_governorAlpha) != address(0)); governorAlpha = _governorAlpha; } /** Update the `Timelock` address @dev only manager can call this. @param _timelock the address of the new `Timelock`. */ function setTimelock(ITimelock _timelock) public override onlyManager { require(address(_timelock) != address(0)); timelock = _timelock; } /** Update the `VotingEscrow` address @dev only manager can call this. @param _votingEscrow the address of the new `VotingEscrow`. */ function setVotingEscrow(IVotingEscrow _votingEscrow) public override onlyManager { require(address(_votingEscrow) != address(0)); votingEscrow = _votingEscrow; } function controller() public view override returns (IAccessController) { return parallel.controller(); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "../interfaces/IAddressProvider.sol"; import "../interfaces/IVaultsCore.sol"; import "../interfaces/IAccessController.sol"; import "../interfaces/IConfigProvider.sol"; import "../interfaces/ISTABLEX.sol"; import "../interfaces/IPriceFeed.sol"; import "../interfaces/IRatesManager.sol"; import "../interfaces/ILiquidationManager.sol"; import "../interfaces/IVaultsCore.sol"; import "../interfaces/IVaultsDataProvider.sol"; contract AddressProvider is IAddressProvider { IAccessController public override controller; IConfigProvider public override config; IVaultsCore public override core; ISTABLEX public override stablex; IRatesManager public override ratesManager; IPriceFeed public override priceFeed; ILiquidationManager public override liquidationManager; IVaultsDataProvider public override vaultsData; IFeeDistributor public override feeDistributor; constructor(IAccessController _controller) public { controller = _controller; } modifier onlyManager() { require(controller.hasRole(controller.MANAGER_ROLE(), msg.sender), "Caller is not a Manager"); _; } function setAccessController(IAccessController _controller) public override onlyManager { require(address(_controller) != address(0)); controller = _controller; } function setConfigProvider(IConfigProvider _config) public override onlyManager { require(address(_config) != address(0)); config = _config; } function setVaultsCore(IVaultsCore _core) public override onlyManager { require(address(_core) != address(0)); core = _core; } function setStableX(ISTABLEX _stablex) public override onlyManager { require(address(_stablex) != address(0)); stablex = _stablex; } function setRatesManager(IRatesManager _ratesManager) public override onlyManager { require(address(_ratesManager) != address(0)); ratesManager = _ratesManager; } function setLiquidationManager(ILiquidationManager _liquidationManager) public override onlyManager { require(address(_liquidationManager) != address(0)); liquidationManager = _liquidationManager; } function setPriceFeed(IPriceFeed _priceFeed) public override onlyManager { require(address(_priceFeed) != address(0)); priceFeed = _priceFeed; } function setVaultsDataProvider(IVaultsDataProvider _vaultsData) public override onlyManager { require(address(_vaultsData) != address(0)); vaultsData = _vaultsData; } function setFeeDistributor(IFeeDistributor _feeDistributor) public override onlyManager { require(address(_feeDistributor) != address(0)); feeDistributor = _feeDistributor; } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "../governance/interfaces/IGovernanceAddressProvider.sol"; import "./interfaces/ISupplyMiner.sol"; import "../interfaces/IVaultsDataProvider.sol"; contract DebtNotifier is IDebtNotifier { IGovernanceAddressProvider public override a; mapping(address => ISupplyMiner) public override collateralSupplyMinerMapping; constructor(IGovernanceAddressProvider _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } modifier onlyVaultsCore() { require(msg.sender == address(a.parallel().core()), "Caller is not VaultsCore"); _; } modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender)); _; } /** Notifies the correct supplyMiner of a change in debt. @dev Only the vaultsCore can call this. `debtChanged` will silently return if collateralType is not known to prevent any problems in vaultscore. @param _vaultId the ID of the vault of which the debt has changed. **/ function debtChanged(uint256 _vaultId) public override onlyVaultsCore { IVaultsDataProvider.Vault memory v = a.parallel().vaultsData().vaults(_vaultId); ISupplyMiner supplyMiner = collateralSupplyMinerMapping[v.collateralType]; if (address(supplyMiner) == address(0)) { // not throwing error so VaultsCore keeps working return; } supplyMiner.baseDebtChanged(v.owner, v.baseDebt); } /** Updates the collateral to supplyMiner mapping. @dev Manager role in the AccessController is required to call this. @param collateral the address of the collateralType. @param supplyMiner the address of the supplyMiner which will be notified on debt changes for this collateralType. **/ function setCollateralSupplyMiner(address collateral, ISupplyMiner supplyMiner) public override onlyManager { collateralSupplyMinerMapping[collateral] = supplyMiner; } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./GenericMiner.sol"; import "./interfaces/ISupplyMiner.sol"; import "../governance/interfaces/IGovernanceAddressProvider.sol"; contract SupplyMiner is ISupplyMiner, GenericMiner { using SafeMath for uint256; constructor(IGovernanceAddressProvider _addresses) public GenericMiner(_addresses) {} modifier onlyNotifier() { require(msg.sender == address(a.debtNotifier()), "Caller is not DebtNotifier"); _; } /** Gets called by the `DebtNotifier` and will update the stake of the user to match his current outstanding debt by using his baseDebt. @param user address of the user. @param newBaseDebt the new baseDebt and therefore stake for the user. */ function baseDebtChanged(address user, uint256 newBaseDebt) public override onlyNotifier { _updateStake(user, newBaseDebt); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/IVaultsDataProvider.sol"; import "../interfaces/IAddressProvider.sol"; contract VaultsDataProvider is IVaultsDataProvider { using SafeMath for uint256; IAddressProvider public override a; uint256 public override vaultCount = 0; mapping(address => uint256) public override baseDebt; mapping(uint256 => Vault) private _vaults; mapping(address => mapping(address => uint256)) private _vaultOwners; modifier onlyVaultsCore() { require(msg.sender == address(a.core()), "Caller is not VaultsCore"); _; } constructor(IAddressProvider _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } /** Opens a new vault. @dev only the vaultsCore module can call this function @param _collateralType address to the collateral asset e.g. WETH @param _owner the owner of the new vault. */ function createVault(address _collateralType, address _owner) public override onlyVaultsCore returns (uint256) { require(_collateralType != address(0)); require(_owner != address(0)); uint256 newId = ++vaultCount; require(_collateralType != address(0), "collateralType unknown"); Vault memory v = Vault({ collateralType: _collateralType, owner: _owner, collateralBalance: 0, baseDebt: 0, createdAt: block.timestamp }); _vaults[newId] = v; _vaultOwners[_owner][_collateralType] = newId; return newId; } /** Set the collateral balance of a vault. @dev only the vaultsCore module can call this function @param _id Vault ID of which the collateral balance will be updated @param _balance the new balance of the vault. */ function setCollateralBalance(uint256 _id, uint256 _balance) public override onlyVaultsCore { require(vaultExists(_id), "Vault not found."); Vault storage v = _vaults[_id]; v.collateralBalance = _balance; } /** Set the base debt of a vault. @dev only the vaultsCore module can call this function @param _id Vault ID of which the base debt will be updated @param _newBaseDebt the new base debt of the vault. */ function setBaseDebt(uint256 _id, uint256 _newBaseDebt) public override onlyVaultsCore { Vault storage _vault = _vaults[_id]; if (_newBaseDebt > _vault.baseDebt) { uint256 increase = _newBaseDebt.sub(_vault.baseDebt); baseDebt[_vault.collateralType] = baseDebt[_vault.collateralType].add(increase); } else { uint256 decrease = _vault.baseDebt.sub(_newBaseDebt); baseDebt[_vault.collateralType] = baseDebt[_vault.collateralType].sub(decrease); } _vault.baseDebt = _newBaseDebt; } /** Get a vault by vault ID. @param _id The vault's ID to be retrieved @return struct Vault { address collateralType; address owner; uint256 collateralBalance; uint256 baseDebt; uint256 createdAt; } */ function vaults(uint256 _id) public view override returns (Vault memory) { Vault memory v = _vaults[_id]; return v; } /** Get the owner of a vault. @param _id the ID of the vault @return owner of the vault */ function vaultOwner(uint256 _id) public view override returns (address) { return _vaults[_id].owner; } /** Get the collateral type of a vault. @param _id the ID of the vault @return address for the collateral type of the vault */ function vaultCollateralType(uint256 _id) public view override returns (address) { return _vaults[_id].collateralType; } /** Get the collateral balance of a vault. @param _id the ID of the vault @return collateral balance of the vault */ function vaultCollateralBalance(uint256 _id) public view override returns (uint256) { return _vaults[_id].collateralBalance; } /** Get the base debt of a vault. @param _id the ID of the vault @return base debt of the vault */ function vaultBaseDebt(uint256 _id) public view override returns (uint256) { return _vaults[_id].baseDebt; } /** Retrieve the vault id for a specified owner and collateral type. @dev returns 0 for non-existing vaults @param _collateralType address of the collateral type (Eg: WETH) @param _owner address of the owner of the vault @return vault id of the vault or 0 */ function vaultId(address _collateralType, address _owner) public view override returns (uint256) { return _vaultOwners[_owner][_collateralType]; } /** Checks if a specified vault exists. @param _id the ID of the vault @return boolean if the vault exists */ function vaultExists(uint256 _id) public view override returns (bool) { Vault memory v = _vaults[_id]; return v.collateralType != address(0); } /** Calculated the total outstanding debt for all vaults and all collateral types. @dev uses the existing cumulative rate. Call `refresh()` on `VaultsCore` to make sure it's up to date. @return total debt of the platform */ function debt() public view override returns (uint256) { uint256 total = 0; for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) { address collateralType = a.config().collateralConfigs(i).collateralType; total = total.add(collateralDebt(collateralType)); } return total; } /** Calculated the total outstanding debt for all vaults of a specific collateral type. @dev uses the existing cumulative rate. Call `refreshCollateral()` on `VaultsCore` to make sure it's up to date. @param _collateralType address of the collateral type (Eg: WETH) @return total debt of the platform of one collateral type */ function collateralDebt(address _collateralType) public view override returns (uint256) { return a.ratesManager().calculateDebt(baseDebt[_collateralType], a.core().cumulativeRates(_collateralType)); } /** Calculated the total outstanding debt for a specific vault. @dev uses the existing cumulative rate. Call `refreshCollateral()` on `VaultsCore` to make sure it's up to date. @param _vaultId the ID of the vault @return total debt of one vault */ function vaultDebt(uint256 _vaultId) public view override returns (uint256) { IVaultsDataProvider.Vault memory v = _vaults[_vaultId]; return a.ratesManager().calculateDebt(v.baseDebt, a.core().cumulativeRates(v.collateralType)); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/WadRayMath.sol"; import "../interfaces/ILiquidationManager.sol"; import "../interfaces/IAddressProvider.sol"; contract LiquidationManager is ILiquidationManager, ReentrancyGuard { using SafeMath for uint256; using WadRayMath for uint256; IAddressProvider public override a; uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; // 1 constructor(IAddressProvider _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } /** Check if the health factor is above or equal to 1. @param _collateralValue value of the collateral in PAR @param _vaultDebt outstanding debt to which the collateral balance shall be compared @param _minRatio min ratio to calculate health factor @return boolean if the health factor is >= 1. */ function isHealthy( uint256 _collateralValue, uint256 _vaultDebt, uint256 _minRatio ) public view override returns (bool) { uint256 healthFactor = calculateHealthFactor(_collateralValue, _vaultDebt, _minRatio); return healthFactor >= HEALTH_FACTOR_LIQUIDATION_THRESHOLD; } /** Calculate the healthfactor of a debt balance @param _collateralValue value of the collateral in PAR currency @param _vaultDebt outstanding debt to which the collateral balance shall be compared @param _minRatio min ratio to calculate health factor @return healthFactor */ function calculateHealthFactor( uint256 _collateralValue, uint256 _vaultDebt, uint256 _minRatio ) public view override returns (uint256 healthFactor) { if (_vaultDebt == 0) return WadRayMath.wad(); // CurrentCollateralizationRatio = value(deposited ETH) / debt uint256 collateralizationRatio = _collateralValue.wadDiv(_vaultDebt); // Healthfactor = CurrentCollateralizationRatio / MinimumCollateralizationRatio if (_minRatio > 0) { return collateralizationRatio.wadDiv(_minRatio); } return 1e18; // 1 } /** Calculate the liquidation bonus for a specified amount @param _collateralType address of the collateral type @param _amount amount for which the liquidation bonus shall be calculated @return bonus the liquidation bonus to pay out */ function liquidationBonus(address _collateralType, uint256 _amount) public view override returns (uint256 bonus) { return _amount.wadMul(a.config().collateralLiquidationBonus(_collateralType)); } /** Apply the liquidation bonus to a balance as a discount. @param _collateralType address of the collateral type @param _amount the balance on which to apply to liquidation bonus as a discount. @return discountedAmount */ function applyLiquidationDiscount(address _collateralType, uint256 _amount) public view override returns (uint256 discountedAmount) { return _amount.wadDiv(a.config().collateralLiquidationBonus(_collateralType).add(WadRayMath.wad())); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "../libraries/WadRayMath.sol"; import "../interfaces/ISTABLEX.sol"; import "../interfaces/IFeeDistributor.sol"; import "../interfaces/IAddressProvider.sol"; contract FeeDistributor is IFeeDistributor, ReentrancyGuard { using SafeMath for uint256; event PayeeAdded(address account, uint256 shares); event FeeReleased(uint256 income, uint256 releasedAt); uint256 public override lastReleasedAt; IAddressProvider public override a; uint256 public override totalShares; mapping(address => uint256) public override shares; address[] public payees; modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not Manager"); _; } constructor(IAddressProvider _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } /** Public function to release the accumulated fee income to the payees. @dev anyone can call this. */ function release() public override nonReentrant { uint256 income = a.core().state().availableIncome(); require(income > 0, "income is 0"); require(payees.length > 0, "Payees not configured yet"); lastReleasedAt = now; // Mint USDX to all receivers for (uint256 i = 0; i < payees.length; i++) { address payee = payees[i]; _release(income, payee); } emit FeeReleased(income, lastReleasedAt); } /** Updates the payee configuration to a new one. @dev will release existing fees before the update. @param _payees Array of payees @param _shares Array of shares for each payee */ function changePayees(address[] memory _payees, uint256[] memory _shares) public override onlyManager { require(_payees.length == _shares.length, "Payees and shares mismatched"); require(_payees.length > 0, "No payees"); uint256 income = a.core().state().availableIncome(); if (income > 0 && payees.length > 0) { release(); } for (uint256 i = 0; i < payees.length; i++) { delete shares[payees[i]]; } delete payees; totalShares = 0; for (uint256 i = 0; i < _payees.length; i++) { _addPayee(_payees[i], _shares[i]); } } /** Get current configured payees. @return array of current payees. */ function getPayees() public view override returns (address[] memory) { return payees; } /** Internal function to release a percentage of income to a specific payee @dev uses totalShares to calculate correct share @param _totalIncomeReceived Total income for all payees, will be split according to shares @param _payee The address of the payee to whom to distribute the fees. */ function _release(uint256 _totalIncomeReceived, address _payee) internal { uint256 payment = _totalIncomeReceived.mul(shares[_payee]).div(totalShares); a.stablex().mint(_payee, payment); } /** Internal function to add a new payee. @dev will update totalShares and therefore reduce the relative share of all other payees. @param _payee The address of the payee to add. @param _shares The number of shares owned by the payee. */ function _addPayee(address _payee, uint256 _shares) internal { require(_payee != address(0), "payee is the zero address"); require(_shares > 0, "shares are 0"); require(shares[_payee] == 0, "payee already has shares"); payees.push(_payee); shares[_payee] = _shares; totalShares = totalShares.add(_shares); emit PayeeAdded(_payee, _shares); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/WadRayMath.sol"; import "../interfaces/IRatesManager.sol"; import "../interfaces/IAddressProvider.sol"; contract RatesManager is IRatesManager { using SafeMath for uint256; using WadRayMath for uint256; uint256 private constant _SECONDS_PER_YEAR = 365 days; IAddressProvider public override a; constructor(IAddressProvider _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } /** Calculate the annualized borrow rate from the specified borrowing rate. @param _borrowRate rate for a 1 second interval specified in RAY accuracy. @return annualized rate */ function annualizedBorrowRate(uint256 _borrowRate) public pure override returns (uint256) { return _borrowRate.rayPow(_SECONDS_PER_YEAR); } /** Calculate the total debt from a specified base debt and cumulative rate. @param _baseDebt the base debt to be used. Can be a vault base debt or an aggregate base debt @param _cumulativeRate the cumulative rate in RAY accuracy. @return debt after applying the cumulative rate */ function calculateDebt(uint256 _baseDebt, uint256 _cumulativeRate) public pure override returns (uint256 debt) { return _baseDebt.rayMul(_cumulativeRate); } /** Calculate the base debt from a specified total debt and cumulative rate. @param _debt the total debt to be used. @param _cumulativeRate the cumulative rate in RAY accuracy. @return baseDebt the new base debt */ function calculateBaseDebt(uint256 _debt, uint256 _cumulativeRate) public pure override returns (uint256 baseDebt) { return _debt.rayDiv(_cumulativeRate); } /** Bring an existing cumulative rate forward in time @param _borrowRate rate for a 1 second interval specified in RAY accuracy to be applied @param _timeElapsed the time over whicht the borrow rate shall be applied @param _cumulativeRate the initial cumulative rate from which to apply the borrow rate @return new cumulative rate */ function calculateCumulativeRate( uint256 _borrowRate, uint256 _cumulativeRate, uint256 _timeElapsed ) public view override returns (uint256) { if (_timeElapsed == 0) return _cumulativeRate; uint256 cumulativeElapsed = _borrowRate.rayPow(_timeElapsed); return _cumulativeRate.rayMul(cumulativeElapsed); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../interfaces/IPriceFeed.sol"; import "../interfaces/IAddressProvider.sol"; import "../chainlink/AggregatorV3Interface.sol"; import "../libraries/MathPow.sol"; import "../libraries/WadRayMath.sol"; contract PriceFeed is IPriceFeed { using SafeMath for uint256; using SafeMath for uint8; using WadRayMath for uint256; uint256 public constant PRICE_ORACLE_STALE_THRESHOLD = 1 days; IAddressProvider public override a; mapping(address => AggregatorV3Interface) public override assetOracles; AggregatorV3Interface public override eurOracle; constructor(IAddressProvider _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not a Manager"); _; } /** * @notice Sets the oracle for the given asset, * @param _asset address to the collateral asset e.g. WETH * @param _oracle address to the oracel, this oracle should implement the AggregatorV3Interface */ function setAssetOracle(address _asset, address _oracle) public override onlyManager { require(_asset != address(0)); require(_oracle != address(0)); assetOracles[_asset] = AggregatorV3Interface(_oracle); emit OracleUpdated(_asset, _oracle, msg.sender); } /** * @notice Sets the oracle for EUR, this oracle should provide EUR-USD prices * @param _oracle address to the oracle, this oracle should implement the AggregatorV3Interface */ function setEurOracle(address _oracle) public override onlyManager { require(_oracle != address(0)); eurOracle = AggregatorV3Interface(_oracle); emit EurOracleUpdated(_oracle, msg.sender); } /** * Gets the asset price in EUR (PAR) * @dev returned value has matching decimals to the asset oracle (not the EUR oracle) * @param _asset address to the collateral asset e.g. WETH */ function getAssetPrice(address _asset) public view override returns (uint256 price) { (, int256 eurAnswer, , uint256 eurUpdatedAt, ) = eurOracle.latestRoundData(); require(eurAnswer > 0, "EUR price data not valid"); require(block.timestamp - eurUpdatedAt < PRICE_ORACLE_STALE_THRESHOLD, "EUR price data is stale"); (, int256 answer, , uint256 assetUpdatedAt, ) = assetOracles[_asset].latestRoundData(); require(answer > 0, "Price data not valid"); require(block.timestamp - assetUpdatedAt < PRICE_ORACLE_STALE_THRESHOLD, "Price data is stale"); uint8 eurDecimals = eurOracle.decimals(); uint256 eurAccuracy = MathPow.pow(10, eurDecimals); return uint256(answer).mul(eurAccuracy).div(uint256(eurAnswer)); } /** * @notice Converts asset balance into stablecoin balance at current price * @param _asset address to the collateral asset e.g. WETH * @param _amount amount of collateral */ function convertFrom(address _asset, uint256 _amount) public view override returns (uint256) { uint256 price = getAssetPrice(_asset); uint8 collateralDecimals = ERC20(_asset).decimals(); uint8 parDecimals = ERC20(address(a.stablex())).decimals(); // Needs re-casting because ISTABLEX does not expose decimals() uint8 oracleDecimals = assetOracles[_asset].decimals(); uint256 parAccuracy = MathPow.pow(10, parDecimals); uint256 collateralAccuracy = MathPow.pow(10, oracleDecimals.add(collateralDecimals)); return _amount.mul(price).mul(parAccuracy).div(collateralAccuracy); } /** * @notice Converts stablecoin balance into collateral balance at current price * @param _asset address to the collateral asset e.g. WETH * @param _amount amount of stablecoin */ function convertTo(address _asset, uint256 _amount) public view override returns (uint256) { uint256 price = getAssetPrice(_asset); uint8 collateralDecimals = ERC20(_asset).decimals(); uint8 parDecimals = ERC20(address(a.stablex())).decimals(); // Needs re-casting because ISTABLEX does not expose decimals() uint8 oracleDecimals = assetOracles[_asset].decimals(); uint256 parAccuracy = MathPow.pow(10, parDecimals); uint256 collateralAccuracy = MathPow.pow(10, oracleDecimals.add(collateralDecimals)); return _amount.mul(collateralAccuracy).div(price).div(parAccuracy); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; library MathPow { function pow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : 1; for (n /= 2; n != 0; n /= 2) { x = SafeMath.mul(x, x); if (n % 2 != 0) { z = SafeMath.mul(z, x); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "../chainlink/AggregatorV3Interface.sol"; contract MockChainlinkFeed is AggregatorV3Interface, Ownable { uint256 private _latestPrice; string public override description; uint256 public override version = 3; uint8 public override decimals; constructor( uint8 _decimals, uint256 _price, string memory _description ) public { decimals = _decimals; _latestPrice = _price; description = _description; } function setLatestPrice(uint256 price) public onlyOwner { require(price > 110033500); // > 1.1 USD require(price < 130033500); // > 1.3 USD _latestPrice = price; } /** * @notice get data about a round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * Note that different underlying implementations of AggregatorV3Interface * have slightly different semantics for some of the return values. Consumers * should determine what implementations they expect to receive * data from and validate that they can properly handle return data from all * of them. * @param _roundId the requested round ID as presented through the proxy, this * is made up of the aggregator's round ID with the phase ID encoded in the * two highest order bytes * @return roundId is the round ID from the aggregator for which the data was * retrieved combined with an phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. * (Only some AggregatorV3Interface implementations return meaningful values) * @dev Note that answer and updatedAt may change between queries. */ function getRoundData(uint80 _roundId) public view override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { roundId = uint80(_roundId); answer = int256(_latestPrice); startedAt = uint256(1597422127); updatedAt = uint256(1597695228); answeredInRound = uint80(_roundId); } /** * @notice get data about the latest round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * Note that different underlying implementations of AggregatorV3Interface * have slightly different semantics for some of the return values. Consumers * should determine what implementations they expect to receive * data from and validate that they can properly handle return data from all * of them. * @return roundId is the round ID from the aggregator for which the data was * retrieved combined with an phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. * (Only some AggregatorV3Interface implementations return meaningful values) * @dev Note that answer and updatedAt may change between queries. */ function latestRoundData() public view override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { uint256 latestRound = 101; roundId = uint80(latestRound); answer = int256(_latestPrice); startedAt = uint256(1597422127); updatedAt = now; answeredInRound = uint80(latestRound); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../chainlink/AggregatorV3Interface.sol"; contract MockChainlinkAggregator is AggregatorV3Interface { uint256 private _latestPrice; uint256 private _updatedAt; string public override description; uint256 public override version = 3; uint8 public override decimals; constructor( uint8 _decimals, uint256 _price, string memory _description ) public { decimals = _decimals; _latestPrice = _price; description = _description; } function setLatestPrice(uint256 price) public { _latestPrice = price; } function setUpdatedAt(uint256 updatedAt) public { _updatedAt = updatedAt; } /** * @notice get data about a round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * Note that different underlying implementations of AggregatorV3Interface * have slightly different semantics for some of the return values. Consumers * should determine what implementations they expect to receive * data from and validate that they can properly handle return data from all * of them. * @param _roundId the requested round ID as presented through the proxy, this * is made up of the aggregator's round ID with the phase ID encoded in the * two highest order bytes * @return roundId is the round ID from the aggregator for which the data was * retrieved combined with an phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. * (Only some AggregatorV3Interface implementations return meaningful values) * @dev Note that answer and updatedAt may change between queries. */ function getRoundData(uint80 _roundId) public view override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { roundId = uint80(_roundId); answer = int256(_latestPrice); startedAt = uint256(1597422127); updatedAt = uint256(1597695228); answeredInRound = uint80(_roundId); } /** * @notice get data about the latest round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * Note that different underlying implementations of AggregatorV3Interface * have slightly different semantics for some of the return values. Consumers * should determine what implementations they expect to receive * data from and validate that they can properly handle return data from all * of them. * @return roundId is the round ID from the aggregator for which the data was * retrieved combined with an phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. * (Only some AggregatorV3Interface implementations return meaningful values) * @dev Note that answer and updatedAt may change between queries. */ function latestRoundData() public view override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { uint256 latestRound = 101; roundId = uint80(latestRound); answer = int256(_latestPrice); startedAt = uint256(1597422127); updatedAt = _updatedAt; answeredInRound = uint80(latestRound); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "../libraries/WadRayMath.sol"; import "../interfaces/IConfigProvider.sol"; import "../interfaces/IAddressProvider.sol"; contract ConfigProvider is IConfigProvider { IAddressProvider public override a; mapping(uint256 => CollateralConfig) private _collateralConfigs; //indexing starts at 1 mapping(address => uint256) public override collateralIds; uint256 public override numCollateralConfigs; /// @notice The minimum duration of voting on a proposal, in seconds uint256 public override minVotingPeriod = 3 days; /// @notice The max duration of voting on a proposal, in seconds uint256 public override maxVotingPeriod = 2 weeks; /// @notice The percentage of votes in support of a proposal required in order for a quorum to be reached and for a proposal to succeed uint256 public override votingQuorum = 1e16; // 1% /// @notice The percentage of votes required in order for a voter to become a proposer uint256 public override proposalThreshold = 2e14; // 0.02% constructor(IAddressProvider _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not a Manager"); _; } /** Creates or overwrites an existing config for a collateral type @param _collateralType address of the collateral type @param _debtLimit the debt ceiling for the collateral type @param _liquidationRatio the minimum ratio to maintain to avoid liquidation @param _minCollateralRatio the minimum ratio to maintain to borrow new money or withdraw collateral @param _borrowRate the borrowing rate specified in 1 second interval in RAY accuracy. @param _originationFee an optional origination fee for newly created debt. Can be 0. @param _liquidationBonus the liquidation bonus to be paid to liquidators. @param _liquidationFee an optional fee for liquidation debt. Can be 0. */ function setCollateralConfig( address _collateralType, uint256 _debtLimit, uint256 _liquidationRatio, uint256 _minCollateralRatio, uint256 _borrowRate, uint256 _originationFee, uint256 _liquidationBonus, uint256 _liquidationFee ) public override onlyManager { require(address(_collateralType) != address(0)); require(_minCollateralRatio >= _liquidationRatio); if (collateralIds[_collateralType] == 0) { // Initialize new collateral a.core().state().initializeRates(_collateralType); CollateralConfig memory config = CollateralConfig({ collateralType: _collateralType, debtLimit: _debtLimit, liquidationRatio: _liquidationRatio, minCollateralRatio: _minCollateralRatio, borrowRate: _borrowRate, originationFee: _originationFee, liquidationBonus: _liquidationBonus, liquidationFee: _liquidationFee }); numCollateralConfigs++; _collateralConfigs[numCollateralConfigs] = config; collateralIds[_collateralType] = numCollateralConfigs; } else { // Update collateral config a.core().state().refreshCollateral(_collateralType); uint256 id = collateralIds[_collateralType]; _collateralConfigs[id].collateralType = _collateralType; _collateralConfigs[id].debtLimit = _debtLimit; _collateralConfigs[id].liquidationRatio = _liquidationRatio; _collateralConfigs[id].minCollateralRatio = _minCollateralRatio; _collateralConfigs[id].borrowRate = _borrowRate; _collateralConfigs[id].originationFee = _originationFee; _collateralConfigs[id].liquidationBonus = _liquidationBonus; _collateralConfigs[id].liquidationFee = _liquidationFee; } emit CollateralUpdated( _collateralType, _debtLimit, _liquidationRatio, _minCollateralRatio, _borrowRate, _originationFee, _liquidationBonus, _liquidationFee ); } function _emitUpdateEvent(address _collateralType) internal { emit CollateralUpdated( _collateralType, _collateralConfigs[collateralIds[_collateralType]].debtLimit, _collateralConfigs[collateralIds[_collateralType]].liquidationRatio, _collateralConfigs[collateralIds[_collateralType]].minCollateralRatio, _collateralConfigs[collateralIds[_collateralType]].borrowRate, _collateralConfigs[collateralIds[_collateralType]].originationFee, _collateralConfigs[collateralIds[_collateralType]].liquidationBonus, _collateralConfigs[collateralIds[_collateralType]].liquidationFee ); } /** Remove the config for a collateral type @param _collateralType address of the collateral type */ function removeCollateral(address _collateralType) public override onlyManager { uint256 id = collateralIds[_collateralType]; require(id != 0, "collateral does not exist"); _collateralConfigs[id] = _collateralConfigs[numCollateralConfigs]; //move last entry forward collateralIds[_collateralConfigs[id].collateralType] = id; //update id for last entry delete _collateralConfigs[numCollateralConfigs]; // delete last entry delete collateralIds[_collateralType]; numCollateralConfigs--; emit CollateralRemoved(_collateralType); } /** Sets the debt limit for a collateral type @param _collateralType address of the collateral type @param _debtLimit the new debt limit */ function setCollateralDebtLimit(address _collateralType, uint256 _debtLimit) public override onlyManager { _collateralConfigs[collateralIds[_collateralType]].debtLimit = _debtLimit; _emitUpdateEvent(_collateralType); } /** Sets the minimum liquidation ratio for a collateral type @dev this is the liquidation treshold under which a vault is considered open for liquidation. @param _collateralType address of the collateral type @param _liquidationRatio the new minimum collateralization ratio */ function setCollateralLiquidationRatio(address _collateralType, uint256 _liquidationRatio) public override onlyManager { require(_liquidationRatio <= _collateralConfigs[collateralIds[_collateralType]].minCollateralRatio); _collateralConfigs[collateralIds[_collateralType]].liquidationRatio = _liquidationRatio; _emitUpdateEvent(_collateralType); } /** Sets the minimum ratio for a collateral type for new borrowing or collateral withdrawal @param _collateralType address of the collateral type @param _minCollateralRatio the new minimum open ratio */ function setCollateralMinCollateralRatio(address _collateralType, uint256 _minCollateralRatio) public override onlyManager { require(_minCollateralRatio >= _collateralConfigs[collateralIds[_collateralType]].liquidationRatio); _collateralConfigs[collateralIds[_collateralType]].minCollateralRatio = _minCollateralRatio; _emitUpdateEvent(_collateralType); } /** Sets the borrowing rate for a collateral type @dev borrowing rate is specified for a 1 sec interval and accurancy is in RAY. @param _collateralType address of the collateral type @param _borrowRate the new borrowing rate for a 1 sec interval */ function setCollateralBorrowRate(address _collateralType, uint256 _borrowRate) public override onlyManager { a.core().state().refreshCollateral(_collateralType); _collateralConfigs[collateralIds[_collateralType]].borrowRate = _borrowRate; _emitUpdateEvent(_collateralType); } /** Sets the origiation fee for a collateral type @dev this rate is applied as a one time fee for new borrowing and is specified in WAD @param _collateralType address of the collateral type @param _originationFee new origination fee in WAD */ function setCollateralOriginationFee(address _collateralType, uint256 _originationFee) public override onlyManager { _collateralConfigs[collateralIds[_collateralType]].originationFee = _originationFee; _emitUpdateEvent(_collateralType); } /** Sets the liquidation bonus for a collateral type @dev the liquidation bonus is specified in WAD @param _collateralType address of the collateral type @param _liquidationBonus the liquidation bonus to be paid to liquidators. */ function setCollateralLiquidationBonus(address _collateralType, uint256 _liquidationBonus) public override onlyManager { _collateralConfigs[collateralIds[_collateralType]].liquidationBonus = _liquidationBonus; _emitUpdateEvent(_collateralType); } /** Sets the liquidation fee for a collateral type @dev this rate is applied as a fee for liquidation and is specified in WAD @param _collateralType address of the collateral type @param _liquidationFee new liquidation fee in WAD */ function setCollateralLiquidationFee(address _collateralType, uint256 _liquidationFee) public override onlyManager { require(_liquidationFee < 1e18); // fee < 100% _collateralConfigs[collateralIds[_collateralType]].liquidationFee = _liquidationFee; _emitUpdateEvent(_collateralType); } /** Set the min voting period for a gov proposal. @param _minVotingPeriod the min voting period for a gov proposal */ function setMinVotingPeriod(uint256 _minVotingPeriod) public override onlyManager { minVotingPeriod = _minVotingPeriod; } /** Set the max voting period for a gov proposal. @param _maxVotingPeriod the max voting period for a gov proposal */ function setMaxVotingPeriod(uint256 _maxVotingPeriod) public override onlyManager { maxVotingPeriod = _maxVotingPeriod; } /** Set the voting quora for a gov proposal. @param _votingQuorum the voting quora for a gov proposal */ function setVotingQuorum(uint256 _votingQuorum) public override onlyManager { require(_votingQuorum < 1e18); votingQuorum = _votingQuorum; } /** Set the proposal threshold for a gov proposal. @param _proposalThreshold the proposal threshold for a gov proposal */ function setProposalThreshold(uint256 _proposalThreshold) public override onlyManager { require(_proposalThreshold < 1e18); proposalThreshold = _proposalThreshold; } /** Get the debt limit for a collateral type @dev this is a platform wide limit for new debt issuance against a specific collateral type @param _collateralType address of the collateral type */ function collateralDebtLimit(address _collateralType) public view override returns (uint256) { return _collateralConfigs[collateralIds[_collateralType]].debtLimit; } /** Get the liquidation ratio that needs to be maintained for a collateral type to avoid liquidation. @param _collateralType address of the collateral type */ function collateralLiquidationRatio(address _collateralType) public view override returns (uint256) { return _collateralConfigs[collateralIds[_collateralType]].liquidationRatio; } /** Get the minimum collateralization ratio for a collateral type for new borrowing or collateral withdrawal. @param _collateralType address of the collateral type */ function collateralMinCollateralRatio(address _collateralType) public view override returns (uint256) { return _collateralConfigs[collateralIds[_collateralType]].minCollateralRatio; } /** Get the borrowing rate for a collateral type @dev borrowing rate is specified for a 1 sec interval and accurancy is in RAY. @param _collateralType address of the collateral type */ function collateralBorrowRate(address _collateralType) public view override returns (uint256) { return _collateralConfigs[collateralIds[_collateralType]].borrowRate; } /** Get the origiation fee for a collateral type @dev this rate is applied as a one time fee for new borrowing and is specified in WAD @param _collateralType address of the collateral type */ function collateralOriginationFee(address _collateralType) public view override returns (uint256) { return _collateralConfigs[collateralIds[_collateralType]].originationFee; } /** Get the liquidation bonus for a collateral type @dev this rate is applied as a one time fee for new borrowing and is specified in WAD @param _collateralType address of the collateral type */ function collateralLiquidationBonus(address _collateralType) public view override returns (uint256) { return _collateralConfigs[collateralIds[_collateralType]].liquidationBonus; } /** Get the liquidation fee for a collateral type @dev this rate is applied as a one time fee for new borrowing and is specified in WAD @param _collateralType address of the collateral type */ function collateralLiquidationFee(address _collateralType) public view override returns (uint256) { return _collateralConfigs[collateralIds[_collateralType]].liquidationFee; } /** Retreives the entire config for a specific config id. @param _id the ID of the conifg to be returned */ function collateralConfigs(uint256 _id) public view override returns (CollateralConfig memory) { require(_id <= numCollateralConfigs, "Invalid config id"); return _collateralConfigs[_id]; } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/ITimelock.sol"; contract Timelock is ITimelock { using SafeMath for uint256; uint256 public constant MINIMUM_DELAY = 2 days; uint256 public constant MAXIMUM_DELAY = 30 days; uint256 public constant override GRACE_PERIOD = 14 days; address public admin; address public pendingAdmin; uint256 public override delay; mapping(bytes32 => bool) public override queuedTransactions; constructor(address _admin, uint256 _delay) public { require(address(_admin) != address(0)); require(_delay >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay."); require(_delay <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); admin = _admin; delay = _delay; } receive() external payable {} fallback() external payable {} function setDelay(uint256 _delay) public { require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); require(_delay >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay."); require(_delay <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); delay = _delay; emit NewDelay(delay); } function acceptAdmin() public override { require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin."); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address _pendingAdmin) public { require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); pendingAdmin = _pendingAdmin; emit NewPendingAdmin(pendingAdmin); } function queueTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) public override returns (bytes32) { require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin."); require( eta >= block.timestamp.add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay." ); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash; } function cancelTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) public override { require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function executeTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) public payable override returns (bytes memory) { require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued."); require(block.timestamp >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock."); require(block.timestamp <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale."); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call{ value: value }(callData); require(success, "Timelock::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.6.12; import '../Timelock.sol'; // Test timelock contract with admin helpers contract TestTimelock is Timelock { constructor(address admin_, uint256 delay_) public Timelock(admin_, 2 days) { delay = delay_; } function harnessSetPendingAdmin(address pendingAdmin_) public { pendingAdmin = pendingAdmin_; } function harnessSetAdmin(address admin_) public { admin = admin_; } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IGovernorAlpha.sol"; import "./interfaces/IGovernanceAddressProvider.sol"; import "../libraries/WadRayMath.sol"; contract GovernorAlpha is IGovernorAlpha { using SafeMath for uint256; using WadRayMath for uint256; /// @notice The maximum number of actions that can be included in a proposal function proposalMaxOperations() public pure returns (uint256) { return 10; } // 10 actions IGovernanceAddressProvider public a; /// @notice The address of the Governor Guardian address public guardian; /// @notice The total number of proposals uint256 public proposalCount; /// @notice The official record of all proposals ever proposed mapping(uint256 => Proposal) public proposals; /// @notice The latest proposal for each proposer mapping(address => uint256) public latestProposalIds; constructor(IGovernanceAddressProvider _addresses, address _guardian) public { require(address(_addresses) != address(0)); require(address(_guardian) != address(0)); a = _addresses; guardian = _guardian; } function propose( address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description, uint256 endTime ) public override returns (uint256) { uint256 votingDuration = endTime.sub(block.timestamp); require(votingDuration >= a.parallel().config().minVotingPeriod(), "Proposal end-time too early"); require(votingDuration <= a.parallel().config().maxVotingPeriod(), "Proposal end-time too late"); require( a.votingEscrow().balanceOfAt(msg.sender, endTime) > proposalThreshold(), "GovernorAlpha::propose: proposer votes below proposal threshold" ); require( targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorAlpha::propose: proposal function information arity mismatch" ); require(targets.length != 0, "GovernorAlpha::propose: must provide actions"); require(targets.length <= proposalMaxOperations(), "GovernorAlpha::propose: too many actions"); uint256 latestProposalId = latestProposalIds[msg.sender]; if (latestProposalId != 0) { ProposalState proposersLatestProposalState = state(latestProposalId); require( proposersLatestProposalState != ProposalState.Active, "GovernorAlpha::propose: one live proposal per proposer, found an already active proposal" ); } proposalCount++; Proposal memory newProposal = Proposal({ id: proposalCount, proposer: msg.sender, eta: 0, targets: targets, values: values, signatures: signatures, calldatas: calldatas, startTime: block.timestamp, endTime: endTime, forVotes: 0, againstVotes: 0, canceled: false, executed: false }); proposals[newProposal.id] = newProposal; latestProposalIds[newProposal.proposer] = newProposal.id; emit ProposalCreated( newProposal.id, msg.sender, targets, values, signatures, calldatas, block.timestamp, endTime, description ); return newProposal.id; } function queue(uint256 proposalId) public override { require( state(proposalId) == ProposalState.Succeeded, "GovernorAlpha::queue: proposal can only be queued if it is succeeded" ); Proposal storage proposal = proposals[proposalId]; uint256 eta = block.timestamp.add(a.timelock().delay()); for (uint256 i = 0; i < proposal.targets.length; i++) { _queueOrRevert(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta); } proposal.eta = eta; emit ProposalQueued(proposalId, eta); } function execute(uint256 proposalId) public payable override { require( state(proposalId) == ProposalState.Queued, "GovernorAlpha::execute: proposal can only be executed if it is queued" ); Proposal storage proposal = proposals[proposalId]; proposal.executed = true; for (uint256 i = 0; i < proposal.targets.length; i++) { a.timelock().executeTransaction{ value: proposal.values[i] }( proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ); } emit ProposalExecuted(proposalId); } function cancel(uint256 proposalId) public override { ProposalState state = state(proposalId); require(state != ProposalState.Executed, "GovernorAlpha::cancel: cannot cancel executed proposal"); Proposal storage proposal = proposals[proposalId]; require(msg.sender == guardian, "Only Guardian can cancel"); proposal.canceled = true; for (uint256 i = 0; i < proposal.targets.length; i++) { a.timelock().cancelTransaction( proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ); } emit ProposalCanceled(proposalId); } function castVote(uint256 proposalId, bool support) public override { require(state(proposalId) == ProposalState.Active, "GovernorAlpha::_castVote: voting is closed"); Proposal storage proposal = proposals[proposalId]; Receipt storage receipt = proposal.receipts[msg.sender]; require(receipt.hasVoted == false, "GovernorAlpha::_castVote: voter already voted"); uint256 votes = a.votingEscrow().balanceOfAt(msg.sender, proposal.endTime); if (support) { proposal.forVotes = proposal.forVotes.add(votes); } else { proposal.againstVotes = proposal.againstVotes.add(votes); } receipt.hasVoted = true; receipt.support = support; receipt.votes = votes; emit VoteCast(msg.sender, proposalId, support, votes); } // solhint-disable-next-line private-vars-leading-underscore function __acceptAdmin() public { require(msg.sender == guardian, "GovernorAlpha::__acceptAdmin: sender must be gov guardian"); a.timelock().acceptAdmin(); } // solhint-disable-next-line private-vars-leading-underscore function __abdicate() public { require(msg.sender == guardian, "GovernorAlpha::__abdicate: sender must be gov guardian"); guardian = address(0); } // solhint-disable-next-line private-vars-leading-underscore function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint256 eta) public { require(msg.sender == guardian, "GovernorAlpha::__queueSetTimelockPendingAdmin: sender must be gov guardian"); a.timelock().queueTransaction( address(a.timelock()), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta ); } // solhint-disable-next-line private-vars-leading-underscore function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint256 eta) public { require(msg.sender == guardian, "GovernorAlpha::__executeSetTimelockPendingAdmin: sender must be gov guardian"); a.timelock().executeTransaction( address(a.timelock()), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta ); } /// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed function quorumVotes() public view override returns (uint256) { return a.votingEscrow().stakingToken().totalSupply().wadMul(a.parallel().config().votingQuorum()); } /// @notice The number of votes required in order for a voter to become a proposer function proposalThreshold() public view override returns (uint256) { return a.votingEscrow().stakingToken().totalSupply().wadMul(a.parallel().config().proposalThreshold()); } function getActions(uint256 proposalId) public view override returns ( address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas ) { Proposal storage p = proposals[proposalId]; return (p.targets, p.values, p.signatures, p.calldatas); } function getReceipt(uint256 proposalId, address voter) public view override returns (Receipt memory) { return proposals[proposalId].receipts[voter]; } function state(uint256 proposalId) public view override returns (ProposalState) { require(proposalCount >= proposalId && proposalId > 0, "GovernorAlpha::state: invalid proposal id"); Proposal storage proposal = proposals[proposalId]; if (proposal.canceled) { return ProposalState.Canceled; } else if (block.timestamp <= proposal.endTime) { return ProposalState.Active; } else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes()) { return ProposalState.Defeated; } else if (proposal.eta == 0) { return ProposalState.Succeeded; } else if (proposal.executed) { return ProposalState.Executed; } else if (block.timestamp >= a.timelock().GRACE_PERIOD().add(proposal.endTime)) { return ProposalState.Expired; } else { return ProposalState.Queued; } } function _queueOrRevert( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) internal { require( !a.timelock().queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorAlpha::_queueOrRevert: proposal action already queued at eta" ); a.timelock().queueTransaction(target, value, signature, data, eta); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/WadRayMath.sol"; import "../governance/interfaces/IGovernanceAddressProvider.sol"; import "./interfaces/IMIMODistributor.sol"; import "./BaseDistributor.sol"; /* Distribution Formula: 55.5m MIMO in first week -5.55% redution per week total(timestamp) = _SECONDS_PER_WEEK * ( (1-_WEEKLY_R^(timestamp/_SECONDS_PER_WEEK)) / (1-_WEEKLY_R) ) + timestamp % _SECONDS_PER_WEEK * (1-_WEEKLY_R^(timestamp/_SECONDS_PER_WEEK) */ contract MIMODistributor is BaseDistributor, IMIMODistributorExtension { using SafeMath for uint256; using WadRayMath for uint256; uint256 private constant _SECONDS_PER_YEAR = 365 days; uint256 private constant _SECONDS_PER_WEEK = 7 days; uint256 private constant _WEEKLY_R = 9445e23; //-5.55% uint256 private constant _FIRST_WEEK_TOKENS = 55500000 ether; //55.5m uint256 public override startTime; constructor(IGovernanceAddressProvider _a, uint256 _startTime) public { require(address(_a) != address(0)); a = _a; startTime = _startTime; } /** Get current monthly issuance of new MIMO tokens. @return number of monthly issued tokens currently`. */ function currentIssuance() public view override returns (uint256) { return weeklyIssuanceAt(now); } /** Get monthly issuance of new MIMO tokens at `timestamp`. @dev invalid for timestamps before deployment @param timestamp for which to calculate the monthly issuance @return number of monthly issued tokens at `timestamp`. */ function weeklyIssuanceAt(uint256 timestamp) public view override returns (uint256) { uint256 elapsedSeconds = timestamp.sub(startTime); uint256 elapsedWeeks = elapsedSeconds.div(_SECONDS_PER_WEEK); return _WEEKLY_R.rayPow(elapsedWeeks).rayMul(_FIRST_WEEK_TOKENS); } /** Calculates how many MIMO tokens can be minted since the last time tokens were minted @return number of mintable tokens available right now. */ function mintableTokens() public view override returns (uint256) { return totalSupplyAt(now).sub(a.mimo().totalSupply()); } /** Calculates the totalSupply for any point after `startTime` @param timestamp for which to calculate the totalSupply @return totalSupply at timestamp. */ function totalSupplyAt(uint256 timestamp) public view override returns (uint256) { uint256 elapsedSeconds = timestamp.sub(startTime); uint256 elapsedWeeks = elapsedSeconds.div(_SECONDS_PER_WEEK); uint256 lastWeekSeconds = elapsedSeconds % _SECONDS_PER_WEEK; uint256 one = WadRayMath.ray(); uint256 fullWeeks = one.sub(_WEEKLY_R.rayPow(elapsedWeeks)).rayMul(_FIRST_WEEK_TOKENS).rayDiv(one.sub(_WEEKLY_R)); uint256 currentWeekIssuance = weeklyIssuanceAt(timestamp); uint256 partialWeek = currentWeekIssuance.mul(lastWeekSeconds).div(_SECONDS_PER_WEEK); return fullWeeks.add(partialWeek); } /** Internal function to release a percentage of newTokens to a specific payee @dev uses totalShares to calculate correct share @param _totalnewTokensReceived Total newTokens for all payees, will be split according to shares @param _payee The address of the payee to whom to distribute the fees. */ function _release(uint256 _totalnewTokensReceived, address _payee) internal override { uint256 payment = _totalnewTokensReceived.mul(shares[_payee]).div(totalShares); a.mimo().mint(_payee, payment); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../governance/interfaces/IGovernanceAddressProvider.sol"; import "./interfaces/IBaseDistributor.sol"; contract DistributorManager { using SafeMath for uint256; IGovernanceAddressProvider public a; IBaseDistributor public mimmoDistributor; modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not Manager"); _; } constructor(IGovernanceAddressProvider _a, IBaseDistributor _mimmoDistributor) public { require(address(_a) != address(0)); require(address(_mimmoDistributor) != address(0)); a = _a; mimmoDistributor = _mimmoDistributor; } /** Public function to release the accumulated new MIMO tokens to the payees. @dev anyone can call this. */ function releaseAll() public { mimmoDistributor.release(); address[] memory distributors = mimmoDistributor.getPayees(); for (uint256 i = 0; i < distributors.length; i++) { IBaseDistributor(distributors[i]).release(); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract MockWETH is ERC20("Wrapped Ether", "WETH") { function mint(address account, uint256 amount) public { _mint(account, amount); } function deposit() public payable { _mint(msg.sender, msg.value); } function withdraw(uint256 wad) public { _burn(msg.sender, wad); msg.sender.transfer(wad); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract MockWBTC is ERC20("Wrapped Bitcoin", "WBTC") { function mint(address account, uint256 amount) public { _mint(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract MockMIMO is ERC20("MIMO Token", "MIMO") { function mint(address account, uint256 amount) public { _mint(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract MockERC20 is ERC20 { constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20(_name, _symbol) { super._setupDecimals(_decimals); } function mint(address account, uint256 amount) public { _mint(account, amount); } function burn(address account, uint256 amount) public { _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract MockBPT is ERC20("Balancer Pool Token", "BPT") { function mint(address account, uint256 amount) public { _mint(account, amount); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IAddressProvider.sol"; import "../libraries/interfaces/IVault.sol"; contract MIMOBuyback { bytes32 public constant KEEPER_ROLE = keccak256("KEEPER_ROLE"); IAddressProvider public a; IERC20 public PAR; IERC20 public MIMO; uint256 public lockExpiry; bytes32 public poolID; IVault public balancer = IVault(0xBA12222222228d8Ba445958a75a0704d566BF2C8); bool public whitelistEnabled = false; constructor( uint256 _lockExpiry, bytes32 _poolID, address _a, address _mimo ) public { lockExpiry = _lockExpiry; poolID = _poolID; a = IAddressProvider(_a); MIMO = IERC20(_mimo); PAR = a.stablex(); PAR.approve(address(balancer), 2**256 - 1); } modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not a Manager"); _; } modifier onlyKeeper() { require( !whitelistEnabled || (whitelistEnabled && a.controller().hasRole(KEEPER_ROLE, msg.sender)), "Caller is not a Keeper" ); _; } function withdrawMIMO(address destination) public onlyManager { require(block.timestamp > lockExpiry, "lock not expired yet"); require(MIMO.transfer(destination, MIMO.balanceOf(address(this)))); } function buyMIMO() public onlyKeeper { a.core().state().refresh(); a.feeDistributor().release(); bytes memory userData = abi.encode(); IVault.SingleSwap memory singleSwap = IVault.SingleSwap( poolID, IVault.SwapKind.GIVEN_IN, IAsset(address(PAR)), // swap in IAsset(address(MIMO)), // swap out PAR.balanceOf(address(this)), // all PAR of this contract userData ); IVault.FundManagement memory fundManagement = IVault.FundManagement( address(this), // sender false, // useInternalBalance payable(address(this)), // recipient false // // useInternalBalance ); balancer.swap( singleSwap, fundManagement, 0, // limit, could be frontrun? 2**256 - 1 // deadline ); } function setWhitelistEnabled(bool _status) public onlyManager { whitelistEnabled = _status; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IAsset { // solhint-disable-previous-line no-empty-blocks } interface IVault { enum SwapKind { GIVEN_IN, GIVEN_OUT } /** * @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on * the `kind` value. * * `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address). * Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct SingleSwap { bytes32 poolId; SwapKind kind; IAsset assetIn; IAsset assetOut; uint256 amount; bytes userData; } /** * @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the * `recipient` account. * * If the caller is not `sender`, it must be an authorized relayer for them. * * If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20 * transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender` * must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of * `joinPool`. * * If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of * transferred. This matches the behavior of `exitPool`. * * Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a * revert. */ struct FundManagement { address sender; bool fromInternalBalance; address payable recipient; bool toInternalBalance; } /** * @dev Performs a swap with a single Pool. * * If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens * taken from the Pool, which must be greater than or equal to `limit`. * * If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens * sent to the Pool, which must be less than or equal to `limit`. * * Internal Balance usage and the recipient are determined by the `funds` struct. * * Emits a `Swap` event. */ function swap( SingleSwap memory singleSwap, FundManagement memory funds, uint256 limit, uint256 deadline ) external payable returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; /** Buggy ERC20 implementation without the return bool on `transfer`, `transferFrom` and `approve` for testing purposes */ contract MockBuggyERC20 is Context { using SafeMath for uint256; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _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 totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual { _transfer(_msgSender(), recipient, amount); } function allowance(address owner, address spender) public view virtual returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual { _approve(_msgSender(), spender, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public virtual { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance") ); } function mint(address account, uint256 amount) public { _mint(account, amount); } 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 _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); } 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); } 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); } 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); } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface BPool is IERC20 { function gulp(address token) external; function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external; function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external; function swapExactAmountIn( address tokenIn, uint256 tokenAmountIn, address tokenOut, uint256 minAmountOut, uint256 maxPrice ) external returns (uint256 tokenAmountOut, uint256 spotPriceAfter); function swapExactAmountOut( address tokenIn, uint256 maxAmountIn, address tokenOut, uint256 tokenAmountOut, uint256 maxPrice ) external returns (uint256 tokenAmountIn, uint256 spotPriceAfter); function joinswapExternAmountIn( address tokenIn, uint256 tokenAmountIn, uint256 minPoolAmountOut ) external returns (uint256 poolAmountOut); function joinswapPoolAmountOut( address tokenIn, uint256 poolAmountOut, uint256 maxAmountIn ) external returns (uint256 tokenAmountIn); function exitswapPoolAmountIn( address tokenOut, uint256 poolAmountIn, uint256 minAmountOut ) external returns (uint256 tokenAmountOut); function exitswapExternAmountOut( address tokenOut, uint256 tokenAmountOut, uint256 maxPoolAmountIn ) external returns (uint256 poolAmountIn); function calcPoolOutGivenSingleIn( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 poolSupply, uint256 totalWeight, uint256 tokenAmountIn, uint256 swapFee ) external pure returns (uint256 poolAmountOut); function getSpotPrice(address tokenIn, address tokenOut) external view returns (uint256 spotPrice); function getSpotPriceSansFee(address tokenIn, address tokenOut) external view returns (uint256 spotPrice); function getSwapFee() external view returns (uint256); function getBalance(address token) external view returns (uint256); function getDenormalizedWeight(address token) external view returns (uint256); function getTotalDenormalizedWeight() external view returns (uint256); function getNormalizedWeight(address token) external view returns (uint256); function isPublicSwap() external view returns (bool); function isFinalized() external view returns (bool); }
Allows anyone to claim a token if they exist in a merkle root. This event is triggered whenever a call to #claim succeeds. Claim the given amount of the token to the given address. Reverts if the inputs are invalid. Returns the address of the token distributed by this contract. Returns the merkle root of the merkle tree containing account balances available to claim. Returns true if the index has been marked claimed. Returns the block timestamp when claims will end Returns true if the claim period has not ended.
interface IMerkleDistributor { event Claimed(uint256 index, address account, uint256 amount); function claim( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof ) external; function token() external view returns (address); function merkleRoot() external view returns (bytes32); function isClaimed(uint256 index) external view returns (bool); function endTime() external view returns (uint256); function isActive() external view returns (bool); }
12,889,156
[ 1, 19132, 1281, 476, 358, 7516, 279, 1147, 309, 2898, 1005, 316, 279, 30235, 1365, 18, 1220, 871, 353, 10861, 17334, 279, 745, 358, 7516, 21933, 18, 18381, 326, 864, 3844, 434, 326, 1147, 358, 326, 864, 1758, 18, 868, 31537, 309, 326, 4540, 854, 2057, 18, 2860, 326, 1758, 434, 326, 1147, 16859, 635, 333, 6835, 18, 2860, 326, 30235, 1365, 434, 326, 30235, 2151, 4191, 2236, 324, 26488, 2319, 358, 7516, 18, 2860, 638, 309, 326, 770, 711, 2118, 9350, 7516, 329, 18, 2860, 326, 1203, 2858, 1347, 11955, 903, 679, 2860, 638, 309, 326, 7516, 3879, 711, 486, 16926, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 5831, 6246, 264, 15609, 1669, 19293, 288, 203, 225, 871, 18381, 329, 12, 11890, 5034, 770, 16, 1758, 2236, 16, 2254, 5034, 3844, 1769, 203, 203, 225, 445, 7516, 12, 203, 565, 2254, 5034, 770, 16, 203, 565, 1758, 2236, 16, 203, 565, 2254, 5034, 3844, 16, 203, 565, 1731, 1578, 8526, 745, 892, 30235, 20439, 203, 225, 262, 3903, 31, 203, 203, 225, 445, 1147, 1435, 3903, 1476, 1135, 261, 2867, 1769, 203, 203, 225, 445, 30235, 2375, 1435, 3903, 1476, 1135, 261, 3890, 1578, 1769, 203, 203, 225, 445, 353, 9762, 329, 12, 11890, 5034, 770, 13, 3903, 1476, 1135, 261, 6430, 1769, 203, 203, 225, 445, 13859, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 225, 445, 15083, 1435, 3903, 1476, 1135, 261, 6430, 1769, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0xb8a88034bcf46e26c6bae1269ff2d051e2dee65c //Contract name: MintableToken //Balance: 0 Ether //Verification Date: 2/15/2018 //Transacion Count: 14 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping (address => Snapshot[]) balances; mapping (address => uint256) userWithdrawalBlocks; /** * @dev 'Snapshot' is the structure that attaches a block number to a * given value, the block number attached is the one that last changed the value * 'fromBlock' - is the block number that the value was generated from * 'value' - is the amount of tokens at a specific block number */ struct Snapshot { uint128 fromBlock; uint128 value; } /** * @dev tracks history of totalSupply */ Snapshot[] totalSupplyHistory; /** * @dev track history of 'ETH balance' for dividends */ Snapshot[] balanceForDividendsHistory; /** * @dev transfer token for a specified address * @param to - the address to transfer to. * @param value - the amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { return doTransfer(msg.sender, to, value); } /** * @dev internal function for transfers handling */ function doTransfer(address _from, address _to, uint _amount) internal returns(bool) { if (_amount == 0) { return true; } // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false var previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /** * @dev Queries the balance of `_owner` at a specific `_blockNumber` * @param _owner The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at `_blockNumber` */ function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token if ((balances[_owner].length == 0)|| (balances[_owner][0].fromBlock > _blockNumber)) { return 0; } else { return getValueAt(balances[_owner], _blockNumber); } } /** * @dev Total amount of tokens at a specific `_blockNumber`. * @param _blockNumber The block number when the totalSupply is queried * @return The total amount of tokens at `_blockNumber` */ function totalSupplyAt(uint _blockNumber) public constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { return 0; } else { return getValueAt(totalSupplyHistory, _blockNumber); } } /** * @dev `getValueAt` retrieves the number of tokens at a given block number * @param checkpoints The history of values being queried * @param _block The block number to retrieve the value at * @return The number of tokens being queried */ function getValueAt(Snapshot[] storage checkpoints, uint _block) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /** * @dev `updateValueAtNow` used to update the `balances` map and the `totalSupplyHistory` * @param checkpoints The history of data being updated * @param _value The new number of tokens */ function updateValueAtNow(Snapshot[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { Snapshot storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Snapshot storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } /** * @dev This function makes it easy to get the total number of tokens * @return The total number of tokens */ function redeemedSupply() public constant returns (uint) { return totalSupplyAt(block.number); } } contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); owner = newOwner; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { return doTransfer(_from, _to, _value); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract MintableToken is StandardToken { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; string public name = "Honey Mining Token"; string public symbol = "HMT"; uint8 public decimals = 8; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public canMint returns (bool) { totalSupply = totalSupply.add(_amount); uint curTotalSupply = redeemedSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_to); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_to], previousBalanceTo + _amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } /** * @dev Function to record snapshot block and amount */ function recordDeposit(uint256 _amount) public { updateValueAtNow(balanceForDividendsHistory, _amount); } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public returns (bool) { mintingFinished = true; MintFinished(); return true; } /** * @dev Function to calculate dividends * @return awailable for withdrawal ethere (wei value) */ function awailableDividends(address userAddress) public view returns (uint256) { uint256 userLastWithdrawalBlock = userWithdrawalBlocks[userAddress]; uint256 amountForWithdraw = 0; for(uint i = 0; i<=balanceForDividendsHistory.length-1; i++){ Snapshot storage snapshot = balanceForDividendsHistory[i]; if(userLastWithdrawalBlock < snapshot.fromBlock) amountForWithdraw = amountForWithdraw.add(balanceOfAt(userAddress, snapshot.fromBlock).mul(snapshot.value).div(totalSupplyAt(snapshot.fromBlock))); } return amountForWithdraw; } /** * @dev Function to record user withdrawal */ function recordWithdraw(address userAddress) public { userWithdrawalBlocks[userAddress] = balanceForDividendsHistory[balanceForDividendsHistory.length-1].fromBlock; } } contract HoneyMiningToken is Ownable { using SafeMath for uint256; MintableToken public token; /** * @dev Info of max supply */ uint256 public maxSupply = 300000000000000; /** * event for token purchase logging * @param purchaser who paid for the tokens, basically - 0x0, but could be user address on refferal case * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount - of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * event for referral comission logging * @param purchaser who paid for the tokens * @param beneficiary who got the bonus tokens * @param amount - of tokens as ref reward */ event ReferralBonus(address indexed purchaser, address indexed beneficiary, uint amount); /** * event for token dividends deposit logging * @param amount - amount of ETH deposited */ event DepositForDividends(uint256 indexed amount); /** * event for dividends withdrawal logging * @param holder - who has the tokens * @param amount - amount of ETH which was withdraw */ event WithdrawDividends(address indexed holder, uint256 amount); /** * event for dev rewards logging * @param purchaser - who paid for the tokens * @param amount - representation of dev reward */ event DevReward(address purchaser, uint amount); function HoneyMiningToken() public { token = new MintableToken(); } /** * @dev fallback function can be used to buy tokens */ function () public payable {buyTokens(0x0);} /** * @dev low level token purchase function * @param referrer - optional parameter for ref bonus */ function buyTokens(address referrer) public payable { require(msg.sender != 0x0); require(msg.sender != referrer); require(validPurchase()); //we dont need 18 decimals - and will use only 8 uint256 amount = msg.value.div(10000000000); // calculate token amount to be created uint256 tokens = amount.mul(rate()); require(tokens >= 100000000); uint256 devTokens = tokens.mul(30).div(100); if(referrer != 0x0){ require(token.balanceOf(referrer) >= 100000000); // 2.5% for referral and referrer uint256 refTokens = tokens.mul(25).div(1000); //tokens = tokens+refTokens; require(maxSupply.sub(redeemedSupply()) >= tokens.add(refTokens.mul(2)).add(devTokens)); //generate tokens for purchser token.mint(msg.sender, tokens.add(refTokens)); TokenPurchase(msg.sender, msg.sender, amount, tokens.add(refTokens)); token.mint(referrer, refTokens); ReferralBonus(msg.sender, referrer, refTokens); } else{ require(maxSupply.sub(redeemedSupply())>=tokens.add(devTokens)); //updatedReddemedSupply = redeemedSupply().add(tokens.add(devTokens)); //generate tokens for purchser token.mint(msg.sender, tokens); // log purchase TokenPurchase(msg.sender, msg.sender, amount, tokens); } token.mint(owner, devTokens); DevReward(msg.sender, devTokens); forwardFunds(); } /** * @return true if the transaction can buy tokens */ function validPurchase() internal constant returns (bool) { return !hasEnded() && msg.value != 0; } /** * @return true if sale is over */ function hasEnded() public constant returns (bool) { return maxSupply <= redeemedSupply(); } /** * @dev get current user balance * @param userAddress - address of user * @return current balance of tokens */ function checkBalance(address userAddress) public constant returns (uint){ return token.balanceOf(userAddress); } /** * @dev get user balance of tokens on specific block * @param userAddress - address of user * @param targetBlock - block number * @return address balance on block */ function checkBalanceAt(address userAddress, uint256 targetBlock) public constant returns (uint){ return token.balanceOfAt(userAddress, targetBlock); } /** * @dev get awailable dividends for withdrawal * @param userAddress - target * @return amount of ether (wei value) for current user */ function awailableDividends(address userAddress) public constant returns (uint){ return token.awailableDividends(userAddress); } /** * @return total purchased tokens value */ function redeemedSupply() public view returns (uint){ return token.totalSupply(); } /** * @dev user-related method for withdrawal dividends */ function withdrawDividends() public { uint _amount = awailableDividends(msg.sender); require(_amount > 0); msg.sender.transfer(_amount); token.recordWithdraw(msg.sender); WithdrawDividends(msg.sender, _amount); } /** * @dev function for deposit ether to token address as/for dividends */ function depositForDividends() public payable onlyOwner { require(msg.value > 0); token.recordDeposit(msg.value); DepositForDividends(msg.value); } function stopSales() public onlyOwner{ maxSupply = token.totalSupply(); } function forwardFunds() internal { owner.transfer(msg.value); } function rate() internal constant returns (uint) { if(redeemedSupply() < 1000000000000) return 675; else if (redeemedSupply() < 5000000000000) return 563; else return 450; } }
If the amount being transfered is more than the balance of the account the transfer returns false
var previousBalanceFrom = balanceOfAt(_from, block.number);
1,836,320
[ 1, 2047, 326, 3844, 3832, 7412, 329, 353, 1898, 2353, 326, 11013, 434, 326, 225, 2236, 326, 7412, 1135, 629, 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, 282, 569, 2416, 13937, 1265, 273, 11013, 951, 861, 24899, 2080, 16, 1203, 18, 2696, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Background SVG generator library BackgroundDetail { /// @dev Background N°1 => Ordinary function item_1() public pure returns (string memory) { return base( string( abi.encodePacked( '<g id="Ordinary"><radialGradient id="radial-gradient" cx="210" cy="212" r="210" gradientTransform="matrix(1, 0, 0, -1, 0, 422)" gradientUnits="userSpaceOnUse"> <stop offset="0" stop-color="#726680"/> <stop offset="1" stop-color="#4a4a4a"/> </radialGradient>', background("323232"), "</g>" ) ) ); } /// @dev Background N°2 => Uncommon function item_2() public pure returns (string memory) { return base( string( abi.encodePacked( '<g id="Uncommon"><radialGradient id="radial-gradient" cx="210" cy="212" r="210" gradientTransform="matrix(1, 0, 0, -1, 0, 422)" gradientUnits="userSpaceOnUse"> <stop offset="0" stop-color="#2fa675"/> <stop offset="1" stop-color="#106c48"/> </radialGradient>', background("125443"), "</g>" ) ) ); } /// @dev Background N°3 => Surprising function item_3() public pure returns (string memory) { return base( string( abi.encodePacked( '<g id="Surprising"><radialGradient id="radial-gradient" cx="210" cy="212" r="210" gradientTransform="matrix(1, 0, 0, -1, 0, 422)" gradientUnits="userSpaceOnUse"> <stop offset="0" stop-color="#4195ad"/> <stop offset="1" stop-color="#2b6375"/> </radialGradient>', background("204b59"), "</g>" ) ) ); } /// @dev Background N°4 => Impressive function item_4() public pure returns (string memory) { return base( string( abi.encodePacked( '<g id="Impressive"><radialGradient id="radial-gradient" cx="210" cy="212" r="210" gradientTransform="matrix(1, 0, 0, -1, 0, 422)" gradientUnits="userSpaceOnUse"> <stop offset="0" stop-color="#991fc4"/> <stop offset="1" stop-color="#61147d"/> </radialGradient>', background("470f5c"), "</g>" ) ) ); } /// @dev Background N°5 => Bloody function item_5() public pure returns (string memory) { return base( string( abi.encodePacked( '<g id="Bloody"><radialGradient id="radial-gradient" cx="210" cy="212" r="210" gradientTransform="matrix(1, 0, 0, -1, 0, 422)" gradientUnits="userSpaceOnUse"> <stop offset="0" stop-color="#8c134f"/> <stop offset="1" stop-color="#6d0738"/> </radialGradient>', background("410824"), "</g>" ) ) ); } /// @dev Background N°6 => Phenomenal function item_6() public pure returns (string memory) { return base( string( abi.encodePacked( '<g id="Phenomenal"><radialGradient id="radial-gradient" cx="210" cy="212" r="210" gradientTransform="matrix(1, 0, 0, -1, 0, 422)" gradientUnits="userSpaceOnUse"> <stop offset="0" stop-color="#fff38d"/> <stop offset="1" stop-color="#d68e4b"/> </radialGradient>', background("bd4e4a"), "</g>" ) ) ); } /// @dev Background N°7 => Artistic function item_7() public pure returns (string memory) { return base( string( abi.encodePacked( '<g id="Artistic"><radialGradient id="radial-gradient" cx="210" cy="-1171.6" r="210" gradientTransform="matrix(1, 0, 0, -1, 0, -961.6)" gradientUnits="userSpaceOnUse"> <stop offset="0.5" stop-color="#fff9ab"/> <stop offset="1" stop-color="#16c7b5"/> </radialGradient>', background("ff9fd7"), "</g>" ) ) ); } /// @dev Background N°8 => Unreal function item_8() public pure returns (string memory) { return base( string( abi.encodePacked( '<g id="Unreal"><radialGradient id="radial-gradient" cx="210.05" cy="209.5" r="209.98" gradientUnits="userSpaceOnUse"> <stop offset="0" stop-color="#634363"/><stop offset="1" stop-color="#04061c"/></radialGradient>', background("000"), "</g>" ) ) ); } function background(string memory color) private pure returns (string memory) { return string( abi.encodePacked( '<path d="M389.9,419.5H30.1a30,30,0,0,1-30-30V29.5a30,30,0,0,1,30-30H390a30,30,0,0,1,30,30v360A30.11,30.11,0,0,1,389.9,419.5Z" transform="translate(0 0.5)" fill="url(#radial-gradient)"/> <g> <path id="Main_Spin" fill="#', color, '" stroke="#', color, '" stroke-miterlimit="10" d="M210,63.3c-192.6,3.5-192.6,290,0,293.4 C402.6,353.2,402.6,66.7,210,63.3z M340.8,237.5c-0.6,2.9-1.4,5.7-2.2,8.6c-43.6-13.6-80.9,37.8-54.4,75.1 c-4.9,3.2-10.1,6.1-15.4,8.8c-33.9-50.6,14.8-117.8,73.3-101.2C341.7,231.7,341.4,234.6,340.8,237.5z M331.4,265.5 c-7.9,17.2-19.3,32.4-33.3,44.7c-15.9-23.3,7.6-55.7,34.6-47.4C332.3,263.7,331.8,264.6,331.4,265.5z M332.5,209.6 C265,202.4,217,279,252.9,336.5c-5.8,1.9-11.7,3.5-17.7,4.7c-40.3-73.8,24.6-163.5,107.2-148c0.6,6,1.2,12.2,1.1,18.2 C339.9,210.6,336.2,210,332.5,209.6z M87.8,263.9c28.7-11.9,56,24,36.3,48.4C108.5,299.2,96.2,282.5,87.8,263.9z M144.3,312.7 c17.8-38.8-23.4-81.6-62.6-65.5c-1.7-5.7-2.9-11.5-3.7-17.4c60-20.6,112.7,49.4,76,101.5c-5.5-2.4-10.7-5.3-15.6-8.5 C140.7,319.6,142.7,316.3,144.3,312.7z M174.2,330.4c32.6-64-28.9-138.2-97.7-118c-0.3-6.1,0.4-12.4,0.9-18.5 c85-18.6,151.7,71.7,110.8,147.8c-6.1-1-12.2-2.4-18.1-4.1C171.6,335.3,173,332.9,174.2,330.4z M337,168.6c-7-0.7-14.4-0.8-21.4-0.2 c-43.1-75.9-167.4-75.9-210.7-0.2c-7.3-0.6-14.9,0-22.1,0.9C118.2,47.7,301.1,47.3,337,168.6z M281.1,175.9c-3,1.1-5.9,2.3-8.7,3.6 c-29.6-36.1-93.1-36.7-123.4-1.2c-5.8-2.5-11.9-4.5-18-6.1c36.6-50.4,122.9-50,159,0.7C286.9,173.8,284,174.8,281.1,175.9z M249.6,193.1c-2.4,1.8-4.7,3.6-7,5.6c-16.4-15.6-46-16.4-63.2-1.5c-4.7-3.8-9.6-7.3-14.7-10.5c23.9-24.1,69.1-23.5,92.2,1.3 C254.4,189.6,252,191.3,249.6,193.1z M211.9,239.2c-5.2-10.8-11.8-20.7-19.7-29.4c10.7-8.1,27.9-7.3,37.9,1.6 C222.8,219.7,216.7,229.1,211.9,239.2z"> <animateTransform attributeName="transform" begin="0s" dur="20s" type="rotate" from="-360 210 210" to="0 210 210" repeatCount="indefinite" /> </path> <g id="Spin_Inverse"> <circle fill="none" stroke="#', color, '" stroke-width="7" stroke-dasharray="22.2609,22.2609" cx="210" cy="210" r="163"> <animateTransform attributeName="transform" begin="0s" dur="20s" type="rotate" from="360 210 210" to="0 210 210" repeatCount="indefinite" /> </circle> </g> <g id="Spin"> <circle fill="none" stroke="#', color, '" stroke-width="7" stroke-dasharray="22.2041,22.2041" cx="210" cy="210" r="183.8"> <animateTransform attributeName="transform" begin="0s" dur="20s" type="rotate" from="-360 210 210" to="0 210 210" repeatCount="indefinite" /> </circle> </g> </g>' ) ); } /// @notice Return the skin name of the given id /// @param id The skin Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Ordinary"; } else if (id == 2) { name = "Unusual"; } else if (id == 3) { name = "Surprising"; } else if (id == 4) { name = "Impressive"; } else if (id == 5) { name = "Bloody"; } else if (id == 6) { name = "Phenomenal"; } else if (id == 7) { name = "Artistic"; } else if (id == 8) { name = "Unreal"; } } /// @dev The base SVG for the body function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="background">', children, "</g>")); } }
@dev Background N°6 => Phenomenal
function item_6() public pure returns (string memory) { return base( string( abi.encodePacked( '<g id="Phenomenal"><radialGradient id="radial-gradient" cx="210" cy="212" r="210" gradientTransform="matrix(1, 0, 0, -1, 0, 422)" gradientUnits="userSpaceOnUse"> <stop offset="0" stop-color="#fff38d"/> <stop offset="1" stop-color="#d68e4b"/> </radialGradient>', background("bd4e4a"), "</g>" ) ) ); }
902,389
[ 1, 8199, 423, 131, 113, 26, 516, 4360, 275, 362, 275, 287, 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, 761, 67, 26, 1435, 1071, 16618, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 203, 5411, 1026, 12, 203, 7734, 533, 12, 203, 10792, 24126, 18, 3015, 4420, 329, 12, 203, 13491, 2368, 75, 612, 1546, 3731, 275, 362, 275, 287, 14050, 6012, 649, 15651, 612, 1546, 6012, 649, 17, 20219, 6, 9494, 1546, 22, 2163, 6, 6143, 1546, 22, 2138, 6, 436, 1546, 22, 2163, 6, 10292, 4059, 1546, 5667, 12, 21, 16, 374, 16, 374, 16, 300, 21, 16, 374, 16, 27252, 2225, 10292, 7537, 1546, 1355, 3819, 1398, 3727, 6441, 411, 5681, 1384, 1546, 20, 6, 2132, 17, 3266, 1546, 7, 25449, 7414, 72, 6, 21259, 411, 5681, 1384, 1546, 21, 6, 2132, 17, 3266, 1546, 7, 72, 9470, 73, 24, 70, 6, 21259, 7765, 6012, 649, 15651, 1870, 16, 203, 13491, 5412, 2932, 16410, 24, 73, 24, 69, 6, 3631, 203, 13491, 6823, 75, 2984, 203, 10792, 262, 203, 7734, 262, 203, 5411, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/97/0xF6f217CBFb2B256FF9663B14F353698a661F4772/sources/contracts/Ac.sol
ENVIRONMENT VARIABLESBUSD TESTNET TOKEN ADDRESS: 0xeD24FC36d5Ee211Ea25A80239Fb8C4Cfd80f12EeTESTNET OWNER ADDRESS:10 BUSD: ALLOWANCE : 10000000000000000000THIS ACTUAL CONTRACT ADDRESS:
contract Ac is Ownable, Pausable { event CoinBought( address buyer, uint256 packType, uint date ); event CoinClaimed( address claimer, uint256 packType, uint date ); event CoinUpdated( address updater, address to, uint256 number, uint date ); event NewVersionMigration( address newContract, uint256 busd, uint256 coins ); constructor(address _BUSD, address _theOwner, uint256 _coins) { BUSD = IERC20(_BUSD); _owner = _theOwner; coins = _coins; } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function addBalanceRequest(uint256 _quantity, address _receptor) public onlyOwner whenNotPaused{ require(_quantity>0, "For add balance to an account, the amount should be greater than 0"); addBalance(_quantity); emit CoinUpdated(msg.sender, _receptor, _quantity, block.timestamp); } function subtractBalanceRequest(uint256 _quantity, address _receptor) public onlyOwner whenNotPaused{ require(_quantity>0, "For subtract balance to an account, the amount should be greater than 0"); subtractBalance(_quantity); emit CoinUpdated(msg.sender, _receptor, _quantity, block.timestamp); } function addBalance(uint256 _newAdd) private whenNotPaused{ users[msg.sender] +=_newAdd; } function subtractBalance(uint256 _newAdd) private whenNotPaused{ users[msg.sender] -=_newAdd; } function buyPackOne() public payable whenNotPaused{ uint256 packType = 1; uint256 units = 100; require(IERC20(BUSD).balanceOf(msg.sender) >= value, "BUSD: Insufficient funds"); require(IERC20(BUSD).allowance(msg.sender, address(this)) >= value, "BUSD: Insufficient allowance funds"); SafeERC20.safeTransferFrom(IERC20(BUSD), msg.sender, address(this), value); coins +=units; addBalance(units); emit CoinBought(msg.sender, packType, block.timestamp); } function buyPackTwo() public payable whenNotPaused{ uint256 packType = 2; uint256 units = 200; require(IERC20(BUSD).balanceOf(msg.sender) >= precio, "BUSD: Insufficient funds"); require(IERC20(BUSD).allowance(msg.sender, address(this)) >= precio, "BUSD: Insufficient allowance funds"); SafeERC20.safeTransferFrom(IERC20(BUSD), msg.sender, address(this), precio); coins +=units; addBalance(units); emit CoinBought(msg.sender, packType, block.timestamp); } function buyPackThree() public payable whenNotPaused{ uint256 packType = 3; uint256 units = 300; require(IERC20(BUSD).balanceOf(msg.sender) >= value, "BUSD: Insufficient funds"); require(IERC20(BUSD).allowance(msg.sender, address(this)) >= value, "BUSD: Insufficient allowance funds"); SafeERC20.safeTransferFrom(IERC20(BUSD), msg.sender, address(this), value); coins +=units; addBalance(units); emit CoinBought(msg.sender, packType, block.timestamp); } function claimPackOne() public whenNotPaused{ uint256 packType = 1; uint256 units = 100; require(users[msg.sender]>0, "The user has no coins to claim"); require(users[msg.sender]>=units, "COINS: Insufficient user funds"); require(IERC20(BUSD).balanceOf(address(this)) >= value, "BUSD: Contract insufficient funds"); require(coins>= units, "COINS: Insufficient global funds"); IERC20(BUSD).transfer(msg.sender, value); coins -=units; subtractBalance(units); emit CoinClaimed(msg.sender, packType, block.timestamp); } function claimPackTwo() public whenNotPaused{ uint256 packType = 2; uint256 units = 500; require(users[msg.sender]>0, "The user has no coins to claim"); require(users[msg.sender]>=units, "COINS: Insufficient user funds"); require(IERC20(BUSD).balanceOf(address(this)) >= value, "BUSD: Contract insufficient funds"); require(coins>= units, "COINS: Insufficient global funds"); IERC20(BUSD).transfer(msg.sender, value); coins -=units; subtractBalance(units); emit CoinClaimed(msg.sender, packType, block.timestamp); } function claimPackThree() public whenNotPaused{ uint256 packType = 3; uint256 units = 2000; require(users[msg.sender]>0, "The user has no coins to claim"); require(users[msg.sender]>=units, "COINS: Insufficient user funds"); require(IERC20(BUSD).balanceOf(address(this)) >= value, "BUSD: Contract insufficient funds"); require(coins>= units, "COINS: Insufficient global funds"); IERC20(BUSD).transfer(msg.sender, value); coins -=units; subtractBalance(units); emit CoinClaimed(msg.sender, packType, block.timestamp); } function claimPackFour() public whenNotPaused{ uint256 packType = 4; uint256 units = 5000; require(users[msg.sender]>0, "The user has no coins to claim"); require(users[msg.sender]>=units, "COINS: Insufficient user funds"); require(IERC20(BUSD).balanceOf(address(this)) >= value, "BUSD: Contract insufficient funds"); require(coins>= units, "COINS: Insufficient global funds"); IERC20(BUSD).transfer(msg.sender, value); coins -=units; subtractBalance(units); emit CoinClaimed(msg.sender, packType, block.timestamp); } function exportFundsVersion(address _destinatary) public onlyOwner whenNotPaused{ require(IERC20(BUSD).balanceOf(address(this)) > 0, "There aren't BUSD tokens to export"); uint256 tokens = IERC20(BUSD).balanceOf(address(this)); IERC20(BUSD).transfer(_destinatary, tokens); emit NewVersionMigration(_destinatary, tokens, coins); } }
3,282,756
[ 1, 1157, 30417, 22965, 55, 3000, 9903, 22130, 14843, 14275, 11689, 10203, 30, 374, 6554, 40, 3247, 4488, 5718, 72, 25, 41, 73, 22, 2499, 41, 69, 2947, 37, 31644, 5520, 42, 70, 28, 39, 24, 39, 8313, 3672, 74, 2138, 41, 73, 16961, 14843, 531, 22527, 11689, 10203, 30, 2163, 605, 3378, 40, 30, 18592, 4722, 294, 2130, 12648, 2787, 11706, 2455, 5127, 14684, 14235, 8020, 2849, 1268, 11689, 10203, 30, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 12848, 353, 14223, 6914, 16, 21800, 16665, 288, 203, 203, 203, 565, 871, 28932, 13809, 9540, 12, 203, 3639, 1758, 27037, 16, 203, 3639, 2254, 5034, 2298, 559, 16, 203, 3639, 2254, 1509, 203, 565, 11272, 203, 203, 565, 871, 28932, 9762, 329, 12, 203, 3639, 1758, 927, 69, 4417, 16, 203, 3639, 2254, 5034, 2298, 559, 16, 203, 3639, 2254, 1509, 203, 565, 11272, 203, 203, 565, 871, 28932, 7381, 12, 203, 3639, 1758, 7760, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1300, 16, 203, 3639, 2254, 1509, 203, 565, 11272, 203, 203, 565, 871, 1166, 1444, 10224, 12, 203, 3639, 1758, 394, 8924, 16, 203, 3639, 2254, 5034, 5766, 72, 16, 203, 3639, 2254, 5034, 276, 9896, 203, 565, 11272, 203, 203, 203, 203, 203, 565, 3885, 12, 2867, 389, 3000, 9903, 16, 1758, 389, 5787, 5541, 16, 2254, 5034, 389, 71, 9896, 13, 288, 203, 1377, 605, 3378, 40, 273, 467, 654, 39, 3462, 24899, 3000, 9903, 1769, 203, 1377, 389, 8443, 273, 389, 5787, 5541, 31, 203, 1377, 276, 9896, 273, 389, 71, 9896, 31, 203, 565, 289, 203, 203, 565, 445, 11722, 1435, 1071, 1338, 5541, 288, 203, 3639, 389, 19476, 5621, 203, 565, 289, 203, 203, 565, 445, 640, 19476, 1435, 1071, 1338, 5541, 288, 203, 3639, 389, 318, 19476, 5621, 203, 565, 289, 203, 203, 565, 445, 527, 13937, 691, 12, 11890, 5034, 389, 16172, 16, 1758, 389, 266, 6757, 13, 1071, 1338, 5541, 1347, 1248, 28590, 95, 203, 3639, 2583, 24899, 16172, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; // Powerball contract // Keep up and until the moon! // To implement: 1. liquidity pool, 2. winning probability 3. how close you were versus winning (just to show in front end) // 4. how to deal with contract balance received from airdrop // Key question -- what's balance for this, and what's balance for owner? contract FreePowerball is ERC20, Ownable { using SafeMath for uint256; using Address for address; // contract setup uint256 private _ownershipLimit = 5; // in 0.0001 // fee structure //uint256 private _totalSupply = 1 * 10 ** 12 * 10 ** 18; uint256 private _rewardFee = 4; uint256 private _liquidityFee = 2; uint256 private _rewardPool; // monetary system uint256 private _mTotalBase = 10 ** 15; uint256 private _mMultiplierPrecision = 10 ** 10; uint256 private _mMultiplier = 1 * _mMultiplierPrecision; uint256 private _mTotalSupply = _mTotalBase.mul(_mMultiplier).div(_mMultiplierPrecision); // previous day trading volume uint256 private _previousDayStart = 0; uint256 private _previousDayVol = 0; uint256 private _currentDayVol = 0; // winning probability uint256 private _volumeWinProbMultiplier = 1; // prob = a * vol% + b * holding % uint256 private _holdingWinProbMultiplier = 2; uint256 private _step1ProbMultiplier = 100; // this = 100 / _step2ProbCap uint256 private _step1ProbCap = 80; uint256 private _step2ProbCap = 1; // 1%, 2% or 4% // winner verification -- to prevent hacks address private _lastBuyder = address(0); uint256 private _firstVerifier = 5; uint256 private _secondVerifier = 10; uint256 private _winVeirificationMod1 = 10; uint256 private _winVeirificationMod2 = 10; bool private _lotteryInVerification = false; address private _lotteryCandidate; uint256 private _lotteryCandidateHash; uint256 private _numOfVerifier = 0; // lottery uint256 private _lotteryPrecision = 10 ** 7; // need to be bigger than total balance, or have a floor uint256 private _prizeShare = 5; // 10% of the reward pool is given out to the lottery winner -- can make the probability higher uint256 private _airDropShare = 5; // 10% of the reward pool is given out in an airdrop bool private _lotteryLocked = false; address private _lockedCandidate = address(0); uint256 private _lockedHash = 0; uint256 private _currentRound = 0; // historical lottery info struct lotteryHistory { uint256 time; uint256 reward; address winner; } mapping (address => uint256) private _redeemable; mapping (uint256 => lotteryHistory) private _previousRounds; mapping (address => uint256[3]) private _lastParticipance; // diable special transfer bool private _specialTransferDisabled = false; event LaunchedAndSpecialTransferDisabled(); event LotterWinner(address winner); event AirDrop(uint256 amount); event LotterRedeemed(address winner, uint256 reward); constructor () ERC20("FreePowerball", "POWERBALL") Ownable() public { _balances[owner()] = _mTotalBase; emit Transfer(address(0), owner(), _mTotalBase); } // -------------------------------------------------------------------------- // Monetary system // -------------------------------------------------------------------------- function _baseToMoney(uint256 amountBase) private view returns (uint256) { return amountBase.mul(_mMultiplier); } function _moneyToBase(uint256 amountMoney) private view returns (uint256) { return amountMoney.div(_mMultiplier); } function getMoneyMultiplier() private view returns (uint256) { return _mMultiplier; } // // view total balance function getTotalBalance() public view returns (uint256) { return _baseToMoney(_mTotalBase); } // view reward pool balance function getRewardBalance() public view returns (uint256) { return _baseToMoney(_rewardPool); } // view real balance of each account function balanceOf(address account) public view override returns (uint256) { return _baseToMoney(_balances[account]); } // check total in circulation // total base money: reward pool + holders + contract holding + liquidity pool function getTotalCirculation(bool baseBool) public view returns (uint256) { uint256 inCirculation = _mTotalBase - _rewardPool - _balances[address(this)]; if (baseBool) { return inCirculation; } return _baseToMoney(inCirculation); } // -------------------------------------------------------------------------- // control // -------------------------------------------------------------------------- function setOwnershipLimit(uint256 limit) public onlyOwner() { _ownershipLimit = limit; } function setTaxFeePercent(uint256 reward, uint256 liquidity) public onlyOwner() { _rewardFee = reward; _liquidityFee = liquidity; } function setVerifier(uint256 verifier1, uint256 verifier2) public onlyOwner() { _firstVerifier = verifier1; _secondVerifier = verifier2; } function setWinningProb(uint256 newVolumeWinMultiple, uint256 newHoldingWinMultiple, uint256 newStep1Cap, uint256 newStep2Cap) public onlyOwner() { _volumeWinProbMultiplier = newVolumeWinMultiple; // prob = a * vol% + b * holding % _holdingWinProbMultiplier = newHoldingWinMultiple; _step1ProbCap = newStep1Cap; _step2ProbCap = newStep2Cap; require(((_step2ProbCap == 1) || (_step2ProbCap == 2) || (_step2ProbCap == 4)), "Winning prob cap has only three options 1, 2, 4"); // to maintain the winning probability -- adjust the step1 probabiity based on verification probability if (_step2ProbCap == 1) { _winVeirificationMod1 = 10; _winVeirificationMod2 = 10; _step1ProbMultiplier = 100; } if (_step2ProbCap == 2) { _winVeirificationMod1 = 5; _winVeirificationMod2 = 10; _step1ProbMultiplier = 50; } if (_step2ProbCap == 4) { _winVeirificationMod1 = 5; _winVeirificationMod2 = 5; _step1ProbMultiplier = 25; } } function setPrizeDropShare(uint256 newPrizeShare, uint256 newAirDropShare) public onlyOwner() { _prizeShare = newPrizeShare; _airDropShare = newAirDropShare; } // -------------------------------------------------------------------------- // airdrop // -------------------------------------------------------------------------- function _autoAirDrop() private { uint256 contractBalancePre = _baseToMoney(_balances[address(this)]); uint256 mAmountAirDrop = _rewardPool.mul(_airDropShare).div(100); _rewardPool -= mAmountAirDrop; _mMultiplier = _mMultiplier.mul(_mTotalBase.mul(_mMultiplierPrecision).div(_mTotalBase - mAmountAirDrop)).div(_mMultiplierPrecision); _mTotalBase -= mAmountAirDrop; emit AirDrop(mAmountAirDrop); // burn the ones received by contract uint256 contractBalanceAfter = _baseToMoney(_balances[address(this)]); uint256 toBurn = _moneyToBase(contractBalanceAfter - contractBalancePre); _burn(address(this), toBurn); } function manualAirDrop(uint256 percentageToDrop) public onlyOwner() { uint256 contractBalancePre = _baseToMoney(_balances[address(this)]); require(percentageToDrop <= 99, "Not enough amount in reward pool to airdrop"); uint256 mAmountAirDrop = _rewardPool.mul(percentageToDrop).div(100); _rewardPool -= mAmountAirDrop; _mMultiplier.mul(_mTotalBase.mul(_mMultiplierPrecision).div(_mTotalBase - mAmountAirDrop)).div(_mMultiplierPrecision); _mTotalBase -= mAmountAirDrop; emit AirDrop(mAmountAirDrop); // burn the ones received by contract uint256 contractBalanceAfter = _baseToMoney(_balances[address(this)]); uint256 toBurn = _moneyToBase(contractBalanceAfter - contractBalancePre); _burn(address(this), toBurn); } // -------------------------------------------------------------------------- // transfer // -------------------------------------------------------------------------- // compute values before transfer happens function _getTransferValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 rewardToCollect = tAmount.mul(_rewardFee).div(100); uint256 liquidityToCollect = tAmount.mul(_liquidityFee).div(100); uint256 amountToTransfer = tAmount.sub(rewardToCollect).sub(liquidityToCollect); return (amountToTransfer, rewardToCollect, liquidityToCollect); } // transfer function function _transfer(address sender, address receipient, uint256 amountIn) internal override { // update trading volume _updateTradingVolume(); // convert money to base amount uint256 amount = _moneyToBase(amountIn); // check eligibility require(sender != address(0), "ERC20: transfer from the zero address"); require(receipient != address(0), "ERC20: transfer to the zero address"); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); // compute amount to be received (uint256 amountAfterTax, uint256 rewardToCollect, uint256 liquidityToCollect) = _getTransferValues(amount); // check if new ownership is below limit + redeem uint256 newOwnership = _balances[receipient] + amountAfterTax; uint256 redeemable = _redeemable[receipient]; if (redeemable < 1) { require(newOwnership.mul(10000).div(_mTotalBase) <= _ownershipLimit, "Amount after purchase exceeds ownership limit"); } else { uint baseToRedeem = redeemable.mul(_rewardPool).div(100); newOwnership += baseToRedeem; _rewardPool -= baseToRedeem; _autoAirDrop(); emit LotterRedeemed(receipient, baseToRedeem); } // make the transfer _rewardPool += rewardToCollect; _balances[sender] = senderBalance - amount; _balances[receipient] = newOwnership; emit Transfer(sender, receipient, amountAfterTax); // cumulating trading volume and track last buyer _currentDayVol += amount; _lastBuyder = receipient; // if lottery is open -- if the person is eligible, run step 1 if (!_lotteryLocked) { if (_getAvailabilityForLottery(receipient)) { _checkWinStep1(receipient, amount); } else { _numOfVerifier += 1; _lastParticipance[receipient] = [block.timestamp, _currentRound, 0]; if (_numOfVerifier == _firstVerifier) { _checkWinStep2Verification1(receipient, amount); } if (_numOfVerifier == _secondVerifier) { _checkWinStep2Verification2(receipient, amount); } } } } function _updateTradingVolume() private { if (block.timestamp - _previousDayStart > 1 days) { _previousDayStart = block.timestamp; _previousDayVol = _currentDayVol; _currentDayVol = 0; } } // -------------------------------------------------------------------------- // probabilities // -------------------------------------------------------------------------- // winning p1 based on holding function _getHoldingPercentage(address buyer) private view returns (uint256) { uint256 eligibleShares = getTotalCirculation(true); return balanceOf(buyer).mul(_lotteryPrecision).div(eligibleShares); } // winning p2 based on volume function _getVolumePercentage(uint256 amount) private view returns (uint256) { return amount.mul(_lotteryPrecision).div(_previousDayVol); } // generate winning probability function _getWinProbStep1(address buyer, uint256 amount) private view returns (uint256) { uint256 prob; prob = _getHoldingPercentage(buyer) * _holdingWinProbMultiplier; prob += _getVolumePercentage(amount) * _volumeWinProbMultiplier; if (prob == 0){ prob += _lotteryPrecision / 10000; // lowest probability is 1/10000 } if (prob >= _step1ProbCap * _lotteryPrecision / 100){ prob = _step1ProbCap * _lotteryPrecision / 100; // capped ste1 prob } return prob; } // check if step 1 wins function _checkWinStep1(address buyer, uint256 amount) private returns (bool) { uint256 lotteryHash = uint256(keccak256(abi.encode(buyer, _lastBuyder ,amount, block.timestamp))) % _lotteryPrecision; if (lotteryHash < _getWinProbStep1(buyer, amount)) { _lotteryLocked = true; _lockedCandidate = buyer; _lockedHash = lotteryHash; return true; } _lastParticipance[buyer] = [block.timestamp, _currentRound, 0]; return false; } // two verifications for the winner function _checkWinStep2Verification1(address verifier, uint amount) private { uint256 verifyHash1 = uint256(keccak256(abi.encode(verifier, amount, block.timestamp))) % _winVeirificationMod1; if (_lockedHash % _winVeirificationMod1 == verifyHash1) { return; } else { _lastParticipance[_lockedCandidate] = [block.timestamp, _currentRound, 1]; _unlockLotteryPool(); return; } } function _checkWinStep2Verification2(address verifier, uint amount) private { uint256 verifyHash2 = uint256(keccak256(abi.encode(verifier, amount, block.timestamp))) % _winVeirificationMod2; if (_lockedHash % _winVeirificationMod2 == verifyHash2) { _redeemable[_lockedCandidate] = _prizeShare; _previousRounds[_currentRound] = lotteryHistory(block.timestamp, _prizeShare, _lockedCandidate); _lastParticipance[_lockedCandidate] = [block.timestamp, _currentRound, 2]; return; } else{ _unlockLotteryPool(); } } function _unlockLotteryPool() private { _lotteryLocked = false; _lockedCandidate = address(0); _lockedHash = 0; _numOfVerifier = 0; return; } // -------------------------------------------------------------------------- // lottery // -------------------------------------------------------------------------- function getRedeemable(address buyer) public view returns(uint256) { return _baseToMoney(_redeemable[buyer]); } function _getAvailabilityForLottery(address buyer) private view returns(bool) { if (buyer == address(this)) { return false; } else return (block.timestamp - _lastParticipance[buyer][0] >= 1 days); } function getCurrentRound() public view returns(uint256) { return _currentRound; } function getHistRoundInfo(uint256 round) public view returns(uint256, uint256, address) { return (_previousRounds[round].time, _previousRounds[round].reward, _previousRounds[round].winner); } function getHistPersonalInfo(address buyer) public view returns(uint256, uint256) { return (_lastParticipance[buyer][0], _lastParticipance[buyer][1]); } // -------------------------------------------------------------------------- // special transfer // -------------------------------------------------------------------------- function _burn(address account, uint256 amount) internal override { 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; _mTotalBase -= amount; emit Transfer(account, address(0), _baseToMoney(amount)); } function disableSpecialTransfer() public { _specialTransferDisabled = true; emit LaunchedAndSpecialTransferDisabled(); } // vanilla transfer function specialVanillaTransfer(address sender, address receipient, uint256 amountIn) public { require(!_specialTransferDisabled, "Special Transfer is already disabled"); // convert money to base amount uint256 amount = _moneyToBase(amountIn); // check eligibility require(sender != address(0), "ERC20: transfer from the zero address"); require(receipient != address(0), "ERC20: transfer to the zero address"); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[receipient] += amount; emit Transfer(sender, receipient, amountIn); } }
winning p2 based on volume
function _getVolumePercentage(uint256 amount) private view returns (uint256) { return amount.mul(_lotteryPrecision).div(_previousDayVol); }
12,588,759
[ 1, 8082, 2093, 293, 22, 2511, 603, 3940, 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, 202, 915, 389, 588, 4545, 16397, 12, 11890, 5034, 3844, 13, 3238, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 202, 202, 2463, 3844, 18, 16411, 24899, 23372, 387, 93, 15410, 2934, 2892, 24899, 11515, 4245, 17431, 1769, 203, 202, 97, 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 ]
pragma solidity ^0.5.2; import "../Proxy/ProxySettable.sol"; import "../Proxy/ProxyGettable.sol"; contract ProxyAdminDelegated is ProxyGettable, ProxySettable { /** * @dev This event will be emitted every time the implementation gets upgraded * @param impl representing the address of the upgraded implementation */ event Upgraded(address indexed impl); /** * @dev Event to show ownership has been transferred * @param newOwner representing the address of the new owner */ event OwnershipTransferred(address newOwner); /** * @dev Upgrades the implementation address * @param impl representing the address of the new implementation to be set */ function upgradeTo(address impl) public { require(impl != address(0), "ProxyAdminDelegated: upgradeTo with zero address implementation"); require(impl != implementation(), "ProxyAdminDelegated: upgradeTo with no change to implementation address"); _setImplementation(impl); emit Upgraded(impl); } /** * @dev Transfers proxy ownership to a new owner address * @param newOwner the address of the new owner */ function transferProxyOwnership(address newOwner) external { require(newOwner != address(0), "ProxyAdminDelegated: transferProxyOwnership with zero address for newOwner"); _setProxyOwner(newOwner); emit OwnershipTransferred(newOwner); } }
* @dev This event will be emitted every time the implementation gets upgraded @param impl representing the address of the upgraded implementation/* @dev Event to show ownership has been transferred @param newOwner representing the address of the new owner/* @dev Upgrades the implementation address @param impl representing the address of the new implementation to be set/
function upgradeTo(address impl) public { require(impl != address(0), "ProxyAdminDelegated: upgradeTo with zero address implementation"); require(impl != implementation(), "ProxyAdminDelegated: upgradeTo with no change to implementation address"); _setImplementation(impl); emit Upgraded(impl); }
13,075,071
[ 1, 2503, 871, 903, 506, 17826, 3614, 813, 326, 4471, 5571, 31049, 225, 9380, 5123, 326, 1758, 434, 326, 31049, 4471, 19, 225, 2587, 358, 2405, 23178, 711, 2118, 906, 4193, 225, 394, 5541, 5123, 326, 1758, 434, 326, 394, 3410, 19, 225, 1948, 13088, 326, 4471, 1758, 225, 9380, 5123, 326, 1758, 434, 326, 394, 4471, 358, 506, 444, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 8400, 774, 12, 2867, 9380, 13, 1071, 288, 203, 565, 2583, 12, 11299, 480, 1758, 12, 20, 3631, 315, 3886, 4446, 15608, 690, 30, 8400, 774, 598, 3634, 1758, 4471, 8863, 203, 565, 2583, 12, 11299, 480, 4471, 9334, 315, 3886, 4446, 15608, 690, 30, 8400, 774, 598, 1158, 2549, 358, 4471, 1758, 8863, 203, 565, 389, 542, 13621, 12, 11299, 1769, 203, 565, 3626, 1948, 19305, 12, 11299, 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 ]
// SPDX-License-Identifier: Unlicensed pragma solidity >=0.7.0 <0.8.0; pragma abicoder v2; import { SafeMath } from "./SafeMath.sol"; /*** * @author codeDcode member Chinmay Vemuri * @dev Can change this to library instead with internal functions ? * @dev Here, fees are represented in basis points. 1bp = 1/100 percent = 0.01% */ library Formulas { using SafeMath for uint256; function calcMarketMakerFee(uint256 _marketMakerFeePer, uint256 _amount) internal pure returns(uint256) { /// @dev Check for overflows. Theoretically, they shouldn't occur here since _amount is in wei and is usually much greater than 10**4. /// @dev Since the _amount is in weis, decimals can be ignored as they don't have a lot of value. This functions rounds towards 0. /// @notice _marketMakerFeePer = 1% which is equal to 100bp. require(_marketMakerFeePer.mul(_amount) > 10**4, "Amount too small !"); // return _marketMakerFeePer*_amount/10**4; return (_marketMakerFeePer.mul(_amount)).div(10**4); } function calcValidationFee(uint256 _marketMakerFeePer, uint256 _validationFeePer, uint256 _amount) internal pure returns(uint256) { require((_validationFeePer.sub(_marketMakerFeePer)).mul(_amount) > 10**4, "Amount is too small !"); return (((_validationFeePer.sub(_marketMakerFeePer)).mul(_amount)).div(10**4)); } function calcRightWrongOptionsBalances(uint256 _rightOption, uint256[] memory _optionBalances) internal pure returns(uint256, uint256) { uint256 _wrongOptionsBalance = 0; uint256 _rightOptionBalance = 0; for(uint8 i = 0; i < _optionBalances.length; ++i) (i != _rightOption)? _wrongOptionsBalance = _wrongOptionsBalance.add(_optionBalances[i]): _rightOptionBalance = _rightOptionBalance.add(_optionBalances[i]); return (_rightOptionBalance, _wrongOptionsBalance); } function calcPayout( uint256 _userStakeOnRightOption, uint256 _rightOptionBalance, uint256 _wrongOptionsBalance) internal pure returns(uint256) { // mapping: this user, B=>7.5, right = 1000, wrong 20 // extraBalance: // rightOption += wrongBalance // uint256 payout = 0; /// @dev payout = userStake + (userStake*_wrongOptionsBalance/_rightOptionBalance); /// @dev Decimals are not required here too if we consider _userStake in wei. // payout = payout.add(_userStake.add(_userStake.mul(_wrongOptionsBalance.div(_rightOptionBalance)))); return _userStakeOnRightOption.add( (_userStakeOnRightOption.mul( _wrongOptionsBalance)).div(_rightOptionBalance)); } function calcValidationFeePer(uint256 _currTime, uint256 _startTime, uint256 _endTime) internal pure returns(uint256) { /*** * @dev Check for rounding errors. * @dev Return the percentage in bp format. Precision = 2 decimal places. * So, 60% = 6000bp, 5% = 500bp, 0.01% = 1bp and so on. */ uint256 fee = 0; uint256 calFactor = 10**10; // No scaling factors as this factor is neutralized later // uint256 T = (_endTime - _startTime)/86400; uint256 T = (_endTime.sub(_startTime)).div(86400); // uint256 t = (_currTime - _startTime)/86400; uint256 t = (_currTime.sub(_startTime)).div(86400); assert(t>=0 && T>0 && t<=T); uint256 nmin = 0; // Func min value uint256 nmax = T**5; // Func max value // fee = (calFactor*(t**5-nmin))/(nmax-nmin); fee = (((t**5).sub(nmin)).mul(calFactor)).div(nmax.sub(nmin)); uint256 fmin = 200; // The min fee applied * 100 uint256 fmax = 7500; // The max fee applied * 100 // fee = fmin + ((fmax-fmin)*fee)/calFactor; // calFactor neutralized here fee = fmin.add((fee.mul(fmax.sub(fmin)).div(calFactor))); assert(fee>=fmin && fee<=fmax); return fee; } function calcWinningOption(uint256[] calldata _reportingOptionBalances) internal pure returns(uint256) { uint256 maxAmount = 0; uint256 optionId = _reportingOptionBalances.length - 1; // By default it is invalid for(uint8 i = 0; i < _reportingOptionBalances.length; ++i) { uint256 optionAmount = _reportingOptionBalances[i]; if( optionAmount > maxAmount) { maxAmount = optionAmount; optionId = i; } } return optionId; } }
No scaling factors as this factor is neutralized later
uint256 calFactor = 10**10;
6,417,021
[ 1, 2279, 10612, 14490, 487, 333, 5578, 353, 22403, 287, 1235, 5137, 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, 3639, 2254, 5034, 1443, 6837, 273, 1728, 636, 2163, 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 ]
./full_match/44787/0x808955925377723FeC0249B64E62A63705b7A778/sources/contracts/StarFarm.sol
Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)).add(pool.extraAmount); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 accStarPerShare = starReward.mul(1e12).div(lpSupply); for(uint256 unumber = 0; unumber < pool.size; ++unumber){ address userAddr = userIndex[_pid][unumber]; if(userIndex[_pid][unumber] == address(0)||userAddr == _msgSender()){ continue; } UserInfo storage user = userInfo[_pid][userAddr]; if(user.amount >0){ (uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(userAddr); uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain.add(_parentGain)).div(100)); uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain.add(_parentGain)).div(100)); uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12); uint256 _nftAmountpendingStar = _nftAmountGain.mul(accStarPerShare).div(1e12); user.reward = user.reward.add(_amountpendingStar); user.nftReward = user.nftReward.add(_nftAmountpendingStar); } } pool.accStarPerShare = accStarPerShare; pool.lastRewardBlock = block.number; } }
13,263,549
[ 1, 1891, 19890, 3152, 434, 326, 864, 2845, 358, 506, 731, 17, 869, 17, 712, 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 ]
[ 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, 565, 445, 1089, 2864, 12, 11890, 5034, 389, 6610, 13, 1071, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 309, 261, 2629, 18, 2696, 1648, 2845, 18, 2722, 17631, 1060, 1768, 13, 288, 203, 5411, 327, 31, 203, 3639, 289, 203, 3639, 2254, 5034, 12423, 3088, 1283, 273, 2845, 18, 9953, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 13, 2934, 1289, 12, 6011, 18, 7763, 6275, 1769, 203, 3639, 309, 261, 9953, 3088, 1283, 422, 374, 13, 288, 203, 5411, 2845, 18, 2722, 17631, 1060, 1768, 273, 1203, 18, 2696, 31, 203, 5411, 327, 31, 203, 3639, 289, 203, 3639, 2254, 5034, 15027, 273, 31863, 5742, 12, 6011, 18, 2722, 17631, 1060, 1768, 16, 1203, 18, 2696, 1769, 203, 3639, 2254, 5034, 10443, 17631, 1060, 273, 15027, 18, 16411, 12, 10983, 2173, 1768, 2934, 16411, 12, 6011, 18, 9853, 2148, 2934, 2892, 12, 4963, 8763, 2148, 1769, 203, 3639, 309, 261, 2629, 18, 2696, 405, 2845, 18, 2722, 17631, 1060, 1768, 597, 12423, 3088, 1283, 480, 374, 13, 288, 203, 5411, 2254, 5034, 4078, 18379, 2173, 9535, 273, 10443, 17631, 1060, 18, 16411, 12, 21, 73, 2138, 2934, 2892, 12, 9953, 3088, 1283, 1769, 203, 5411, 364, 12, 11890, 5034, 640, 1226, 273, 374, 31, 640, 1226, 411, 2845, 18, 1467, 31, 965, 318, 1226, 15329, 203, 2398, 202, 2867, 729, 3178, 273, 729, 1016, 63, 67, 6610, 6362, 318, 1226, 15533, 203, 7734, 309, 12, 1355, 1016, 63, 67, 6610, 6362, 318, 1226, 65, 2 ]
pragma solidity ^ 0.4 .6; /* * * This file is part of Pass DAO. * * The Token Manager smart contract is used for the management of tokens * by a client smart contract (the Dao). Defines the functions to set new funding rules, * create or reward tokens, check token balances, send tokens and send * tokens on behalf of a 3rd party and the corresponding approval process. * */ /// @title Token Manager smart contract of the Pass Decentralized Autonomous Organisation contract PassTokenManagerInterface { struct fundingData { // True if public funding without a main partner bool publicCreation; // The address which sets partners and manages the funding in case of private funding address mainPartner; // The maximum amount (in wei) of the funding uint maxAmountToFund; // The actual funded amount (in wei) uint fundedAmount; // A unix timestamp, denoting the start time of the funding uint startTime; // A unix timestamp, denoting the closing time of the funding uint closingTime; // The price multiplier for a share or a token without considering the inflation rate uint initialPriceMultiplier; // Rate per year in percentage applied to the share or token price uint inflationRate; // Index of the client proposal uint proposalID; } // Address of the creator of the smart contract address public creator; // Address of the Dao address public client; // Address of the recipient; address public recipient; // The token name for display purpose string public name; // The token symbol for display purpose string public symbol; // The quantity of decimals for display purpose uint8 public decimals; // End date of the setup procedure uint public smartContractStartDate; // Total amount of tokens uint256 totalTokenSupply; // Array with all balances mapping(address => uint256) balances; // Array with all allowances mapping(address => mapping(address => uint256)) allowed; // Map of the result (in wei) of fundings mapping(uint => uint) fundedAmount; // Array of token or share holders address[] holders; // Map with the indexes of the holders mapping(address => uint) public holderID; // If true, the shares or tokens can be transfered bool public transferable; // Map of blocked Dao share accounts. Points to the date when the share holder can transfer shares mapping(address => uint) public blockedDeadLine; // Rules for the actual funding and the contractor token price fundingData[2] public FundingRules; /// @return The total supply of shares or tokens function totalSupply() constant external returns(uint256); /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant external returns(uint256 balance); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Quantity of remaining tokens of _owner that _spender is allowed to spend function allowance(address _owner, address _spender) constant external returns(uint256 remaining); /// @param _proposalID The index of the Dao proposal /// @return The result (in wei) of the funding function FundedAmount(uint _proposalID) constant external returns(uint); /// @param _saleDate in case of presale, the date of the presale /// @return the share or token price divisor condidering the sale date and the inflation rate function priceDivisor(uint _saleDate) constant internal returns(uint); /// @return the actual price divisor of a share or token function actualPriceDivisor() constant external returns(uint); /// @return The maximal amount a main partner can fund at this moment /// @param _mainPartner The address of the main parner function fundingMaxAmount(address _mainPartner) constant external returns(uint); /// @return The number of share or token holders function numberOfHolders() constant returns(uint); /// @param _index The index of the holder /// @return the address of the an holder function HolderAddress(uint _index) constant returns(address); // Modifier that allows only the client to manage this account manager modifier onlyClient { if (msg.sender != client) throw; _; } // Modifier that allows only the main partner to manage the actual funding modifier onlyMainPartner { if (msg.sender != FundingRules[0].mainPartner) throw; _; } // Modifier that allows only the contractor propose set the token price or withdraw modifier onlyContractor { if (recipient == 0 || (msg.sender != recipient && msg.sender != creator)) throw; _; } // Modifier for Dao functions modifier onlyDao { if (recipient != 0) throw; _; } /// @dev The constructor function /// @param _creator The address of the creator of the smart contract /// @param _client The address of the client or Dao /// @param _recipient The recipient of this manager /// @param _tokenName The token name for display purpose /// @param _tokenSymbol The token symbol for display purpose /// @param _tokenDecimals The quantity of decimals for display purpose /// @param _transferable True if allows the transfer of tokens //function PassTokenManager( // address _creator, // address _client, // address _recipient, // string _tokenName, // string _tokenSymbol, // uint8 _tokenDecimals, // bool _transferable); /// @notice Function to create initial tokens /// @param _holder The beneficiary of the created tokens /// @param _quantity The quantity of tokens to create function createInitialTokens(address _holder, uint _quantity); /// @notice Function to close the setup procedure of this contract function closeSetup(); /// @notice Function that allow the contractor to propose a token price /// @param _initialPriceMultiplier The initial price multiplier of contractor tokens /// @param _inflationRate If 0, the contractor token price doesn't change during the funding /// @param _closingTime The initial price and inflation rate can be changed after this date function setTokenPriceProposal( uint _initialPriceMultiplier, uint _inflationRate, uint _closingTime ); /// @notice Function to set a funding. Can be private or public /// @param _mainPartner The address of the smart contract to manage a private funding /// @param _publicCreation True if public funding /// @param _initialPriceMultiplier Price multiplier without considering any inflation rate /// @param _maxAmountToFund The maximum amount (in wei) of the funding /// @param _minutesFundingPeriod Period in minutes of the funding /// @param _inflationRate If 0, the token price doesn't change during the funding /// @param _proposalID Index of the client proposal (not mandatory) function setFundingRules( address _mainPartner, bool _publicCreation, uint _initialPriceMultiplier, uint _maxAmountToFund, uint _minutesFundingPeriod, uint _inflationRate, uint _proposalID ) external; /// @dev Internal function to add a new token or share holder /// @param _holder The address of the token or share holder function addHolder(address _holder) internal; /// @dev Internal function for the creation of shares or tokens /// @param _recipient The recipient address of shares or tokens /// @param _amount The funded amount (in wei) /// @param _saleDate In case of presale, the date of the presale /// @return Whether the creation was successful or not function createToken( address _recipient, uint _amount, uint _saleDate ) internal returns(bool success); /// @notice Function used by the main partner to set the start time of the funding /// @param _startTime The unix start date of the funding function setFundingStartTime(uint _startTime) external; /// @notice Function used by the main partner to reward shares or tokens /// @param _recipient The address of the recipient of shares or tokens /// @param _amount The amount (in Wei) to calculate the quantity of shares or tokens to create /// @param _date The unix date to consider for the share or token price calculation /// @return Whether the transfer was successful or not function rewardToken( address _recipient, uint _amount, uint _date ) external; /// @dev Internal function to close the actual funding function closeFunding() internal; /// @notice Function used by the main partner to set the funding fueled function setFundingFueled() external; /// @notice Function to able the transfer of Dao shares or contractor tokens function ableTransfer(); /// @notice Function to disable the transfer of Dao shares function disableTransfer(); /// @notice Function used by the client to block the transfer of shares from and to a share holder /// @param _shareHolder The address of the share holder /// @param _deadLine When the account will be unblocked function blockTransfer(address _shareHolder, uint _deadLine) external; /// @dev Internal function to send `_value` token to `_to` from `_From` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The quantity of shares or tokens to be transferred /// @return Whether the function was successful or not function transferFromTo( address _from, address _to, uint256 _value ) internal returns(bool success); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The quantity of shares or tokens to be transferred /// @return Whether the function was successful or not function transfer(address _to, uint256 _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 quantity of shares or tokens to be transferred function transferFrom( address _from, address _to, uint256 _value ) returns(bool success); /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on its behalf /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns(bool success); event TokenPriceProposalSet(uint InitialPriceMultiplier, uint InflationRate, uint ClosingTime); event holderAdded(uint Index, address Holder); event TokensCreated(address indexed Sender, address indexed TokenHolder, uint Quantity); event FundingRulesSet(address indexed MainPartner, uint indexed FundingProposalId, uint indexed StartTime, uint ClosingTime); event FundingFueled(uint indexed FundingProposalID, uint FundedAmount); event TransferAble(); event TransferDisable(); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract PassTokenManager is PassTokenManagerInterface { function totalSupply() constant external returns(uint256) { return totalTokenSupply; } function balanceOf(address _owner) constant external returns(uint256 balance) { return balances[_owner]; } function allowance(address _owner, address _spender) constant external returns(uint256 remaining) { return allowed[_owner][_spender]; } function FundedAmount(uint _proposalID) constant external returns(uint) { return fundedAmount[_proposalID]; } function priceDivisor(uint _saleDate) constant internal returns(uint) { uint _date = _saleDate; if (_saleDate > FundingRules[0].closingTime) _date = FundingRules[0].closingTime; if (_saleDate < FundingRules[0].startTime) _date = FundingRules[0].startTime; return 100 + 100 * FundingRules[0].inflationRate * (_date - FundingRules[0].startTime) / (100 * 365 days); } function actualPriceDivisor() constant external returns(uint) { return priceDivisor(now); } function fundingMaxAmount(address _mainPartner) constant external returns(uint) { if (now > FundingRules[0].closingTime || now < FundingRules[0].startTime || _mainPartner != FundingRules[0].mainPartner) { return 0; } else { return FundingRules[0].maxAmountToFund; } } function numberOfHolders() constant returns(uint) { return holders.length - 1; } function HolderAddress(uint _index) constant returns(address) { return holders[_index]; } function PassTokenManager( address _creator, address _client, address _recipient, string _tokenName, string _tokenSymbol, uint8 _tokenDecimals, bool _transferable) { if (_creator == 0 || _client == 0 || _client == _recipient || _client == address(this) || _recipient == address(this)) throw; creator = _creator; client = _client; recipient = _recipient; holders.length = 1; name = _tokenName; symbol = _tokenSymbol; decimals = _tokenDecimals; if (_transferable) { transferable = true; TransferAble(); } else { transferable = false; TransferDisable(); } } function createInitialTokens( address _holder, uint _quantity ) { if (smartContractStartDate != 0) throw; if (_quantity > 0 && balances[_holder] == 0) { addHolder(_holder); balances[_holder] = _quantity; totalTokenSupply += _quantity; TokensCreated(msg.sender, _holder, _quantity); } } function closeSetup() { smartContractStartDate = now; } function setTokenPriceProposal( uint _initialPriceMultiplier, uint _inflationRate, uint _closingTime ) onlyContractor { if (_closingTime < now || now < FundingRules[1].closingTime) throw; FundingRules[1].initialPriceMultiplier = _initialPriceMultiplier; FundingRules[1].inflationRate = _inflationRate; FundingRules[1].startTime = now; FundingRules[1].closingTime = _closingTime; TokenPriceProposalSet(_initialPriceMultiplier, _inflationRate, _closingTime); } function setFundingRules( address _mainPartner, bool _publicCreation, uint _initialPriceMultiplier, uint _maxAmountToFund, uint _minutesFundingPeriod, uint _inflationRate, uint _proposalID ) external onlyClient { if (now < FundingRules[0].closingTime || _mainPartner == address(this) || _mainPartner == client || (!_publicCreation && _mainPartner == 0) || (_publicCreation && _mainPartner != 0) || (recipient == 0 && _initialPriceMultiplier == 0) || (recipient != 0 && (FundingRules[1].initialPriceMultiplier == 0 || _inflationRate < FundingRules[1].inflationRate || now < FundingRules[1].startTime || FundingRules[1].closingTime < now + (_minutesFundingPeriod * 1 minutes))) || _maxAmountToFund == 0 || _minutesFundingPeriod == 0) throw; FundingRules[0].startTime = now; FundingRules[0].closingTime = now + _minutesFundingPeriod * 1 minutes; FundingRules[0].mainPartner = _mainPartner; FundingRules[0].publicCreation = _publicCreation; if (recipient == 0) FundingRules[0].initialPriceMultiplier = _initialPriceMultiplier; else FundingRules[0].initialPriceMultiplier = FundingRules[1].initialPriceMultiplier; if (recipient == 0) FundingRules[0].inflationRate = _inflationRate; else FundingRules[0].inflationRate = FundingRules[1].inflationRate; FundingRules[0].fundedAmount = 0; FundingRules[0].maxAmountToFund = _maxAmountToFund; FundingRules[0].proposalID = _proposalID; FundingRulesSet(_mainPartner, _proposalID, FundingRules[0].startTime, FundingRules[0].closingTime); } function addHolder(address _holder) internal { if (holderID[_holder] == 0) { uint _holderID = holders.length++; holders[_holderID] = _holder; holderID[_holder] = _holderID; holderAdded(_holderID, _holder); } } function createToken( address _recipient, uint _amount, uint _saleDate ) internal returns(bool success) { if (now > FundingRules[0].closingTime || now < FundingRules[0].startTime || _saleDate > FundingRules[0].closingTime || _saleDate < FundingRules[0].startTime || FundingRules[0].fundedAmount + _amount > FundingRules[0].maxAmountToFund) return; uint _a = _amount * FundingRules[0].initialPriceMultiplier; uint _multiplier = 100 * _a; uint _quantity = _multiplier / priceDivisor(_saleDate); if (_a / _amount != FundingRules[0].initialPriceMultiplier || _multiplier / 100 != _a || totalTokenSupply + _quantity <= totalTokenSupply || totalTokenSupply + _quantity <= _quantity) return; addHolder(_recipient); balances[_recipient] += _quantity; totalTokenSupply += _quantity; FundingRules[0].fundedAmount += _amount; TokensCreated(msg.sender, _recipient, _quantity); if (FundingRules[0].fundedAmount == FundingRules[0].maxAmountToFund) closeFunding(); return true; } function setFundingStartTime(uint _startTime) external onlyMainPartner { if (now > FundingRules[0].closingTime) throw; FundingRules[0].startTime = _startTime; } function rewardToken( address _recipient, uint _amount, uint _date ) external onlyMainPartner { uint _saleDate; if (_date == 0) _saleDate = now; else _saleDate = _date; if (!createToken(_recipient, _amount, _saleDate)) throw; } function closeFunding() internal { if (recipient == 0) fundedAmount[FundingRules[0].proposalID] = FundingRules[0].fundedAmount; FundingRules[0].closingTime = now; } function setFundingFueled() external onlyMainPartner { if (now > FundingRules[0].closingTime) throw; closeFunding(); if (recipient == 0) FundingFueled(FundingRules[0].proposalID, FundingRules[0].fundedAmount); } function ableTransfer() onlyClient { if (!transferable) { transferable = true; TransferAble(); } } function disableTransfer() onlyClient { if (transferable) { transferable = false; TransferDisable(); } } function blockTransfer(address _shareHolder, uint _deadLine) external onlyClient onlyDao { if (_deadLine > blockedDeadLine[_shareHolder]) { blockedDeadLine[_shareHolder] = _deadLine; } } function transferFromTo( address _from, address _to, uint256 _value ) internal returns(bool success) { if (transferable && now > blockedDeadLine[_from] && now > blockedDeadLine[_to] && _to != address(this) && balances[_from] >= _value && balances[_to] + _value > balances[_to] && balances[_to] + _value >= _value) { balances[_from] -= _value; balances[_to] += _value; Transfer(_from, _to, _value); addHolder(_to); return true; } else { return false; } } function transfer(address _to, uint256 _value) returns(bool success) { if (!transferFromTo(msg.sender, _to, _value)) throw; return true; } function transferFrom( address _from, address _to, uint256 _value ) returns(bool success) { if (allowed[_from][msg.sender] < _value || !transferFromTo(_from, _to, _value)) throw; allowed[_from][msg.sender] -= _value; return true; } function approve(address _spender, uint256 _value) returns(bool success) { allowed[msg.sender][_spender] = _value; return true; } } pragma solidity ^ 0.4 .6; /* * * This file is part of Pass DAO. * * The Manager smart contract is used for the management of accounts and tokens. * Allows to receive or withdraw ethers and to buy Dao shares. * The contract derives to the Token Manager smart contract for the management of tokens. * * Recipient is 0 for the Dao account manager and the address of * contractor's recipient for the contractors's mahagers. * */ /// @title Manager smart contract of the Pass Decentralized Autonomous Organisation contract PassManagerInterface is PassTokenManagerInterface { struct proposal { // Amount (in wei) of the proposal uint amount; // A description of the proposal string description; // The hash of the proposal's document bytes32 hashOfTheDocument; // A unix timestamp, denoting the date when the proposal was created uint dateOfProposal; // The index of the last approved client proposal uint lastClientProposalID; // The sum amount (in wei) ordered for this proposal uint orderAmount; // A unix timestamp, denoting the date of the last order for the approved proposal uint dateOfOrder; } // Proposals to work for the client proposal[] public proposals; // The address of the last Manager before cloning address public clonedFrom; /// @dev The constructor function /// @param _client The address of the Dao /// @param _recipient The address of the recipient. 0 for the Dao /// @param _clonedFrom The address of the last Manager before cloning /// @param _tokenName The token name for display purpose /// @param _tokenSymbol The token symbol for display purpose /// @param _tokenDecimals The quantity of decimals for display purpose /// @param _transferable True if allows the transfer of tokens //function PassManager( // address _client, // address _recipient, // address _clonedFrom, // string _tokenName, // string _tokenSymbol, // uint8 _tokenDecimals, // bool _transferable //) PassTokenManager( // msg.sender, // _client, // _recipient, // _tokenName, // _tokenSymbol, // _tokenDecimals, // _transferable); /// @notice Function to allow sending fees in wei to the Dao function receiveFees() payable; /// @notice Function to allow the contractor making a deposit in wei function receiveDeposit() payable; /// @notice Function to clone a proposal from another manager contract /// @param _amount Amount (in wei) of the proposal /// @param _description A description of the proposal /// @param _hashOfTheDocument The hash of the proposal's document /// @param _dateOfProposal A unix timestamp, denoting the date when the proposal was created /// @param _lastClientProposalID The index of the last approved client proposal /// @param _orderAmount The sum amount (in wei) ordered for this proposal /// @param _dateOfOrder A unix timestamp, denoting the date of the last order for the approved proposal function cloneProposal( uint _amount, string _description, bytes32 _hashOfTheDocument, uint _dateOfProposal, uint _lastClientProposalID, uint _orderAmount, uint _dateOfOrder); /// @notice Function to clone tokens from a manager /// @param _from The index of the first holder /// @param _to The index of the last holder function cloneTokens( uint _from, uint _to); /// @notice Function to update the client address function updateClient(address _newClient); /// @notice Function to update the recipent address /// @param _newRecipient The adress of the recipient function updateRecipient(address _newRecipient); /// @notice Function to buy Dao shares according to the funding rules /// with `msg.sender` as the beneficiary function buyShares() payable; /// @notice Function to buy Dao shares according to the funding rules /// @param _recipient The beneficiary of the created shares function buySharesFor(address _recipient) payable; /// @notice Function to make a proposal to work for the client /// @param _amount The amount (in wei) of the proposal /// @param _description String describing the proposal /// @param _hashOfTheDocument The hash of the proposal document /// @return The index of the contractor proposal function newProposal( uint _amount, string _description, bytes32 _hashOfTheDocument ) returns(uint); /// @notice Function used by the client to order according to the contractor proposal /// @param _clientProposalID The index of the last approved client proposal /// @param _proposalID The index of the contractor proposal /// @param _amount The amount (in wei) of the order /// @return Whether the order was made or not function order( uint _clientProposalID, uint _proposalID, uint _amount ) external returns(bool); /// @notice Function used by the client to send ethers from the Dao manager /// @param _recipient The address to send to /// @param _amount The amount (in wei) to send /// @return Whether the transfer was successful or not function sendTo( address _recipient, uint _amount ) external returns(bool); /// @notice Function to allow contractors to withdraw ethers /// @param _amount The amount (in wei) to withdraw function withdraw(uint _amount); /// @return The number of Dao rules proposals function numberOfProposals() constant returns(uint); event FeesReceived(address indexed From, uint Amount); event DepositReceived(address indexed From, uint Amount); event ProposalCloned(uint indexed LastClientProposalID, uint indexed ProposalID, uint Amount, string Description, bytes32 HashOfTheDocument); event ClientUpdated(address LastClient, address NewClient); event RecipientUpdated(address LastRecipient, address NewRecipient); event ProposalAdded(uint indexed ProposalID, uint Amount, string Description, bytes32 HashOfTheDocument); event Order(uint indexed clientProposalID, uint indexed ProposalID, uint Amount); event Withdawal(address indexed Recipient, uint Amount); } contract PassManager is PassManagerInterface, PassTokenManager { function PassManager( address _client, address _recipient, address _clonedFrom, string _tokenName, string _tokenSymbol, uint8 _tokenDecimals, bool _transferable ) PassTokenManager( msg.sender, _client, _recipient, _tokenName, _tokenSymbol, _tokenDecimals, _transferable ) { clonedFrom = _clonedFrom; proposals.length = 1; } function receiveFees() payable onlyDao { FeesReceived(msg.sender, msg.value); } function receiveDeposit() payable onlyContractor { DepositReceived(msg.sender, msg.value); } function cloneProposal( uint _amount, string _description, bytes32 _hashOfTheDocument, uint _dateOfProposal, uint _lastClientProposalID, uint _orderAmount, uint _dateOfOrder ) { if (smartContractStartDate != 0 || recipient == 0) throw; uint _proposalID = proposals.length++; proposal c = proposals[_proposalID]; c.amount = _amount; c.description = _description; c.hashOfTheDocument = _hashOfTheDocument; c.dateOfProposal = _dateOfProposal; c.lastClientProposalID = _lastClientProposalID; c.orderAmount = _orderAmount; c.dateOfOrder = _dateOfOrder; ProposalCloned(_lastClientProposalID, _proposalID, c.amount, c.description, c.hashOfTheDocument); } function cloneTokens( uint _from, uint _to) { if (smartContractStartDate != 0) throw; PassManager _clonedFrom = PassManager(_clonedFrom); if (_from < 1 || _to > _clonedFrom.numberOfHolders()) throw; address _holder; for (uint i = _from; i <= _to; i++) { _holder = _clonedFrom.HolderAddress(i); if (balances[_holder] == 0) { createInitialTokens(_holder, _clonedFrom.balanceOf(_holder)); } } } function updateClient(address _newClient) onlyClient { if (_newClient == 0 || _newClient == recipient) throw; ClientUpdated(client, _newClient); client = _newClient; } function updateRecipient(address _newRecipient) onlyContractor { if (_newRecipient == 0 || _newRecipient == client) throw; RecipientUpdated(recipient, _newRecipient); recipient = _newRecipient; } function buyShares() payable { buySharesFor(msg.sender); } function buySharesFor(address _recipient) payable onlyDao { if (!FundingRules[0].publicCreation || !createToken(_recipient, msg.value, now)) throw; } function newProposal( uint _amount, string _description, bytes32 _hashOfTheDocument ) onlyContractor returns(uint) { uint _proposalID = proposals.length++; proposal c = proposals[_proposalID]; c.amount = _amount; c.description = _description; c.hashOfTheDocument = _hashOfTheDocument; c.dateOfProposal = now; ProposalAdded(_proposalID, c.amount, c.description, c.hashOfTheDocument); return _proposalID; } function order( uint _clientProposalID, uint _proposalID, uint _orderAmount ) external onlyClient returns(bool) { proposal c = proposals[_proposalID]; uint _sum = c.orderAmount + _orderAmount; if (_sum > c.amount || _sum < c.orderAmount || _sum < _orderAmount) return; c.lastClientProposalID = _clientProposalID; c.orderAmount = _sum; c.dateOfOrder = now; Order(_clientProposalID, _proposalID, _orderAmount); return true; } function sendTo( address _recipient, uint _amount ) external onlyClient onlyDao returns(bool) { if (_recipient.send(_amount)) return true; else return false; } function withdraw(uint _amount) onlyContractor { if (!recipient.send(_amount)) throw; Withdawal(recipient, _amount); } function numberOfProposals() constant returns(uint) { return proposals.length - 1; } } pragma solidity ^ 0.4 .6; /* This file is part of Pass DAO. Pass DAO is free software: you can redistribute it and/or modify it under the terms of the GNU lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Pass DAO 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 lesser General Public License for more details. You should have received a copy of the GNU lesser General Public License along with Pass DAO. If not, see <http://www.gnu.org/licenses></http:>. */ /* Smart contract for a Decentralized Autonomous Organization (DAO) to automate organizational governance and decision-making. */ /// @title Pass Decentralized Autonomous Organisation contract PassDaoInterface { struct BoardMeeting { // Address of the creator of the board meeting for a proposal address creator; // Index to identify the proposal to pay a contractor or fund the Dao uint proposalID; // Index to identify the proposal to update the Dao rules uint daoRulesProposalID; // unix timestamp, denoting the end of the set period of a proposal before the board meeting uint setDeadline; // Fees (in wei) paid by the creator of the board meeting uint fees; // Total of fees (in wei) rewarded to the voters or to the Dao account manager for the balance uint totalRewardedAmount; // A unix timestamp, denoting the end of the voting period uint votingDeadline; // True if the proposal's votes have yet to be counted, otherwise False bool open; // A unix timestamp, denoting the date of the execution of the approved proposal uint dateOfExecution; // Number of shares in favor of the proposal uint yea; // Number of shares opposed to the proposal uint nay; // mapping to indicate if a shareholder has voted mapping(address => bool) hasVoted; } struct Contractor { // The address of the contractor manager smart contract address contractorManager; // The date of the first order for the contractor uint creationDate; } struct Proposal { // Index to identify the board meeting of the proposal uint boardMeetingID; // The contractor manager smart contract PassManager contractorManager; // The index of the contractor proposal uint contractorProposalID; // The amount (in wei) of the proposal uint amount; // True if the proposal foresees a contractor token creation bool tokenCreation; // True if public funding without a main partner bool publicShareCreation; // The address which sets partners and manages the funding in case of private funding address mainPartner; // The initial price multiplier of Dao shares at the beginning of the funding uint initialSharePriceMultiplier; // The inflation rate to calculate the actual contractor share price uint inflationRate; // A unix timestamp, denoting the start time of the funding uint minutesFundingPeriod; // True if the proposal is closed bool open; } struct Rules { // Index to identify the board meeting that decides to apply or not the Dao rules uint boardMeetingID; // The quorum needed for each proposal is calculated by totalSupply / minQuorumDivisor uint minQuorumDivisor; // Minimum fees (in wei) to create a proposal uint minBoardMeetingFees; // Period in minutes to consider or set a proposal before the voting procedure uint minutesSetProposalPeriod; // The minimum debate period in minutes that a generic proposal can have uint minMinutesDebatePeriod; // The inflation rate to calculate the reward of fees to voters during a board meeting uint feesRewardInflationRate; // True if the dao rules allow the transfer of shares bool transferable; // Address of the effective Dao smart contract (can be different of this Dao in case of upgrade) address dao; } // The creator of the Dao address public creator; // The name of the project string public projectName; // The address of the last Dao before upgrade (not mandatory) address public lastDao; // End date of the setup procedure uint public smartContractStartDate; // The Dao manager smart contract PassManager public daoManager; // The minimum periods in minutes uint public minMinutesPeriods; // The maximum period in minutes for proposals (set+debate) uint public maxMinutesProposalPeriod; // The maximum funding period in minutes for funding proposals uint public maxMinutesFundingPeriod; // The maximum inflation rate for share price or rewards to voters uint public maxInflationRate; // Map to allow the share holders to withdraw board meeting fees mapping(address => uint) pendingFees; // Board meetings to vote for or against a proposal BoardMeeting[] public BoardMeetings; // Contractors of the Dao Contractor[] public Contractors; // Map with the indexes of the contractors mapping(address => uint) contractorID; // Proposals to pay a contractor or fund the Dao Proposal[] public Proposals; // Proposals to update the Dao rules Rules[] public DaoRulesProposals; // The current Dao rules Rules public DaoRules; /// @dev The constructor function /// @param _projectName The name of the Dao /// @param _lastDao The address of the last Dao before upgrade (not mandatory) //function PassDao( // string _projectName, // address _lastDao); /// @dev Internal function to add a new contractor /// @param _contractorManager The address of the contractor manager /// @param _creationDate The date of the first order function addContractor(address _contractorManager, uint _creationDate) internal; /// @dev Function to clone a contractor from the last Dao in case of upgrade /// @param _contractorManager The address of the contractor manager /// @param _creationDate The date of the first order function cloneContractor(address _contractorManager, uint _creationDate); /// @notice Function to update the client of the contractor managers in case of upgrade /// @param _from The index of the first contractor manager to update /// @param _to The index of the last contractor manager to update function updateClientOfContractorManagers( uint _from, uint _to); /// @dev Function to initialize the Dao /// @param _daoManager Address of the Dao manager smart contract /// @param _maxInflationRate The maximum inflation rate for contractor and funding proposals /// @param _minMinutesPeriods The minimum periods in minutes /// @param _maxMinutesFundingPeriod The maximum funding period in minutes for funding proposals /// @param _maxMinutesProposalPeriod The maximum period in minutes for proposals (set+debate) /// @param _minQuorumDivisor The initial minimum quorum divisor for the proposals /// @param _minBoardMeetingFees The amount (in wei) to make a proposal and ask for a board meeting /// @param _minutesSetProposalPeriod The minimum period in minutes before a board meeting /// @param _minMinutesDebatePeriod The minimum period in minutes of the board meetings /// @param _feesRewardInflationRate The inflation rate to calculate the reward of fees to voters during a board meeting function initDao( address _daoManager, uint _maxInflationRate, uint _minMinutesPeriods, uint _maxMinutesFundingPeriod, uint _maxMinutesProposalPeriod, uint _minQuorumDivisor, uint _minBoardMeetingFees, uint _minutesSetProposalPeriod, uint _minMinutesDebatePeriod, uint _feesRewardInflationRate ); /// @dev Internal function to create a board meeting /// @param _proposalID The index of the proposal if for a contractor or for a funding /// @param _daoRulesProposalID The index of the proposal if Dao rules /// @param _minutesDebatingPeriod The duration in minutes of the meeting /// @return the index of the board meeting function newBoardMeeting( uint _proposalID, uint _daoRulesProposalID, uint _minutesDebatingPeriod ) internal returns(uint); /// @notice Function to make a proposal to pay a contractor or fund the Dao /// @param _contractorManager Address of the contractor manager smart contract /// @param _contractorProposalID Index of the contractor proposal of the contractor manager /// @param _amount The amount (in wei) of the proposal /// @param _tokenCreation True if the proposal foresees a contractor token creation /// @param _publicShareCreation True if public funding without a main partner /// @param _mainPartner The address which sets partners and manage the funding /// in case of private funding (not mandatory) /// @param _initialSharePriceMultiplier The initial price multiplier of shares /// @param _inflationRate If 0, the share price doesn't change during the funding (not mandatory) /// @param _minutesFundingPeriod Period in minutes of the funding /// @param _minutesDebatingPeriod Period in minutes of the board meeting to vote on the proposal /// @return The index of the proposal function newProposal( address _contractorManager, uint _contractorProposalID, uint _amount, bool _publicShareCreation, bool _tokenCreation, address _mainPartner, uint _initialSharePriceMultiplier, uint _inflationRate, uint _minutesFundingPeriod, uint _minutesDebatingPeriod ) payable returns(uint); /// @notice Function to make a proposal to change the Dao rules /// @param _minQuorumDivisor If 5, the minimum quorum is 20% /// @param _minBoardMeetingFees The amount (in wei) to make a proposal and ask for a board meeting /// @param _minutesSetProposalPeriod Minimum period in minutes before a board meeting /// @param _minMinutesDebatePeriod The minimum period in minutes of the board meetings /// @param _feesRewardInflationRate The inflation rate to calculate the reward of fees to voters during a board meeting /// @param _transferable True if the proposal foresees to allow the transfer of Dao shares /// @param _dao Address of a new Dao smart contract in case of upgrade (not mandatory) /// @param _minutesDebatingPeriod Period in minutes of the board meeting to vote on the proposal function newDaoRulesProposal( uint _minQuorumDivisor, uint _minBoardMeetingFees, uint _minutesSetProposalPeriod, uint _minMinutesDebatePeriod, uint _feesRewardInflationRate, bool _transferable, address _dao, uint _minutesDebatingPeriod ) payable returns(uint); /// @notice Function to vote during a board meeting /// @param _boardMeetingID The index of the board meeting /// @param _supportsProposal True if the proposal is supported function vote( uint _boardMeetingID, bool _supportsProposal ); /// @notice Function to execute a board meeting decision and close the board meeting /// @param _boardMeetingID The index of the board meeting /// @return Whether the proposal was executed or not function executeDecision(uint _boardMeetingID) returns(bool); /// @notice Function to order a contractor proposal /// @param _proposalID The index of the proposal /// @return Whether the proposal was ordered and the proposal amount sent or not function orderContractorProposal(uint _proposalID) returns(bool); /// @notice Function to withdraw the rewarded board meeting fees /// @return Whether the withdraw was successful or not function withdrawBoardMeetingFees() returns(bool); /// @param _shareHolder Address of the shareholder /// @return The amount in wei the shareholder can withdraw function PendingFees(address _shareHolder) constant returns(uint); /// @return The minimum quorum for proposals to pass function minQuorum() constant returns(uint); /// @return The number of contractors function numberOfContractors() constant returns(uint); /// @return The number of board meetings (or proposals) function numberOfBoardMeetings() constant returns(uint); event ContractorProposalAdded(uint indexed ProposalID, uint boardMeetingID, address indexed ContractorManager, uint indexed ContractorProposalID, uint amount); event FundingProposalAdded(uint indexed ProposalID, uint boardMeetingID, bool indexed LinkedToContractorProposal, uint amount, address MainPartner, uint InitialSharePriceMultiplier, uint InflationRate, uint MinutesFundingPeriod); event DaoRulesProposalAdded(uint indexed DaoRulesProposalID, uint boardMeetingID, uint MinQuorumDivisor, uint MinBoardMeetingFees, uint MinutesSetProposalPeriod, uint MinMinutesDebatePeriod, uint FeesRewardInflationRate, bool Transferable, address NewDao); event Voted(uint indexed boardMeetingID, uint ProposalID, uint DaoRulesProposalID, bool position, address indexed voter); event ProposalClosed(uint indexed ProposalID, uint indexed DaoRulesProposalID, uint boardMeetingID, uint FeesGivenBack, bool ProposalExecuted, uint BalanceSentToDaoManager); event SentToContractor(uint indexed ProposalID, uint indexed ContractorProposalID, address indexed ContractorManagerAddress, uint AmountSent); event Withdrawal(address indexed Recipient, uint Amount); event DaoUpgraded(address NewDao); } contract PassDao is PassDaoInterface { function PassDao( string _projectName, address _lastDao) { lastDao = _lastDao; creator = msg.sender; projectName = _projectName; Contractors.length = 1; BoardMeetings.length = 1; Proposals.length = 1; DaoRulesProposals.length = 1; } function addContractor(address _contractorManager, uint _creationDate) internal { if (contractorID[_contractorManager] == 0) { uint _contractorID = Contractors.length++; Contractor c = Contractors[_contractorID]; contractorID[_contractorManager] = _contractorID; c.contractorManager = _contractorManager; c.creationDate = _creationDate; } } function cloneContractor(address _contractorManager, uint _creationDate) { if (DaoRules.minQuorumDivisor != 0) throw; addContractor(_contractorManager, _creationDate); } function initDao( address _daoManager, uint _maxInflationRate, uint _minMinutesPeriods, uint _maxMinutesFundingPeriod, uint _maxMinutesProposalPeriod, uint _minQuorumDivisor, uint _minBoardMeetingFees, uint _minutesSetProposalPeriod, uint _minMinutesDebatePeriod, uint _feesRewardInflationRate ) { if (smartContractStartDate != 0) throw; maxInflationRate = _maxInflationRate; minMinutesPeriods = _minMinutesPeriods; maxMinutesFundingPeriod = _maxMinutesFundingPeriod; maxMinutesProposalPeriod = _maxMinutesProposalPeriod; DaoRules.minQuorumDivisor = _minQuorumDivisor; DaoRules.minBoardMeetingFees = _minBoardMeetingFees; DaoRules.minutesSetProposalPeriod = _minutesSetProposalPeriod; DaoRules.minMinutesDebatePeriod = _minMinutesDebatePeriod; DaoRules.feesRewardInflationRate = _feesRewardInflationRate; daoManager = PassManager(_daoManager); smartContractStartDate = now; } function updateClientOfContractorManagers( uint _from, uint _to) { if (_from < 1 || _to > Contractors.length - 1) throw; for (uint i = _from; i <= _to; i++) { PassManager(Contractors[i].contractorManager).updateClient(DaoRules.dao); } } function newBoardMeeting( uint _proposalID, uint _daoRulesProposalID, uint _minutesDebatingPeriod ) internal returns(uint) { if (msg.value < DaoRules.minBoardMeetingFees || DaoRules.minutesSetProposalPeriod + _minutesDebatingPeriod > maxMinutesProposalPeriod || now + ((DaoRules.minutesSetProposalPeriod + _minutesDebatingPeriod) * 1 minutes) < now || _minutesDebatingPeriod < DaoRules.minMinutesDebatePeriod || msg.sender == address(this)) throw; uint _boardMeetingID = BoardMeetings.length++; BoardMeeting b = BoardMeetings[_boardMeetingID]; b.creator = msg.sender; b.proposalID = _proposalID; b.daoRulesProposalID = _daoRulesProposalID; b.fees = msg.value; b.setDeadline = now + (DaoRules.minutesSetProposalPeriod * 1 minutes); b.votingDeadline = b.setDeadline + (_minutesDebatingPeriod * 1 minutes); b.open = true; return _boardMeetingID; } function newProposal( address _contractorManager, uint _contractorProposalID, uint _amount, bool _tokenCreation, bool _publicShareCreation, address _mainPartner, uint _initialSharePriceMultiplier, uint _inflationRate, uint _minutesFundingPeriod, uint _minutesDebatingPeriod ) payable returns(uint) { if ((_contractorManager != 0 && _contractorProposalID == 0) || (_contractorManager == 0 && (_initialSharePriceMultiplier == 0 || _contractorProposalID != 0) || (_tokenCreation && _publicShareCreation) || (_initialSharePriceMultiplier != 0 && (_minutesFundingPeriod < minMinutesPeriods || _inflationRate > maxInflationRate || _minutesFundingPeriod > maxMinutesFundingPeriod)))) throw; uint _proposalID = Proposals.length++; Proposal p = Proposals[_proposalID]; p.contractorManager = PassManager(_contractorManager); p.contractorProposalID = _contractorProposalID; p.amount = _amount; p.tokenCreation = _tokenCreation; p.publicShareCreation = _publicShareCreation; p.mainPartner = _mainPartner; p.initialSharePriceMultiplier = _initialSharePriceMultiplier; p.inflationRate = _inflationRate; p.minutesFundingPeriod = _minutesFundingPeriod; p.boardMeetingID = newBoardMeeting(_proposalID, 0, _minutesDebatingPeriod); p.open = true; if (_contractorProposalID != 0) { ContractorProposalAdded(_proposalID, p.boardMeetingID, p.contractorManager, p.contractorProposalID, p.amount); if (_initialSharePriceMultiplier != 0) { FundingProposalAdded(_proposalID, p.boardMeetingID, true, p.amount, p.mainPartner, p.initialSharePriceMultiplier, _inflationRate, _minutesFundingPeriod); } } else if (_initialSharePriceMultiplier != 0) { FundingProposalAdded(_proposalID, p.boardMeetingID, false, p.amount, p.mainPartner, p.initialSharePriceMultiplier, _inflationRate, _minutesFundingPeriod); } return _proposalID; } function newDaoRulesProposal( uint _minQuorumDivisor, uint _minBoardMeetingFees, uint _minutesSetProposalPeriod, uint _minMinutesDebatePeriod, uint _feesRewardInflationRate, bool _transferable, address _newDao, uint _minutesDebatingPeriod ) payable returns(uint) { if (_minQuorumDivisor <= 1 || _minQuorumDivisor > 10 || _minutesSetProposalPeriod < minMinutesPeriods || _minMinutesDebatePeriod < minMinutesPeriods || _minutesSetProposalPeriod + _minMinutesDebatePeriod > maxMinutesProposalPeriod || _feesRewardInflationRate > maxInflationRate) throw; uint _DaoRulesProposalID = DaoRulesProposals.length++; Rules r = DaoRulesProposals[_DaoRulesProposalID]; r.minQuorumDivisor = _minQuorumDivisor; r.minBoardMeetingFees = _minBoardMeetingFees; r.minutesSetProposalPeriod = _minutesSetProposalPeriod; r.minMinutesDebatePeriod = _minMinutesDebatePeriod; r.feesRewardInflationRate = _feesRewardInflationRate; r.transferable = _transferable; r.dao = _newDao; r.boardMeetingID = newBoardMeeting(0, _DaoRulesProposalID, _minutesDebatingPeriod); DaoRulesProposalAdded(_DaoRulesProposalID, r.boardMeetingID, _minQuorumDivisor, _minBoardMeetingFees, _minutesSetProposalPeriod, _minMinutesDebatePeriod, _feesRewardInflationRate, _transferable, _newDao); return _DaoRulesProposalID; } function vote( uint _boardMeetingID, bool _supportsProposal ) { BoardMeeting b = BoardMeetings[_boardMeetingID]; if (b.hasVoted[msg.sender] || now < b.setDeadline || now > b.votingDeadline) throw; uint _balance = uint(daoManager.balanceOf(msg.sender)); if (_balance == 0) throw; b.hasVoted[msg.sender] = true; if (_supportsProposal) b.yea += _balance; else b.nay += _balance; if (b.fees > 0 && b.proposalID != 0 && Proposals[b.proposalID].contractorProposalID != 0) { uint _a = 100 * b.fees; if ((_a / 100 != b.fees) || ((_a * _balance) / _a != _balance)) throw; uint _multiplier = (_a * _balance) / uint(daoManager.totalSupply()); uint _divisor = 100 + 100 * DaoRules.feesRewardInflationRate * (now - b.setDeadline) / (100 * 365 days); uint _rewardedamount = _multiplier / _divisor; if (b.totalRewardedAmount + _rewardedamount > b.fees) _rewardedamount = b.fees - b.totalRewardedAmount; b.totalRewardedAmount += _rewardedamount; pendingFees[msg.sender] += _rewardedamount; } Voted(_boardMeetingID, b.proposalID, b.daoRulesProposalID, _supportsProposal, msg.sender); daoManager.blockTransfer(msg.sender, b.votingDeadline); } function executeDecision(uint _boardMeetingID) returns(bool) { BoardMeeting b = BoardMeetings[_boardMeetingID]; Proposal p = Proposals[b.proposalID]; if (now < b.votingDeadline || !b.open) throw; b.open = false; if (p.contractorProposalID == 0) p.open = false; uint _fees; uint _minQuorum = minQuorum(); if (b.fees > 0 && (b.proposalID == 0 || p.contractorProposalID == 0) && b.yea + b.nay >= _minQuorum) { _fees = b.fees; b.fees = 0; pendingFees[b.creator] += _fees; } uint _balance = b.fees - b.totalRewardedAmount; if (_balance > 0) { if (!daoManager.send(_balance)) throw; } if (b.yea + b.nay < _minQuorum || b.yea <= b.nay) { p.open = false; ProposalClosed(b.proposalID, b.daoRulesProposalID, _boardMeetingID, _fees, false, _balance); return; } b.dateOfExecution = now; if (b.proposalID != 0) { if (p.initialSharePriceMultiplier != 0) { daoManager.setFundingRules(p.mainPartner, p.publicShareCreation, p.initialSharePriceMultiplier, p.amount, p.minutesFundingPeriod, p.inflationRate, b.proposalID); if (p.contractorProposalID != 0 && p.tokenCreation) { p.contractorManager.setFundingRules(p.mainPartner, p.publicShareCreation, 0, p.amount, p.minutesFundingPeriod, maxInflationRate, b.proposalID); } } } else { Rules r = DaoRulesProposals[b.daoRulesProposalID]; DaoRules.boardMeetingID = r.boardMeetingID; DaoRules.minQuorumDivisor = r.minQuorumDivisor; DaoRules.minMinutesDebatePeriod = r.minMinutesDebatePeriod; DaoRules.minBoardMeetingFees = r.minBoardMeetingFees; DaoRules.minutesSetProposalPeriod = r.minutesSetProposalPeriod; DaoRules.feesRewardInflationRate = r.feesRewardInflationRate; DaoRules.transferable = r.transferable; if (r.transferable) daoManager.ableTransfer(); else daoManager.disableTransfer(); if ((r.dao != 0) && (r.dao != address(this))) { DaoRules.dao = r.dao; daoManager.updateClient(r.dao); DaoUpgraded(r.dao); } } ProposalClosed(b.proposalID, b.daoRulesProposalID, _boardMeetingID, _fees, true, _balance); return true; } function orderContractorProposal(uint _proposalID) returns(bool) { Proposal p = Proposals[_proposalID]; BoardMeeting b = BoardMeetings[p.boardMeetingID]; if (b.open || !p.open) throw; uint _amount = p.amount; if (p.initialSharePriceMultiplier != 0) { _amount = daoManager.FundedAmount(_proposalID); if (_amount == 0 && now < b.dateOfExecution + (p.minutesFundingPeriod * 1 minutes)) return; } p.open = false; if (_amount == 0 || !p.contractorManager.order(_proposalID, p.contractorProposalID, _amount)) return; if (!daoManager.sendTo(p.contractorManager, _amount)) throw; SentToContractor(_proposalID, p.contractorProposalID, address(p.contractorManager), _amount); addContractor(address(p.contractorManager), now); return true; } function withdrawBoardMeetingFees() returns(bool) { uint _amount = pendingFees[msg.sender]; pendingFees[msg.sender] = 0; if (msg.sender.send(_amount)) { Withdrawal(msg.sender, _amount); return true; } else { pendingFees[msg.sender] = _amount; return false; } } function PendingFees(address _shareHolder) constant returns(uint) { return (pendingFees[_shareHolder]); } function minQuorum() constant returns(uint) { return (uint(daoManager.totalSupply()) / DaoRules.minQuorumDivisor); } function numberOfContractors() constant returns(uint) { return Contractors.length - 1; } function numberOfBoardMeetings() constant returns(uint) { return BoardMeetings.length - 1; } }
The address of the contractor manager smart contract The date of the first order for the contractor
struct Contractor { address contractorManager; uint creationDate; }
12,620,217
[ 1, 1986, 1758, 434, 326, 6835, 280, 3301, 13706, 6835, 1021, 1509, 434, 326, 1122, 1353, 364, 326, 6835, 280, 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, 3639, 1958, 13456, 280, 288, 203, 7734, 1758, 6835, 280, 1318, 31, 203, 7734, 2254, 6710, 1626, 31, 203, 3639, 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 ]
./full_match/80001/0x38D7c5D106c93831351fc4c6C9686b5FE8dd28C3/sources/src/lib/PureHelpers.sol
@notice Returns sorted array of accounts for 0xSplits.
function _sortAddresses(address[] memory addresses) internal pure returns (address[] memory) { for (uint256 i = addresses.length - 1; i > 0;) { for (uint256 j = 0; j < i;) { if (addresses[i] < addresses[j]) { (addresses[i], addresses[j]) = (addresses[j], addresses[i]); } unchecked { ++j; } } unchecked { --i; } } return addresses; }
5,632,460
[ 1, 1356, 3115, 526, 434, 9484, 364, 374, 92, 16582, 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, 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, 445, 389, 3804, 7148, 12, 2867, 8526, 3778, 6138, 13, 2713, 16618, 1135, 261, 2867, 8526, 3778, 13, 288, 203, 3639, 364, 261, 11890, 5034, 277, 273, 6138, 18, 2469, 300, 404, 31, 277, 405, 374, 30943, 288, 203, 5411, 364, 261, 11890, 5034, 525, 273, 374, 31, 525, 411, 277, 30943, 288, 203, 7734, 309, 261, 13277, 63, 77, 65, 411, 6138, 63, 78, 5717, 288, 203, 10792, 261, 13277, 63, 77, 6487, 6138, 63, 78, 5717, 273, 261, 13277, 63, 78, 6487, 6138, 63, 77, 19226, 203, 7734, 289, 203, 7734, 22893, 288, 203, 10792, 965, 78, 31, 203, 7734, 289, 203, 5411, 289, 203, 5411, 22893, 288, 203, 7734, 1493, 77, 31, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 327, 6138, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.4.21 <0.8.0; pragma abicoder v2; // import ERC721 iterface import "./ERC721.sol"; // JunkGuys smart contract inherits ERC721 interface contract JunkGuys is ERC721 { // this contract's token collection name string public collectionName; // this contract's token symbol string public collectionNameSymbol; // total number of junk guys minted uint256 public junkGuyCounter; // define junk guy struct struct JunkGuy { uint256 tokenId; string tokenName; string tokenURI; address payable mintedBy; address payable currentOwner; address payable previousOwner; uint256 price; uint256 numberOfTransfers; bool forSale; } // map junkguy's token id to junk guy mapping(uint256 => JunkGuy) public allJunkGuys; // check if token name exists mapping(string => bool) public tokenNameExists; // check if color exists mapping(string => bool) public colorExists; // check if token URI exists mapping(string => bool) public tokenURIExists; // initialize contract while deployment with contract's collection name and token constructor() ERC721("Junk Guys Collection", "CB") { collectionName = name(); collectionNameSymbol = symbol(); } // mint a new junk guy function mintJunkGuy(string memory _name, string memory _tokenURI, uint256 _price, string[] calldata _colors) external { // check if thic fucntion caller is not an zero address account require(msg.sender != address(0)); // increment counter junkGuyCounter ++; // check if a token exists with the above token id => incremented counter require(!_exists(junkGuyCounter)); // loop through the colors passed and check if each colors already exists or not for(uint i=0; i<_colors.length; i++) { require(!colorExists[_colors[i]]); } // check if the token URI already exists or not require(!tokenURIExists[_tokenURI]); // check if the token name already exists or not require(!tokenNameExists[_name]); // mint the token _mint(msg.sender, junkGuyCounter); // set token URI (bind token id with the passed in token URI) _setTokenURI(junkGuyCounter, _tokenURI); // loop through the colors passed and make each of the colors as exists since the token is already minted for (uint i=0; i<_colors.length; i++) { colorExists[_colors[i]] = true; } // make passed token URI as exists tokenURIExists[_tokenURI] = true; // make token name passed as exists tokenNameExists[_name] = true; // creat a new junk guy (struct) and pass in new values JunkGuy memory newJunkGuy = JunkGuy( junkGuyCounter, _name, _tokenURI, msg.sender, msg.sender, address(0), _price, 0, true); // add the token id and it's junk guy to all junk guys mapping allJunkGuys[junkGuyCounter] = newJunkGuy; } // get owner of the token function getTokenOwner(uint256 _tokenId) public view returns(address) { address _tokenOwner = ownerOf(_tokenId); return _tokenOwner; } // get metadata of the token function getTokenMetaData(uint _tokenId) public view returns(string memory) { string memory tokenMetaData = tokenURI(_tokenId); return tokenMetaData; } // get total number of tokens minted so far function getNumberOfTokensMinted() public view returns(uint256) { uint256 totalNumberOfTokensMinted = totalSupply(); return totalNumberOfTokensMinted; } // get total number of tokens owned by an address function getTotalNumberOfTokensOwnedByAnAddress(address _owner) public view returns(uint256) { uint256 totalNumberOfTokensOwned = balanceOf(_owner); return totalNumberOfTokensOwned; } // check if the token already exists function getTokenExists(uint256 _tokenId) public view returns(bool) { bool tokenExists = _exists(_tokenId); return tokenExists; } // by a token by passing in the token's id function buyToken(uint256 _tokenId) public payable { // check if the function caller is not an zero account address require(msg.sender != address(0)); // check if the token id of the token being bought exists or not require(_exists(_tokenId)); // get the token's owner address tokenOwner = ownerOf(_tokenId); // token's owner should not be an zero address account require(tokenOwner != address(0)); // the one who wants to buy the token should not be the token's owner require(tokenOwner != msg.sender); // get that token from all junk guys mapping and create a memory of it defined as (struct => JunkGuy) JunkGuy memory junkguy = allJunkGuys[_tokenId]; // price sent in to buy should be equal to or more than the token's price require(msg.value >= junkguy.price); // token should be for sale require(junkguy.forSale); // transfer the token from owner to the caller of the function (buyer) _transfer(tokenOwner, msg.sender, _tokenId); // get owner of the token address payable sendTo = junkguy.currentOwner; // send token's worth of ethers to the owner sendTo.transfer(msg.value); // update the token's previous owner junkguy.previousOwner = junkguy.currentOwner; // update the token's current owner junkguy.currentOwner = msg.sender; // update the how many times this token was transfered junkguy.numberOfTransfers += 1; // set and update that token in the mapping allJunkGuys[_tokenId] = junkguy; } function changeTokenPrice(uint256 _tokenId, uint256 _newPrice) public { // require caller of the function is not an empty address require(msg.sender != address(0)); // require that token should exist require(_exists(_tokenId)); // get the token's owner address tokenOwner = ownerOf(_tokenId); // check that token's owner should be equal to the caller of the function require(tokenOwner == msg.sender); // get that token from all junk guys mapping and create a memory of it defined as (struct => JunkGuy) JunkGuy memory junkguy = allJunkGuys[_tokenId]; // update token's price with new price junkguy.price = _newPrice; // set and update that token in the mapping allJunkGuys[_tokenId] = junkguy; } // switch between set for sale and set not for sale function toggleForSale(uint256 _tokenId) public { // require caller of the function is not an empty address require(msg.sender != address(0)); // require that token should exist require(_exists(_tokenId)); // get the token's owner address tokenOwner = ownerOf(_tokenId); // check that token's owner should be equal to the caller of the function require(tokenOwner == msg.sender); // get that token from all junk guys mapping and create a memory of it defined as (struct => JunkGuy) JunkGuy memory junkguy = allJunkGuys[_tokenId]; // if token's forSale is false make it true and vice versa if(junkguy.forSale) { junkguy.forSale = false; } else { junkguy.forSale = true; } // set and update that token in the mapping allJunkGuys[_tokenId] = junkguy; } }
map junkguy's token id to junk guy
mapping(uint256 => JunkGuy) public allJunkGuys;
12,969,702
[ 1, 1458, 525, 1683, 6891, 93, 1807, 1147, 612, 358, 525, 1683, 3058, 93, 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, 11890, 5034, 516, 804, 1683, 6099, 93, 13, 1071, 777, 46, 1683, 6099, 1900, 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 ]
./full_match/1/0xba629E206dfB3C6b1B874e6f44a734EAdbE75bEF/sources/contracts/core/PoolRebalanceHelper.sol
The address the transaction was sent to
address to;
2,971,069
[ 1, 1986, 1758, 326, 2492, 1703, 3271, 358, 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, 1758, 358, 31, 1377, 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, -100 ]
./full_match/1/0x82a7b5842085f434c6584A8c44b6A1C15c25a512/sources/contracts/Pool.sol
* @inheritdoc IPool/
function withdraw(uint128 tick, uint128 redemptionId) external nonReentrant returns (uint256, uint256) { (uint128 shares, uint128 amount) = _withdraw(tick, redemptionId); if (amount != 0) _currencyToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, tick, redemptionId, shares, amount); return (shares, amount);
9,659,235
[ 1, 36, 10093, 467, 2864, 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, 565, 445, 598, 9446, 12, 11890, 10392, 4024, 16, 2254, 10392, 283, 19117, 375, 548, 13, 3903, 1661, 426, 8230, 970, 1135, 261, 11890, 5034, 16, 2254, 5034, 13, 288, 203, 3639, 261, 11890, 10392, 24123, 16, 2254, 10392, 3844, 13, 273, 389, 1918, 9446, 12, 6470, 16, 283, 19117, 375, 548, 1769, 203, 203, 3639, 309, 261, 8949, 480, 374, 13, 389, 7095, 1345, 18, 4626, 5912, 12, 3576, 18, 15330, 16, 3844, 1769, 203, 203, 3639, 3626, 3423, 9446, 82, 12, 3576, 18, 15330, 16, 4024, 16, 283, 19117, 375, 548, 16, 24123, 16, 3844, 1769, 203, 203, 3639, 327, 261, 30720, 16, 3844, 1769, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; contract B4000Token is ERC20, Ownable { using SafeMath for *; bool public isMining = true; mapping(address => bool) private adminMap; struct StakeItem { address a; // address uint256 s; // stake count } mapping(address => uint) private stakeIndex; StakeItem[] public stakePool; // NFT cards mine rewards mapping(address => uint256) public nftBalance; // LP stake mine data mapping(address => uint256) public LPBalance; // b4k stake mine data mapping(address => uint256) public coinBalance; // mapping(address => uint256) public _b4kBalance; event onMinedChanged(bool _status); event onAdminChanged(address _addr, bool isAdmin); constructor(address _admin) ERC20("B4000 Coin", "B4K") { adminMap[_admin] = true; stakeIndex[address(this)] = 0; stakePool.push(StakeItem({ a: address(this), s: 0 })); } modifier onlyOwnerAdmin() { address _sender = _msgSender(); require(adminMap[_sender] || owner() == _sender, "B4K: caller is not owner or admin"); _; } // ==================== NFT mine ==================== function nftBalanceOf(address _addr) public view returns(uint256) { return nftBalance[_addr]; } // harvest nft mine rewards function harvestNftMineBalance() public { address _sender = msg.sender; require(nftBalance[_sender] > 0, "B4K: Not enough NFT rewards to harvest"); _mint(_sender, nftBalance[_sender]); nftBalance[_sender] = 0; } // mint b4k to nft owners function batchMintNft(address[] memory _addr, uint256[] memory _mineCount) public onlyOwnerAdmin { require(isMining, "B4K: has stoped mine"); require(_addr.length == _mineCount.length, "B4K: _addr.length and _mineCount.length are not same"); for (uint i = 0; i < _addr.length; i++) { nftBalance[_addr[i]] = nftBalance[_addr[i]].add(_mineCount[i]); } } // ==================== NFT mine ==================== // ==================== LP stake mine ==================== function LPBalanceOf(address _addr) public view returns(uint256) { return LPBalance[_addr]; } // harvest LP stake mine rewards function harvestLPMineBalance() public { address _sender = msg.sender; require(LPBalance[_sender] > 0, "B4K: Not enough LP stake rewards to harvest"); _mint(_sender, LPBalance[_sender]); LPBalance[_sender] = 0; } // mint b4k to LP stakers function batchMintLP(address[] memory _addr, uint256[] memory _mineCount) public onlyOwnerAdmin { require(isMining, "B4K: has stoped mine"); require(_addr.length == _mineCount.length, "B4K: _addr.length and _mineCount.length are not same"); for (uint i = 0; i < _addr.length; i++) { LPBalance[_addr[i]] = LPBalance[_addr[i]].add(_mineCount[i]); } } // ==================== LP stake mine ==================== // ==================== B4k Coin stake mine ==================== function coinBalanceOf(address _addr) public view returns(uint256) { return coinBalance[_addr]; } // harvest b4k stake mine rewards function harvestCoinBalance() public { address _sender = msg.sender; require(coinBalance[_sender] > 0, "B4K: Not enough b4k rewards to harvest"); _mint(_sender, coinBalance[_sender]); coinBalance[_sender] = 0; } function batchMintCoin(address[] memory _addr, uint256[] memory _mineCount) public onlyOwnerAdmin { require(isMining, "B4K: has stoped mine"); require(_addr.length == _mineCount.length, "B4K: _addr.length and _mineCount.length are not same"); for (uint i = 0; i < _addr.length; i++) { coinBalance[_addr[i]] = coinBalance[_addr[i]].add(_mineCount[i]); } } // ==================== B4k Coin stake mine ==================== // ==================== stake B4K ==================== function getStakeData() public view returns(StakeItem[] memory) { uint total = stakePool.length; StakeItem[] memory arr = new StakeItem[](total); // the (i == 0) is this contract placeholder, not used for users for (uint i = 1; i < stakePool.length; i++) { arr[i] = stakePool[i]; } return arr; } function stakeIndexOf(address _addr) public view returns (uint) { return stakeIndex[_addr]; } function stakeBalanceOf(address _addr) public view returns (StakeItem memory) { uint idx = stakeIndex[_addr]; if(idx == 0) { // Not Found return StakeItem({ a: address(_addr), s: 0 }); } return stakePool[idx]; } function withdrawStake(uint256 _count) public { require(_count > 0, "B4K: withdrawn token counts should > 0"); address _sender = msg.sender; uint idx = stakeIndex[_sender]; require(idx > 0, "B4K: Not stake any token before"); StakeItem memory st = stakePool[idx]; uint256 balance = st.s; require(balance >= _count, "B4K: Not enough staked blance to withdraw"); _transfer(address(this), _sender, _count); stakePool[idx] = StakeItem({ a: _sender, s: st.s.sub(_count) }); } // stake b4k token from user's wallet function stakeToken(uint256 _count) public { require(_count > 0, "B4K: staked token counts should > 0"); address _sender = msg.sender; uint256 senderBallance = balanceOf(_sender); require(senderBallance >= _count, "B4K: Not enough ballance to stake"); transfer(address(this), _count); increaseStakePool(_sender, _count); } // compound: stake user's all rewards from coinBalance function compoundCoinRewards() public { address _sender = msg.sender; uint256 ballance = coinBalance[_sender]; require(ballance > 0, "B4K: Not enough b4k rewards to stake"); coinBalance[_sender] = 0; increaseStakePool(_sender, ballance); _mint(address(this), ballance); } function increaseStakePool(address _addr, uint256 _count) internal { uint idx = stakeIndex[_addr]; if(idx > 0) { stakePool[idx].s = stakePool[idx].s.add(_count); } else { stakePool.push(StakeItem({ a: _addr, s: _count })); stakeIndex[_addr] = stakePool.length - 1; } } // ==================== stake B4K ==================== function startMine() public onlyOwner { isMining = true; emit onMinedChanged(isMining); } function stopMine() public onlyOwner { isMining = false; emit onMinedChanged(isMining); } function setAdmin(address _addr) public onlyOwner { adminMap[_addr] = true; emit onAdminChanged(_addr, true); } function removeAdmin(address _addr) public onlyOwner { adminMap[_addr] = false; emit onAdminChanged(_addr, false); } function isAdmin(address _addr) public view returns (bool) { return adminMap[_addr]; } function mintTo(address _addr, uint256 _mineCount) public onlyOwnerAdmin { require(isMining, "B4K: has stoped mine"); _mint(_addr, _mineCount); } }
harvest b4k stake mine rewards
function harvestCoinBalance() public { address _sender = msg.sender; require(coinBalance[_sender] > 0, "B4K: Not enough b4k rewards to harvest"); _mint(_sender, coinBalance[_sender]); coinBalance[_sender] = 0; }
13,097,317
[ 1, 30250, 26923, 324, 24, 79, 384, 911, 312, 558, 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, 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, 17895, 26923, 27055, 13937, 1435, 1071, 288, 203, 3639, 1758, 389, 15330, 273, 1234, 18, 15330, 31, 203, 3639, 2583, 12, 12645, 13937, 63, 67, 15330, 65, 405, 374, 16, 315, 38, 24, 47, 30, 2288, 7304, 324, 24, 79, 283, 6397, 358, 17895, 26923, 8863, 203, 3639, 389, 81, 474, 24899, 15330, 16, 13170, 13937, 63, 67, 15330, 19226, 203, 3639, 13170, 13937, 63, 67, 15330, 65, 273, 374, 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 ]
pragma solidity ^0.5.2; contract Ownable { address private _owner; event OWNERSHIPTRANSFERRED275(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = msg.sender; emit OWNERSHIPTRANSFERRED275(address(0), _owner); } function OWNER625() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER263() { //inject NONSTANDARD NAMING require(ISOWNER221()); _; } function ISOWNER221() public view returns (bool) { //inject NONSTANDARD NAMING return msg.sender == _owner; } function RENOUNCEOWNERSHIP563() public ONLYOWNER263 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED275(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP811(address newOwner) public ONLYOWNER263 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP827(newOwner); } function _TRANSFEROWNERSHIP827(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0)); emit OWNERSHIPTRANSFERRED275(_owner, newOwner); _owner = newOwner; } } contract Secondary { address private _primary; event PRIMARYTRANSFERRED466( //inject NONSTANDARD NAMING address recipient ); constructor () internal { _primary = msg.sender; emit PRIMARYTRANSFERRED466(_primary); } modifier ONLYPRIMARY116() { //inject NONSTANDARD NAMING require(msg.sender == _primary); _; } function PRIMARY581() public view returns (address) { //inject NONSTANDARD NAMING return _primary; } function TRANSFERPRIMARY630(address recipient) public ONLYPRIMARY116 { //inject NONSTANDARD NAMING require(recipient != address(0)); _primary = recipient; emit PRIMARYTRANSFERRED466(_primary); } } // File: node_modules\openzeppelin-solidity\contracts\token\ERC20\IERC20.sol interface IERC20 { function TRANSFER568(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE366(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM855(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TOTALSUPPLY96() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF58(address who) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE511(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING event TRANSFER836(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL290(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: node_modules\openzeppelin-solidity\contracts\math\SafeMath.sol library SafeMath { function MUL97(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function DIV803(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function SUB631(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function ADD445(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MOD309(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } // File: node_modules\openzeppelin-solidity\contracts\token\ERC20\ERC20.sol contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; function TOTALSUPPLY96() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF58(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE511(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowed[owner][spender]; } function TRANSFER568(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER261(msg.sender, to, value); return true; } function APPROVE366(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE283(msg.sender, spender, value); return true; } function TRANSFERFROM855(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER261(from, to, value); _APPROVE283(from, msg.sender, _allowed[from][msg.sender].SUB631(value)); return true; } function INCREASEALLOWANCE464(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE283(msg.sender, spender, _allowed[msg.sender][spender].ADD445(addedValue)); return true; } function DECREASEALLOWANCE302(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE283(msg.sender, spender, _allowed[msg.sender][spender].SUB631(subtractedValue)); return true; } function _TRANSFER261(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(to != address(0)); _balances[from] = _balances[from].SUB631(value); _balances[to] = _balances[to].ADD445(value); emit TRANSFER836(from, to, value); } function _MINT945(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.ADD445(value); _balances[account] = _balances[account].ADD445(value); emit TRANSFER836(address(0), account, value); } function _BURN542(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.SUB631(value); _balances[account] = _balances[account].SUB631(value); emit TRANSFER836(account, address(0), value); } function _APPROVE283(address owner, address spender, uint256 value) internal { //inject NONSTANDARD NAMING require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit APPROVAL290(owner, spender, value); } function _BURNFROM236(address account, uint256 value) internal { //inject NONSTANDARD NAMING _BURN542(account, value); _APPROVE283(account, msg.sender, _allowed[account][msg.sender].SUB631(value)); } } // File: openzeppelin-solidity\contracts\token\ERC20\ERC20Burnable.sol contract ERC20Burnable is ERC20 { function BURN435(uint256 value) public { //inject NONSTANDARD NAMING _BURN542(msg.sender, value); } function BURNFROM369(address from, uint256 value) public { //inject NONSTANDARD NAMING _BURNFROM236(from, value); } } // File: node_modules\openzeppelin-solidity\contracts\access\Roles.sol library Roles { struct Role { mapping (address => bool) bearer; } function ADD445(Role storage role, address account) internal { //inject NONSTANDARD NAMING require(account != address(0)); require(!HAS23(role, account)); role.bearer[account] = true; } function REMOVE600(Role storage role, address account) internal { //inject NONSTANDARD NAMING require(account != address(0)); require(HAS23(role, account)); role.bearer[account] = false; } function HAS23(Role storage role, address account) internal view returns (bool) { //inject NONSTANDARD NAMING require(account != address(0)); return role.bearer[account]; } } // File: node_modules\openzeppelin-solidity\contracts\access\roles\MinterRole.sol contract MinterRole { using Roles for Roles.Role; event MINTERADDED570(address indexed account); //inject NONSTANDARD NAMING event MINTERREMOVED239(address indexed account); //inject NONSTANDARD NAMING Roles.Role private _minters; constructor () internal { _ADDMINTER827(msg.sender); } modifier ONLYMINTER291() { //inject NONSTANDARD NAMING require(ISMINTER698(msg.sender)); _; } function ISMINTER698(address account) public view returns (bool) { //inject NONSTANDARD NAMING return _minters.HAS23(account); } function ADDMINTER239(address account) public ONLYMINTER291 { //inject NONSTANDARD NAMING _ADDMINTER827(account); } function RENOUNCEMINTER237() public { //inject NONSTANDARD NAMING _REMOVEMINTER650(msg.sender); } function _ADDMINTER827(address account) internal { //inject NONSTANDARD NAMING _minters.ADD445(account); emit MINTERADDED570(account); } function _REMOVEMINTER650(address account) internal { //inject NONSTANDARD NAMING _minters.REMOVE600(account); emit MINTERREMOVED239(account); } } // File: openzeppelin-solidity\contracts\token\ERC20\ERC20Mintable.sol contract ERC20Mintable is ERC20, MinterRole { function MINT610(address to, uint256 value) public ONLYMINTER291 returns (bool) { //inject NONSTANDARD NAMING _MINT945(to, value); return true; } } // File: contracts\ERC20Frozenable.sol //truffle-flattener Token.sol contract ERC20Frozenable is ERC20Burnable, ERC20Mintable, Ownable { mapping (address => bool) private _frozenAccount; event FROZENFUNDS807(address target, bool frozen); //inject NONSTANDARD NAMING function FROZENACCOUNT782(address _address) public view returns(bool isFrozen) { //inject NONSTANDARD NAMING return _frozenAccount[_address]; } function FREEZEACCOUNT250(address target, bool freeze) public ONLYOWNER263 { //inject NONSTANDARD NAMING require(_frozenAccount[target] != freeze, "Same as current"); _frozenAccount[target] = freeze; emit FROZENFUNDS807(target, freeze); } function _TRANSFER261(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(!_frozenAccount[from], "error - frozen"); require(!_frozenAccount[to], "error - frozen"); super._TRANSFER261(from, to, value); } } // File: openzeppelin-solidity\contracts\token\ERC20\ERC20Detailed.sol contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function NAME858() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL418() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS361() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } } contract Escrow is Secondary { using SafeMath for uint256; event DEPOSITED6(address indexed payee, uint256 weiAmount); //inject NONSTANDARD NAMING event WITHDRAWN702(address indexed payee, uint256 weiAmount); //inject NONSTANDARD NAMING mapping(address => uint256) private _deposits; function DEPOSITSOF491(address payee) public view returns (uint256) { //inject NONSTANDARD NAMING return _deposits[payee]; } function DEPOSIT494(address payee) public ONLYPRIMARY116 payable { //inject NONSTANDARD NAMING uint256 amount = msg.value; _deposits[payee] = _deposits[payee].ADD445(amount); emit DEPOSITED6(payee, amount); } function WITHDRAW275(address payable payee) public ONLYPRIMARY116 { //inject NONSTANDARD NAMING uint256 payment = _deposits[payee]; _deposits[payee] = 0; payee.transfer(payment); emit WITHDRAWN702(payee, payment); } } contract PullPayment { Escrow private _escrow; constructor () internal { _escrow = new Escrow(); } function WITHDRAWPAYMENTS729(address payable payee) public { //inject NONSTANDARD NAMING _escrow.WITHDRAW275(payee); } function PAYMENTS838(address dest) public view returns (uint256) { //inject NONSTANDARD NAMING return _escrow.DEPOSITSOF491(dest); } function _ASYNCTRANSFER275(address dest, uint256 amount) internal { //inject NONSTANDARD NAMING _escrow.DEPOSIT494.value(amount)(dest); } } contract PaymentSplitter { using SafeMath for uint256; event PAYEEADDED416(address account, uint256 shares); //inject NONSTANDARD NAMING event PAYMENTRELEASED38(address to, uint256 amount); //inject NONSTANDARD NAMING event PAYMENTRECEIVED491(address from, uint256 amount); //inject NONSTANDARD NAMING uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; constructor (address[] memory payees, uint256[] memory shares) public payable { require(payees.length == shares.length); require(payees.length > 0); for (uint256 i = 0; i < payees.length; i++) { _ADDPAYEE628(payees[i], shares[i]); } } function () external payable { emit PAYMENTRECEIVED491(msg.sender, msg.value); } function TOTALSHARES81() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalShares; } function TOTALRELEASED129() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalReleased; } function SHARES670(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _shares[account]; } function RELEASED874(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _released[account]; } function PAYEE185(uint256 index) public view returns (address) { //inject NONSTANDARD NAMING return _payees[index]; } function RELEASE471(address payable account) public { //inject NONSTANDARD NAMING require(_shares[account] > 0); uint256 totalReceived = address(this).balance.ADD445(_totalReleased); uint256 payment = totalReceived.MUL97(_shares[account]).DIV803(_totalShares).SUB631(_released[account]); require(payment != 0); _released[account] = _released[account].ADD445(payment); _totalReleased = _totalReleased.ADD445(payment); account.transfer(payment); emit PAYMENTRELEASED38(account, payment); } function _ADDPAYEE628(address account, uint256 shares_) private { //inject NONSTANDARD NAMING require(account != address(0)); require(shares_ > 0); require(_shares[account] == 0); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares.ADD445(shares_); emit PAYEEADDED416(account, shares_); } } contract ConditionalEscrow is Escrow { function WITHDRAWALALLOWED82(address payee) public view returns (bool); //inject NONSTANDARD NAMING function WITHDRAW275(address payable payee) public { //inject NONSTANDARD NAMING require(WITHDRAWALALLOWED82(payee)); super.WITHDRAW275(payee); } } contract RefundEscrow is ConditionalEscrow { enum State { Active, Refunding, Closed } event REFUNDSCLOSED652(); //inject NONSTANDARD NAMING event REFUNDSENABLED266(); //inject NONSTANDARD NAMING State private _state; address payable private _beneficiary; constructor (address payable beneficiary) public { require(beneficiary != address(0)); _beneficiary = beneficiary; _state = State.Active; } function STATE442() public view returns (State) { //inject NONSTANDARD NAMING return _state; } function BENEFICIARY91() public view returns (address) { //inject NONSTANDARD NAMING return _beneficiary; } function DEPOSIT494(address refundee) public payable { //inject NONSTANDARD NAMING require(_state == State.Active); super.DEPOSIT494(refundee); } function CLOSE124() public ONLYPRIMARY116 { //inject NONSTANDARD NAMING require(_state == State.Active); _state = State.Closed; emit REFUNDSCLOSED652(); } function ENABLEREFUNDS102() public ONLYPRIMARY116 { //inject NONSTANDARD NAMING require(_state == State.Active); _state = State.Refunding; emit REFUNDSENABLED266(); } function BENEFICIARYWITHDRAW365() public { //inject NONSTANDARD NAMING require(_state == State.Closed); _beneficiary.transfer(address(this).balance); } function WITHDRAWALALLOWED82(address) public view returns (bool) { //inject NONSTANDARD NAMING return _state == State.Refunding; } } // File: contracts\Token.sol //truffle-flattener Token.sol contract DeltaBlocks is ERC20Frozenable, ERC20Detailed { constructor() ERC20Detailed("Delta Blocks", "DTB", 18) public { uint256 supply = 10000000000; uint256 initialSupply = supply * uint(10) ** DECIMALS361(); _MINT945(msg.sender, initialSupply); } }
inject NONSTANDARD NAMING
function PAYMENTS838(address dest) public view returns (uint256) {
7,302,981
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 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, 25095, 3212, 55, 28, 7414, 12, 2867, 1570, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 202, 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 ]
./partial_match/42220/0x7ef2EA0939Fa35f3fA78616E3E12246324739203/sources/lib/staked-celo/contracts/Manager.sol
* @notice Used when attempting to activate a group that is already active. @param group The group's address./
error GroupAlreadyAdded(address group);
3,497,647
[ 1, 6668, 1347, 15600, 358, 10235, 279, 1041, 716, 353, 1818, 2695, 18, 225, 1041, 1021, 1041, 1807, 1758, 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, 555, 3756, 9430, 8602, 12, 2867, 1041, 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, -100, -100, -100, -100, -100, -100 ]
//Address: 0x7c43dea72a94972a341489b60ce9a07eb45253f9 //Contract name: AGRECrowdsale //Balance: 0 Ether //Verification Date: 12/3/2017 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.18; //====== Open Zeppelin Library ===== /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Contracts that should not own Contracts * @author Remco Bloemen <remco@2π.com> * @dev Should contracts (anything Ownable) end up being owned by this contract, it allows the owner * of this contract to reclaim ownership of the contracts. */ contract HasNoContracts is Ownable { /** * @dev Reclaim ownership of Ownable contracts * @param contractAddr The address of the Ownable to be reclaimed. */ function reclaimContract(address contractAddr) external onlyOwner { Ownable contractInst = Ownable(contractAddr); contractInst.transferOwnership(owner); } } /** * @title Contracts that should be able to recover tokens * @author SylTi * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. * This will prevent any accidental loss of tokens. */ contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; /** * @dev Reclaim all ERC20Basic compatible tokens * @param token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic token) external onlyOwner { uint256 balance = token.balanceOf(this); token.safeTransfer(owner, balance); } } /** * @title Contracts that should not own Tokens * @author Remco Bloemen <remco@2π.com> * @dev This blocks incoming ERC23 tokens to prevent accidental loss of tokens. * Should tokens (any ERC20Basic compatible) end up in the contract, it allows the * owner to reclaim the tokens. */ contract HasNoTokens is CanReclaimToken { /** * @dev Reject all ERC23 compatible tokens * @param from_ address The address that is transferring the tokens * @param value_ uint256 the amount of the specified token * @param data_ Bytes The data passed from the caller. */ function tokenFallback(address from_, uint256 value_, bytes data_) external { from_; value_; data_; revert(); } } /** * @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 { function Destructible() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } //====== AGRE Contracts ===== /** * @title TradeableToken can be bought and sold from/to it's own contract during it's life time * Sold tokens and Ether received to buy tokens are collected during specified period and then time comes * contract owner should specify price for the last period and send tokens/ether to their new owners. */ contract TradeableToken is StandardToken, Ownable { using SafeMath for uint256; event Sale(address indexed buyer, uint256 amount); event Redemption(address indexed seller, uint256 amount); event DistributionError(address seller, uint256 amount); /** * State of the contract: * Collecting - collecting ether and tokens * Distribution - distribution of bought tokens and ether is in process */ enum State{Collecting, Distribution} State public currentState; //Current state of the contract uint256 public previousPeriodRate; //Previous rate: how many tokens one could receive for 1 ether in the last period uint256 public currentPeriodEndTimestamp; //Timestamp after which no more trades are accepted and contract is waiting to start distribution uint256 public currentPeriodStartBlock; //Number of block when current perions was started uint256 public currentPeriodRate; //Current rate: how much tokens one should receive for 1 ether in current distribution period uint256 public currentPeriodEtherCollected; //How much ether was collected (to buy tokens) during current period and waiting for distribution uint256 public currentPeriodTokenCollected; //How much tokens was collected (to sell tokens) during current period and waiting for distribution mapping(address => uint256) receivedEther; //maps address of buyer to amount of ether he sent mapping(address => uint256) soldTokens; //maps address of seller to amount of tokens he sent uint32 constant MILLI_PERCENT_DIVIDER = 100*1000; uint32 public buyFeeMilliPercent; //The buyer's fee in a thousandth of percent. So, if buyer's fee = 5%, then buyFeeMilliPercent = 5000 and if without buyer shoud receive 200 tokens with fee it will receive 200 - (200 * 5000 / MILLI_PERCENT_DIVIDER) uint32 public sellFeeMilliPercent; //The seller's fee in a thousandth of percent. (see above) uint256 public minBuyAmount; //Minimal amount of ether to buy uint256 public minSellAmount; //Minimal amount of tokens to sell modifier canBuyAndSell() { require(currentState == State.Collecting); require(now < currentPeriodEndTimestamp); _; } function TradeableToken() public { currentState = State.Distribution; //currentPeriodStartBlock = 0; currentPeriodEndTimestamp = now; //ensure that nothing can be collected until new period is started by owner } /** * @notice Send Ether to buy tokens */ function() payable public { require(msg.value > 0); buy(msg.sender, msg.value); } /** * @notice Transfer or sell tokens * Sells tokens transferred to this contract itself or to zero address * @param _to The address to transfer to or token contract address to burn. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { if( (_to == address(this)) || (_to == 0) ){ return sell(msg.sender, _value); }else{ return super.transfer(_to, _value); } } /** * @notice Transfer tokens from one address to another or sell them if _to is this contract or zero address * @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 amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { if( (_to == address(this)) || (_to == 0) ){ var _allowance = allowed[_from][msg.sender]; require (_value <= _allowance); allowed[_from][msg.sender] = _allowance.sub(_value); return sell(_from, _value); }else{ return super.transferFrom(_from, _to, _value); } } /** * @dev Fuction called when somebody is buying tokens * @param who The address of buyer (who will own bought tokens) * @param amount The amount to be transferred. */ function buy(address who, uint256 amount) canBuyAndSell internal returns(bool){ require(amount >= minBuyAmount); currentPeriodEtherCollected = currentPeriodEtherCollected.add(amount); receivedEther[who] = receivedEther[who].add(amount); //if this is first operation from this address, initial value of receivedEther[to] == 0 Sale(who, amount); return true; } /** * @dev Fuction called when somebody is selling his tokens * @param who The address of seller (whose tokens are sold) * @param amount The amount to be transferred. */ function sell(address who, uint256 amount) canBuyAndSell internal returns(bool){ require(amount >= minSellAmount); currentPeriodTokenCollected = currentPeriodTokenCollected.add(amount); soldTokens[who] = soldTokens[who].add(amount); //if this is first operation from this address, initial value of soldTokens[to] == 0 totalSupply = totalSupply.sub(amount); Redemption(who, amount); Transfer(who, address(0), amount); return true; } /** * @notice Set fee applied when buying tokens * @param _buyFeeMilliPercent fee in thousandth of percent (5% = 5000) */ function setBuyFee(uint32 _buyFeeMilliPercent) onlyOwner public { require(_buyFeeMilliPercent < MILLI_PERCENT_DIVIDER); buyFeeMilliPercent = _buyFeeMilliPercent; } /** * @notice Set fee applied when selling tokens * @param _sellFeeMilliPercent fee in thousandth of percent (5% = 5000) */ function setSellFee(uint32 _sellFeeMilliPercent) onlyOwner public { require(_sellFeeMilliPercent < MILLI_PERCENT_DIVIDER); sellFeeMilliPercent = _sellFeeMilliPercent; } /** * @notice set minimal amount of ether which can be used to buy tokens * @param _minBuyAmount minimal amount of ether */ function setMinBuyAmount(uint256 _minBuyAmount) onlyOwner public { minBuyAmount = _minBuyAmount; } /** * @notice set minimal amount of ether which can be used to buy tokens * @param _minSellAmount minimal amount of tokens */ function setMinSellAmount(uint256 _minSellAmount) onlyOwner public { minSellAmount = _minSellAmount; } /** * @notice Collect ether received for token purshases * This is possible both during Collection and Distribution phases */ function collectEther(uint256 amount) onlyOwner public { owner.transfer(amount); } /** * @notice Start distribution phase * @param _currentPeriodRate exchange rate for current distribution */ function startDistribution(uint256 _currentPeriodRate) onlyOwner public { require(currentState != State.Distribution); //owner should not be able to change rate after distribution is started, ensures that everyone have the same rate require(_currentPeriodRate != 0); //something has to be distributed! //require(now >= currentPeriodEndTimestamp) //DO NOT require period end timestamp passed, because there can be some situations when it is neede to end it sooner. But this should be done with extremal care, because of possible race condition between new sales/purshases and currentPeriodRate definition currentState = State.Distribution; currentPeriodRate = _currentPeriodRate; } /** * @notice Distribute tokens to buyers * @param buyers an array of addresses to pay tokens for their ether. Should be composed from outside by reading Sale events */ function distributeTokens(address[] buyers) onlyOwner public { require(currentState == State.Distribution); require(currentPeriodRate > 0); for(uint256 i=0; i < buyers.length; i++){ address buyer = buyers[i]; require(buyer != address(0)); uint256 etherAmount = receivedEther[buyer]; if(etherAmount == 0) continue; //buyer not found or already paid uint256 tokenAmount = etherAmount.mul(currentPeriodRate); uint256 fee = tokenAmount.mul(buyFeeMilliPercent).div(MILLI_PERCENT_DIVIDER); tokenAmount = tokenAmount.sub(fee); receivedEther[buyer] = 0; currentPeriodEtherCollected = currentPeriodEtherCollected.sub(etherAmount); //mint tokens totalSupply = totalSupply.add(tokenAmount); balances[buyer] = balances[buyer].add(tokenAmount); Transfer(address(0), buyer, tokenAmount); } } /** * @notice Distribute ether to sellers * If not enough ether is available on contract ballance * @param sellers an array of addresses to pay ether for their tokens. Should be composed from outside by reading Redemption events */ function distributeEther(address[] sellers) onlyOwner payable public { require(currentState == State.Distribution); require(currentPeriodRate > 0); for(uint256 i=0; i < sellers.length; i++){ address seller = sellers[i]; require(seller != address(0)); uint256 tokenAmount = soldTokens[seller]; if(tokenAmount == 0) continue; //seller not found or already paid uint256 etherAmount = tokenAmount.div(currentPeriodRate); uint256 fee = etherAmount.mul(sellFeeMilliPercent).div(MILLI_PERCENT_DIVIDER); etherAmount = etherAmount.sub(fee); soldTokens[seller] = 0; currentPeriodTokenCollected = currentPeriodTokenCollected.sub(tokenAmount); if(!seller.send(etherAmount)){ //in this case we can only log error and let owner to handle it manually DistributionError(seller, etherAmount); owner.transfer(etherAmount); //assume this should not fail..., overwise - change owner } } } function startCollecting(uint256 _collectingEndTimestamp) onlyOwner public { require(_collectingEndTimestamp > now); //Need some time for collection require(currentState == State.Distribution); //Do not allow to change collection terms after it is started require(currentPeriodEtherCollected == 0); //All sold tokens are distributed require(currentPeriodTokenCollected == 0); //All redeemed tokens are paid previousPeriodRate = currentPeriodRate; currentPeriodRate = 0; currentPeriodStartBlock = block.number; currentPeriodEndTimestamp = _collectingEndTimestamp; currentState = State.Collecting; } } contract AGREToken is TradeableToken, MintableToken, HasNoContracts, HasNoTokens { //MintableToken is StandardToken, Ownable string public symbol = "AGRE"; string public name = "Aggregate Coin"; uint8 public constant decimals = 18; address public founder; //founder address to allow him transfer tokens while minting function init(address _founder, uint32 _buyFeeMilliPercent, uint32 _sellFeeMilliPercent, uint256 _minBuyAmount, uint256 _minSellAmount) onlyOwner public { founder = _founder; setBuyFee(_buyFeeMilliPercent); setSellFee(_sellFeeMilliPercent); setMinBuyAmount(_minBuyAmount); setMinSellAmount(_minSellAmount); } /** * Allow transfer only after crowdsale finished */ modifier canTransfer() { require(mintingFinished || msg.sender == founder); _; } function transfer(address _to, uint256 _value) canTransfer public returns(bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) canTransfer public returns(bool) { return super.transferFrom(_from, _to, _value); } } contract AGRECrowdsale is Ownable, Destructible { using SafeMath for uint256; uint256 public maxGasPrice = 50000000000 wei; //Maximum gas price for contribution transactions uint256 public startTimestamp; //when crowdsal starts uint256 public endTimestamp; //when crowdsal ends uint256 public rate; //how many tokens will be minted for 1 ETH (like 300 CPM for 1 ETH) uint256 public hardCap; //maximum amount of ether to collect AGREToken public token; uint256 public collectedEther; /** * verifies that the gas price is lower than maxGasPrice */ modifier validGasPrice() { require(tx.gasprice <= maxGasPrice); _; } /** * @notice Create a crowdsale contract, a token and initialize them * @param _ownerTokens Amount of tokens that will be mint to owner during the sale */ function AGRECrowdsale(uint256 _startTimestamp, uint256 _endTimestamp, uint256 _rate, uint256 _hardCap, uint256 _ownerTokens, uint32 _buyFeeMilliPercent, uint32 _sellFeeMilliPercent, uint256 _minBuyAmount, uint256 _minSellAmount) public { require(_startTimestamp < _endTimestamp); require(_rate > 0); startTimestamp = _startTimestamp; endTimestamp = _endTimestamp; rate = _rate; hardCap = _hardCap; token = new AGREToken(); token.init(msg.sender, _buyFeeMilliPercent, _sellFeeMilliPercent, _minBuyAmount, _minSellAmount); token.mint(msg.sender, _ownerTokens); } function () payable validGasPrice public { require(crowdsaleOpen()); require(msg.value > 0); require(collectedEther.add(msg.value) <= hardCap); collectedEther = collectedEther.add(msg.value); uint256 buyerTokens = rate.mul(msg.value); token.mint(msg.sender, buyerTokens); } function crowdsaleOpen() public constant returns(bool){ return (rate > 0) && (collectedEther < hardCap) && (startTimestamp <= now) && (now <= endTimestamp); } /** * @notice Updates max gas price for crowdsale transactions */ function setMaxGasPrice(uint256 _maxGasPrice) public onlyOwner { maxGasPrice = _maxGasPrice; } /** * @notice Closes crowdsale, finishes minting (allowing token transfers), transfers token ownership to the owner */ function finalizeCrowdsale() public onlyOwner { rate = 0; //this makes crowdsaleOpen() return false; token.finishMinting(); token.transferOwnership(owner); if(this.balance > 0) owner.transfer(this.balance); } /** * @notice Claim collected ether without closing crowdsale */ function claimEther() public onlyOwner { if(this.balance > 0) owner.transfer(this.balance); } }
Need some time for collection
require(_collectingEndTimestamp > now);
12,995,599
[ 1, 14112, 2690, 813, 364, 1849, 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, 3639, 2583, 24899, 14676, 310, 1638, 4921, 405, 2037, 1769, 4202, 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.25; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title 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 Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer( address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve( address _spender, uint256 _value ) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval( address _spender, uint _addedValue ) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval( address _spender, uint _subtractedValue ) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } contract RepublicToken is PausableToken, BurnableToken { string public constant name = "Republic Token"; string public constant symbol = "REN"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 1000000000 * 10**uint256(decimals); /// @notice The RepublicToken Constructor. constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } function transferTokens(address beneficiary, uint256 amount) public onlyOwner returns (bool) { /* solium-disable error-reason */ require(amount > 0); balances[owner] = balances[owner].sub(amount); balances[beneficiary] = balances[beneficiary].add(amount); emit Transfer(owner, beneficiary, amount); return true; } } /** * @notice LinkedList is a library for a circular double linked list. */ library LinkedList { /* * @notice A permanent NULL node (0x0) in the circular double linked list. * NULL.next is the head, and NULL.previous is the tail. */ address public constant NULL = 0x0; /** * @notice A node points to the node before it, and the node after it. If * node.previous = NULL, then the node is the head of the list. If * node.next = NULL, then the node is the tail of the list. */ struct Node { bool inList; address previous; address next; } /** * @notice LinkedList uses a mapping from address to nodes. Each address * uniquely identifies a node, and in this way they are used like pointers. */ struct List { mapping (address => Node) list; } /** * @notice Insert a new node before an existing node. * * @param self The list being used. * @param target The existing node in the list. * @param newNode The next node to insert before the target. */ function insertBefore(List storage self, address target, address newNode) internal { require(!isInList(self, newNode), "already in list"); require(isInList(self, target) || target == NULL, "not in list"); // It is expected that this value is sometimes NULL. address prev = self.list[target].previous; self.list[newNode].next = target; self.list[newNode].previous = prev; self.list[target].previous = newNode; self.list[prev].next = newNode; self.list[newNode].inList = true; } /** * @notice Insert a new node after an existing node. * * @param self The list being used. * @param target The existing node in the list. * @param newNode The next node to insert after the target. */ function insertAfter(List storage self, address target, address newNode) internal { require(!isInList(self, newNode), "already in list"); require(isInList(self, target) || target == NULL, "not in list"); // It is expected that this value is sometimes NULL. address n = self.list[target].next; self.list[newNode].previous = target; self.list[newNode].next = n; self.list[target].next = newNode; self.list[n].previous = newNode; self.list[newNode].inList = true; } /** * @notice Remove a node from the list, and fix the previous and next * pointers that are pointing to the removed node. Removing anode that is not * in the list will do nothing. * * @param self The list being using. * @param node The node in the list to be removed. */ function remove(List storage self, address node) internal { require(isInList(self, node), "not in list"); if (node == NULL) { return; } address p = self.list[node].previous; address n = self.list[node].next; self.list[p].next = n; self.list[n].previous = p; // Deleting the node should set this value to false, but we set it here for // explicitness. self.list[node].inList = false; delete self.list[node]; } /** * @notice Insert a node at the beginning of the list. * * @param self The list being used. * @param node The node to insert at the beginning of the list. */ function prepend(List storage self, address node) internal { // isInList(node) is checked in insertBefore insertBefore(self, begin(self), node); } /** * @notice Insert a node at the end of the list. * * @param self The list being used. * @param node The node to insert at the end of the list. */ function append(List storage self, address node) internal { // isInList(node) is checked in insertBefore insertAfter(self, end(self), node); } function swap(List storage self, address left, address right) internal { // isInList(left) and isInList(right) are checked in remove address previousRight = self.list[right].previous; remove(self, right); insertAfter(self, left, right); remove(self, left); insertAfter(self, previousRight, left); } function isInList(List storage self, address node) internal view returns (bool) { return self.list[node].inList; } /** * @notice Get the node at the beginning of a double linked list. * * @param self The list being used. * * @return A address identifying the node at the beginning of the double * linked list. */ function begin(List storage self) internal view returns (address) { return self.list[NULL].next; } /** * @notice Get the node at the end of a double linked list. * * @param self The list being used. * * @return A address identifying the node at the end of the double linked * list. */ function end(List storage self) internal view returns (address) { return self.list[NULL].previous; } function next(List storage self, address node) internal view returns (address) { require(isInList(self, node), "not in list"); return self.list[node].next; } function previous(List storage self, address node) internal view returns (address) { require(isInList(self, node), "not in list"); return self.list[node].previous; } } /// @notice This contract stores data and funds for the DarknodeRegistry /// contract. The data / fund logic and storage have been separated to improve /// upgradability. contract DarknodeRegistryStore is Ownable { string public VERSION; // Passed in as a constructor parameter. /// @notice Darknodes are stored in the darknode struct. The owner is the /// address that registered the darknode, the bond is the amount of REN that /// was transferred during registration, and the public key is the /// encryption key that should be used when sending sensitive information to /// the darknode. struct Darknode { // The owner of a Darknode is the address that called the register // function. The owner is the only address that is allowed to // deregister the Darknode, unless the Darknode is slashed for // malicious behavior. address owner; // The bond is the amount of REN submitted as a bond by the Darknode. // This amount is reduced when the Darknode is slashed for malicious // behavior. uint256 bond; // The block number at which the Darknode is considered registered. uint256 registeredAt; // The block number at which the Darknode is considered deregistered. uint256 deregisteredAt; // The public key used by this Darknode for encrypting sensitive data // off chain. It is assumed that the Darknode has access to the // respective private key, and that there is an agreement on the format // of the public key. bytes publicKey; } /// Registry data. mapping(address => Darknode) private darknodeRegistry; LinkedList.List private darknodes; // RepublicToken. RepublicToken public ren; /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _ren The address of the RepublicToken contract. constructor( string _VERSION, RepublicToken _ren ) public { VERSION = _VERSION; ren = _ren; } /// @notice Instantiates a darknode and appends it to the darknodes /// linked-list. /// /// @param _darknodeID The darknode's ID. /// @param _darknodeOwner The darknode's owner's address /// @param _bond The darknode's bond value /// @param _publicKey The darknode's public key /// @param _registeredAt The time stamp when the darknode is registered. /// @param _deregisteredAt The time stamp when the darknode is deregistered. function appendDarknode( address _darknodeID, address _darknodeOwner, uint256 _bond, bytes _publicKey, uint256 _registeredAt, uint256 _deregisteredAt ) external onlyOwner { Darknode memory darknode = Darknode({ owner: _darknodeOwner, bond: _bond, publicKey: _publicKey, registeredAt: _registeredAt, deregisteredAt: _deregisteredAt }); darknodeRegistry[_darknodeID] = darknode; LinkedList.append(darknodes, _darknodeID); } /// @notice Returns the address of the first darknode in the store function begin() external view onlyOwner returns(address) { return LinkedList.begin(darknodes); } /// @notice Returns the address of the next darknode in the store after the /// given address. function next(address darknodeID) external view onlyOwner returns(address) { return LinkedList.next(darknodes, darknodeID); } /// @notice Removes a darknode from the store and transfers its bond to the /// owner of this contract. function removeDarknode(address darknodeID) external onlyOwner { uint256 bond = darknodeRegistry[darknodeID].bond; delete darknodeRegistry[darknodeID]; LinkedList.remove(darknodes, darknodeID); require(ren.transfer(owner, bond), "bond transfer failed"); } /// @notice Updates the bond of the darknode. If the bond is being /// decreased, the difference is sent to the owner of this contract. function updateDarknodeBond(address darknodeID, uint256 bond) external onlyOwner { uint256 previousBond = darknodeRegistry[darknodeID].bond; darknodeRegistry[darknodeID].bond = bond; if (previousBond > bond) { require(ren.transfer(owner, previousBond - bond), "cannot transfer bond"); } } /// @notice Updates the deregistration timestamp of a darknode. function updateDarknodeDeregisteredAt(address darknodeID, uint256 deregisteredAt) external onlyOwner { darknodeRegistry[darknodeID].deregisteredAt = deregisteredAt; } /// @notice Returns the owner of a given darknode. function darknodeOwner(address darknodeID) external view onlyOwner returns (address) { return darknodeRegistry[darknodeID].owner; } /// @notice Returns the bond of a given darknode. function darknodeBond(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].bond; } /// @notice Returns the registration time of a given darknode. function darknodeRegisteredAt(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].registeredAt; } /// @notice Returns the deregistration time of a given darknode. function darknodeDeregisteredAt(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].deregisteredAt; } /// @notice Returns the encryption public key of a given darknode. function darknodePublicKey(address darknodeID) external view onlyOwner returns (bytes) { return darknodeRegistry[darknodeID].publicKey; } } /// @notice DarknodeRegistry is responsible for the registration and /// deregistration of Darknodes. contract DarknodeRegistry is Ownable { string public VERSION; // Passed in as a constructor parameter. /// @notice Darknode pods are shuffled after a fixed number of blocks. /// An Epoch stores an epoch hash used as an (insecure) RNG seed, and the /// blocknumber which restricts when the next epoch can be called. struct Epoch { uint256 epochhash; uint256 blocknumber; } uint256 public numDarknodes; uint256 public numDarknodesNextEpoch; uint256 public numDarknodesPreviousEpoch; /// Variables used to parameterize behavior. uint256 public minimumBond; uint256 public minimumPodSize; uint256 public minimumEpochInterval; address public slasher; /// When one of the above variables is modified, it is only updated when the /// next epoch is called. These variables store the values for the next epoch. uint256 public nextMinimumBond; uint256 public nextMinimumPodSize; uint256 public nextMinimumEpochInterval; address public nextSlasher; /// The current and previous epoch Epoch public currentEpoch; Epoch public previousEpoch; /// Republic ERC20 token contract used to transfer bonds. RepublicToken public ren; /// Darknode Registry Store is the storage contract for darknodes. DarknodeRegistryStore public store; /// @notice Emitted when a darknode is registered. /// @param _darknodeID The darknode ID that was registered. /// @param _bond The amount of REN that was transferred as bond. event LogDarknodeRegistered(address _darknodeID, uint256 _bond); /// @notice Emitted when a darknode is deregistered. /// @param _darknodeID The darknode ID that was deregistered. event LogDarknodeDeregistered(address _darknodeID); /// @notice Emitted when a refund has been made. /// @param _owner The address that was refunded. /// @param _amount The amount of REN that was refunded. event LogDarknodeOwnerRefunded(address _owner, uint256 _amount); /// @notice Emitted when a new epoch has begun. event LogNewEpoch(); /// @notice Emitted when a constructor parameter has been updated. event LogMinimumBondUpdated(uint256 previousMinimumBond, uint256 nextMinimumBond); event LogMinimumPodSizeUpdated(uint256 previousMinimumPodSize, uint256 nextMinimumPodSize); event LogMinimumEpochIntervalUpdated(uint256 previousMinimumEpochInterval, uint256 nextMinimumEpochInterval); event LogSlasherUpdated(address previousSlasher, address nextSlasher); /// @notice Only allow the owner that registered the darknode to pass. modifier onlyDarknodeOwner(address _darknodeID) { require(store.darknodeOwner(_darknodeID) == msg.sender, "must be darknode owner"); _; } /// @notice Only allow unregistered darknodes. modifier onlyRefunded(address _darknodeID) { require(isRefunded(_darknodeID), "must be refunded or never registered"); _; } /// @notice Only allow refundable darknodes. modifier onlyRefundable(address _darknodeID) { require(isRefundable(_darknodeID), "must be deregistered for at least one epoch"); _; } /// @notice Only allowed registered nodes without a pending deregistration to /// deregister modifier onlyDeregisterable(address _darknodeID) { require(isDeregisterable(_darknodeID), "must be deregisterable"); _; } /// @notice Only allow the Slasher contract. modifier onlySlasher() { require(slasher == msg.sender, "must be slasher"); _; } /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _renAddress The address of the RepublicToken contract. /// @param _storeAddress The address of the DarknodeRegistryStore contract. /// @param _minimumBond The minimum bond amount that can be submitted by a /// Darknode. /// @param _minimumPodSize The minimum size of a Darknode pod. /// @param _minimumEpochInterval The minimum number of blocks between /// epochs. constructor( string _VERSION, RepublicToken _renAddress, DarknodeRegistryStore _storeAddress, uint256 _minimumBond, uint256 _minimumPodSize, uint256 _minimumEpochInterval ) public { VERSION = _VERSION; store = _storeAddress; ren = _renAddress; minimumBond = _minimumBond; nextMinimumBond = minimumBond; minimumPodSize = _minimumPodSize; nextMinimumPodSize = minimumPodSize; minimumEpochInterval = _minimumEpochInterval; nextMinimumEpochInterval = minimumEpochInterval; currentEpoch = Epoch({ epochhash: uint256(blockhash(block.number - 1)), blocknumber: block.number }); numDarknodes = 0; numDarknodesNextEpoch = 0; numDarknodesPreviousEpoch = 0; } /// @notice Register a darknode and transfer the bond to this contract. The /// caller must provide a public encryption key for the darknode as well as /// a bond in REN. The bond must be provided as an ERC20 allowance. The dark /// node will remain pending registration until the next epoch. Only after /// this period can the darknode be deregistered. The caller of this method /// will be stored as the owner of the darknode. /// /// @param _darknodeID The darknode ID that will be registered. /// @param _publicKey The public key of the darknode. It is stored to allow /// other darknodes and traders to encrypt messages to the trader. /// @param _bond The bond that will be paid. It must be greater than, or /// equal to, the minimum bond. function register(address _darknodeID, bytes _publicKey, uint256 _bond) external onlyRefunded(_darknodeID) { // REN allowance require(_bond >= minimumBond, "insufficient bond"); // require(ren.allowance(msg.sender, address(this)) >= _bond); require(ren.transferFrom(msg.sender, address(this), _bond), "bond transfer failed"); ren.transfer(address(store), _bond); // Flag this darknode for registration store.appendDarknode( _darknodeID, msg.sender, _bond, _publicKey, currentEpoch.blocknumber + minimumEpochInterval, 0 ); numDarknodesNextEpoch += 1; // Emit an event. emit LogDarknodeRegistered(_darknodeID, _bond); } /// @notice Deregister a darknode. The darknode will not be deregistered /// until the end of the epoch. After another epoch, the bond can be /// refunded by calling the refund method. /// @param _darknodeID The darknode ID that will be deregistered. The caller /// of this method store.darknodeRegisteredAt(_darknodeID) must be // the owner of this darknode. function deregister(address _darknodeID) external onlyDeregisterable(_darknodeID) onlyDarknodeOwner(_darknodeID) { // Flag the darknode for deregistration store.updateDarknodeDeregisteredAt(_darknodeID, currentEpoch.blocknumber + minimumEpochInterval); numDarknodesNextEpoch -= 1; // Emit an event emit LogDarknodeDeregistered(_darknodeID); } /// @notice Progress the epoch if it is possible to do so. This captures /// the current timestamp and current blockhash and overrides the current /// epoch. function epoch() external { if (previousEpoch.blocknumber == 0) { // The first epoch must be called by the owner of the contract require(msg.sender == owner, "not authorized (first epochs)"); } // Require that the epoch interval has passed require(block.number >= currentEpoch.blocknumber + minimumEpochInterval, "epoch interval has not passed"); uint256 epochhash = uint256(blockhash(block.number - 1)); // Update the epoch hash and timestamp previousEpoch = currentEpoch; currentEpoch = Epoch({ epochhash: epochhash, blocknumber: block.number }); // Update the registry information numDarknodesPreviousEpoch = numDarknodes; numDarknodes = numDarknodesNextEpoch; // If any update functions have been called, update the values now if (nextMinimumBond != minimumBond) { minimumBond = nextMinimumBond; emit LogMinimumBondUpdated(minimumBond, nextMinimumBond); } if (nextMinimumPodSize != minimumPodSize) { minimumPodSize = nextMinimumPodSize; emit LogMinimumPodSizeUpdated(minimumPodSize, nextMinimumPodSize); } if (nextMinimumEpochInterval != minimumEpochInterval) { minimumEpochInterval = nextMinimumEpochInterval; emit LogMinimumEpochIntervalUpdated(minimumEpochInterval, nextMinimumEpochInterval); } if (nextSlasher != slasher) { slasher = nextSlasher; emit LogSlasherUpdated(slasher, nextSlasher); } // Emit an event emit LogNewEpoch(); } /// @notice Allows the contract owner to transfer ownership of the /// DarknodeRegistryStore. /// @param _newOwner The address to transfer the ownership to. function transferStoreOwnership(address _newOwner) external onlyOwner { store.transferOwnership(_newOwner); } /// @notice Allows the contract owner to update the minimum bond. /// @param _nextMinimumBond The minimum bond amount that can be submitted by /// a darknode. function updateMinimumBond(uint256 _nextMinimumBond) external onlyOwner { // Will be updated next epoch nextMinimumBond = _nextMinimumBond; } /// @notice Allows the contract owner to update the minimum pod size. /// @param _nextMinimumPodSize The minimum size of a pod. function updateMinimumPodSize(uint256 _nextMinimumPodSize) external onlyOwner { // Will be updated next epoch nextMinimumPodSize = _nextMinimumPodSize; } /// @notice Allows the contract owner to update the minimum epoch interval. /// @param _nextMinimumEpochInterval The minimum number of blocks between epochs. function updateMinimumEpochInterval(uint256 _nextMinimumEpochInterval) external onlyOwner { // Will be updated next epoch nextMinimumEpochInterval = _nextMinimumEpochInterval; } /// @notice Allow the contract owner to update the DarknodeSlasher contract /// address. /// @param _slasher The new slasher address. function updateSlasher(address _slasher) external onlyOwner { nextSlasher = _slasher; } /// @notice Allow the DarknodeSlasher contract to slash half of a darknode's /// bond and deregister it. The bond is distributed as follows: /// 1/2 is kept by the guilty prover /// 1/8 is rewarded to the first challenger /// 1/8 is rewarded to the second challenger /// 1/4 becomes unassigned /// @param _prover The guilty prover whose bond is being slashed /// @param _challenger1 The first of the two darknodes who submitted the challenge /// @param _challenger2 The second of the two darknodes who submitted the challenge function slash(address _prover, address _challenger1, address _challenger2) external onlySlasher { uint256 penalty = store.darknodeBond(_prover) / 2; uint256 reward = penalty / 4; // Slash the bond of the failed prover in half store.updateDarknodeBond(_prover, penalty); // If the darknode has not been deregistered then deregister it if (isDeregisterable(_prover)) { store.updateDarknodeDeregisteredAt(_prover, currentEpoch.blocknumber + minimumEpochInterval); numDarknodesNextEpoch -= 1; emit LogDarknodeDeregistered(_prover); } // Reward the challengers with less than the penalty so that it is not // worth challenging yourself ren.transfer(store.darknodeOwner(_challenger1), reward); ren.transfer(store.darknodeOwner(_challenger2), reward); } /// @notice Refund the bond of a deregistered darknode. This will make the /// darknode available for registration again. Anyone can call this function /// but the bond will always be refunded to the darknode owner. /// /// @param _darknodeID The darknode ID that will be refunded. The caller /// of this method must be the owner of this darknode. function refund(address _darknodeID) external onlyRefundable(_darknodeID) { address darknodeOwner = store.darknodeOwner(_darknodeID); // Remember the bond amount uint256 amount = store.darknodeBond(_darknodeID); // Erase the darknode from the registry store.removeDarknode(_darknodeID); // Refund the owner by transferring REN ren.transfer(darknodeOwner, amount); // Emit an event. emit LogDarknodeOwnerRefunded(darknodeOwner, amount); } /// @notice Retrieves the address of the account that registered a darknode. /// @param _darknodeID The ID of the darknode to retrieve the owner for. function getDarknodeOwner(address _darknodeID) external view returns (address) { return store.darknodeOwner(_darknodeID); } /// @notice Retrieves the bond amount of a darknode in 10^-18 REN. /// @param _darknodeID The ID of the darknode to retrieve the bond for. function getDarknodeBond(address _darknodeID) external view returns (uint256) { return store.darknodeBond(_darknodeID); } /// @notice Retrieves the encryption public key of the darknode. /// @param _darknodeID The ID of the darknode to retrieve the public key for. function getDarknodePublicKey(address _darknodeID) external view returns (bytes) { return store.darknodePublicKey(_darknodeID); } /// @notice Retrieves a list of darknodes which are registered for the /// current epoch. /// @param _start A darknode ID used as an offset for the list. If _start is /// 0x0, the first dark node will be used. _start won't be /// included it is not registered for the epoch. /// @param _count The number of darknodes to retrieve starting from _start. /// If _count is 0, all of the darknodes from _start are /// retrieved. If _count is more than the remaining number of /// registered darknodes, the rest of the list will contain /// 0x0s. function getDarknodes(address _start, uint256 _count) external view returns (address[]) { uint256 count = _count; if (count == 0) { count = numDarknodes; } return getDarknodesFromEpochs(_start, count, false); } /// @notice Retrieves a list of darknodes which were registered for the /// previous epoch. See `getDarknodes` for the parameter documentation. function getPreviousDarknodes(address _start, uint256 _count) external view returns (address[]) { uint256 count = _count; if (count == 0) { count = numDarknodesPreviousEpoch; } return getDarknodesFromEpochs(_start, count, true); } /// @notice Returns whether a darknode is scheduled to become registered /// at next epoch. /// @param _darknodeID The ID of the darknode to return function isPendingRegistration(address _darknodeID) external view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); return registeredAt != 0 && registeredAt > currentEpoch.blocknumber; } /// @notice Returns if a darknode is in the pending deregistered state. In /// this state a darknode is still considered registered. function isPendingDeregistration(address _darknodeID) external view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return deregisteredAt != 0 && deregisteredAt > currentEpoch.blocknumber; } /// @notice Returns if a darknode is in the deregistered state. function isDeregistered(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return deregisteredAt != 0 && deregisteredAt <= currentEpoch.blocknumber; } /// @notice Returns if a darknode can be deregistered. This is true if the /// darknodes is in the registered state and has not attempted to /// deregister yet. function isDeregisterable(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); // The Darknode is currently in the registered state and has not been // transitioned to the pending deregistration, or deregistered, state return isRegistered(_darknodeID) && deregisteredAt == 0; } /// @notice Returns if a darknode is in the refunded state. This is true /// for darknodes that have never been registered, or darknodes that have /// been deregistered and refunded. function isRefunded(address _darknodeID) public view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return registeredAt == 0 && deregisteredAt == 0; } /// @notice Returns if a darknode is refundable. This is true for darknodes /// that have been in the deregistered state for one full epoch. function isRefundable(address _darknodeID) public view returns (bool) { return isDeregistered(_darknodeID) && store.darknodeDeregisteredAt(_darknodeID) <= previousEpoch.blocknumber; } /// @notice Returns if a darknode is in the registered state. function isRegistered(address _darknodeID) public view returns (bool) { return isRegisteredInEpoch(_darknodeID, currentEpoch); } /// @notice Returns if a darknode was in the registered state last epoch. function isRegisteredInPreviousEpoch(address _darknodeID) public view returns (bool) { return isRegisteredInEpoch(_darknodeID, previousEpoch); } /// @notice Returns if a darknode was in the registered state for a given /// epoch. /// @param _darknodeID The ID of the darknode /// @param _epoch One of currentEpoch, previousEpoch function isRegisteredInEpoch(address _darknodeID, Epoch _epoch) private view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); bool registered = registeredAt != 0 && registeredAt <= _epoch.blocknumber; bool notDeregistered = deregisteredAt == 0 || deregisteredAt > _epoch.blocknumber; // The Darknode has been registered and has not yet been deregistered, // although it might be pending deregistration return registered && notDeregistered; } /// @notice Returns a list of darknodes registered for either the current /// or the previous epoch. See `getDarknodes` for documentation on the /// parameters `_start` and `_count`. /// @param _usePreviousEpoch If true, use the previous epoch, otherwise use /// the current epoch. function getDarknodesFromEpochs(address _start, uint256 _count, bool _usePreviousEpoch) private view returns (address[]) { uint256 count = _count; if (count == 0) { count = numDarknodes; } address[] memory nodes = new address[](count); // Begin with the first node in the list uint256 n = 0; address next = _start; if (next == 0x0) { next = store.begin(); } // Iterate until all registered Darknodes have been collected while (n < count) { if (next == 0x0) { break; } // Only include Darknodes that are currently registered bool includeNext; if (_usePreviousEpoch) { includeNext = isRegisteredInPreviousEpoch(next); } else { includeNext = isRegistered(next); } if (!includeNext) { next = store.next(next); continue; } nodes[n] = next; next = store.next(next); n += 1; } return nodes; } } /** * @title Math * @dev Assorted math operations */ library Math { function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } /// @notice Implements safeTransfer, safeTransferFrom and /// safeApprove for CompatibleERC20. /// /// See https://github.com/ethereum/solidity/issues/4116 /// /// This library allows interacting with ERC20 tokens that implement any of /// these interfaces: /// /// (1) transfer returns true on success, false on failure /// (2) transfer returns true on success, reverts on failure /// (3) transfer returns nothing on success, reverts on failure /// /// Additionally, safeTransferFromWithFees will return the final token /// value received after accounting for token fees. library CompatibleERC20Functions { using SafeMath for uint256; /// @notice Calls transfer on the token and reverts if the call fails. function safeTransfer(address token, address to, uint256 amount) internal { CompatibleERC20(token).transfer(to, amount); require(previousReturnValue(), "transfer failed"); } /// @notice Calls transferFrom on the token and reverts if the call fails. function safeTransferFrom(address token, address from, address to, uint256 amount) internal { CompatibleERC20(token).transferFrom(from, to, amount); require(previousReturnValue(), "transferFrom failed"); } /// @notice Calls approve on the token and reverts if the call fails. function safeApprove(address token, address spender, uint256 amount) internal { CompatibleERC20(token).approve(spender, amount); require(previousReturnValue(), "approve failed"); } /// @notice Calls transferFrom on the token, reverts if the call fails and /// returns the value transferred after fees. function safeTransferFromWithFees(address token, address from, address to, uint256 amount) internal returns (uint256) { uint256 balancesBefore = CompatibleERC20(token).balanceOf(to); CompatibleERC20(token).transferFrom(from, to, amount); require(previousReturnValue(), "transferFrom failed"); uint256 balancesAfter = CompatibleERC20(token).balanceOf(to); return Math.min256(amount, balancesAfter.sub(balancesBefore)); } /// @notice Checks the return value of the previous function. Returns true /// if the previous function returned 32 non-zero bytes or returned zero /// bytes. function previousReturnValue() private pure returns (bool) { uint256 returnData = 0; assembly { /* solium-disable-line security/no-inline-assembly */ // Switch on the number of bytes returned by the previous call switch returndatasize // 0 bytes: ERC20 of type (3), did not throw case 0 { returnData := 1 } // 32 bytes: ERC20 of types (1) or (2) case 32 { // Copy the return data into scratch space returndatacopy(0x0, 0x0, 32) // Load the return data into returnData returnData := mload(0x0) } // Other return size: return false default { } } return returnData != 0; } } /// @notice ERC20 interface which doesn't specify the return type for transfer, /// transferFrom and approve. interface CompatibleERC20 { // Modified to not return boolean function transfer(address to, uint256 value) external; function transferFrom(address from, address to, uint256 value) external; function approve(address spender, uint256 value) external; // Not modifier 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); } /// @notice The DarknodeRewardVault contract is responsible for holding fees /// for darknodes for settling orders. Fees can be withdrawn to the address of /// the darknode's operator. Fees can be in ETH or in ERC20 tokens. /// Docs: https://github.com/republicprotocol/republic-sol/blob/master/docs/02-darknode-reward-vault.md contract DarknodeRewardVault is Ownable { using SafeMath for uint256; using CompatibleERC20Functions for CompatibleERC20; string public VERSION; // Passed in as a constructor parameter. /// @notice The special address for Ether. address constant public ETHEREUM = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; DarknodeRegistry public darknodeRegistry; mapping(address => mapping(address => uint256)) public darknodeBalances; event LogDarknodeRegistryUpdated(DarknodeRegistry previousDarknodeRegistry, DarknodeRegistry nextDarknodeRegistry); /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _darknodeRegistry The DarknodeRegistry contract that is used by /// the vault to lookup Darknode owners. constructor(string _VERSION, DarknodeRegistry _darknodeRegistry) public { VERSION = _VERSION; darknodeRegistry = _darknodeRegistry; } function updateDarknodeRegistry(DarknodeRegistry _newDarknodeRegistry) public onlyOwner { emit LogDarknodeRegistryUpdated(darknodeRegistry, _newDarknodeRegistry); darknodeRegistry = _newDarknodeRegistry; } /// @notice Deposit fees into the vault for a Darknode. The Darknode /// registration is not checked (to reduce gas fees); the caller must be /// careful not to call this function for a Darknode that is not registered /// otherwise any fees deposited to that Darknode can be withdrawn by a /// malicious adversary (by registering the Darknode before the honest /// party and claiming ownership). /// /// @param _darknode The address of the Darknode that will receive the /// fees. /// @param _token The address of the ERC20 token being used to pay the fee. /// A special address is used for Ether. /// @param _value The amount of fees in the smallest unit of the token. function deposit(address _darknode, ERC20 _token, uint256 _value) public payable { uint256 receivedValue = _value; if (address(_token) == ETHEREUM) { require(msg.value == _value, "mismatched ether value"); } else { require(msg.value == 0, "unexpected ether value"); receivedValue = CompatibleERC20(_token).safeTransferFromWithFees(msg.sender, address(this), _value); } darknodeBalances[_darknode][_token] = darknodeBalances[_darknode][_token].add(receivedValue); } /// @notice Withdraw fees earned by a Darknode. The fees will be sent to /// the owner of the Darknode. If a Darknode is not registered the fees /// cannot be withdrawn. /// /// @param _darknode The address of the Darknode whose fees are being /// withdrawn. The owner of this Darknode will receive the fees. /// @param _token The address of the ERC20 token to withdraw. function withdraw(address _darknode, ERC20 _token) public { address darknodeOwner = darknodeRegistry.getDarknodeOwner(address(_darknode)); require(darknodeOwner != 0x0, "invalid darknode owner"); uint256 value = darknodeBalances[_darknode][_token]; darknodeBalances[_darknode][_token] = 0; if (address(_token) == ETHEREUM) { darknodeOwner.transfer(value); } else { CompatibleERC20(_token).safeTransfer(darknodeOwner, value); } } }
* @dev Burns a specific amount of tokens. @param _value The amount of token to be burned./
function burn(uint256 _value) public { _burn(msg.sender, _value); }
13,722
[ 1, 38, 321, 87, 279, 2923, 3844, 434, 2430, 18, 225, 389, 1132, 1021, 3844, 434, 1147, 358, 506, 18305, 329, 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 ]
[ 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, 225, 445, 18305, 12, 11890, 5034, 389, 1132, 13, 1071, 288, 203, 565, 389, 70, 321, 12, 3576, 18, 15330, 16, 389, 1132, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x379E0ef89B21180661B7aCE7cE1b60A2Aa2304b6/sources/StakeLevel.sol
* check Is pool invalid or not/
modifier isInvalidPool(){ require( msg.sender==_contractCaller,"invalid pool address!"); _; } constructor() public
16,962,084
[ 1, 1893, 2585, 2845, 2057, 578, 486, 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, 9606, 353, 1941, 2864, 1435, 95, 203, 3639, 2583, 12, 1234, 18, 15330, 631, 67, 16351, 11095, 10837, 5387, 2845, 1758, 4442, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 3885, 1435, 203, 3639, 1071, 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 ]
pragma solidity >=0.5; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; interface IUserList { function isAddrRegistered(address _who) external view returns(bool); function isNickRegistered(bytes32 _nick) external view returns(bool); function isJobAddr(address _isAddrJob) external view returns(bool); } contract LovePropose is Ownable { IUserList public userList; struct Propose { address sender; address receiver; bytes32 infoHash; } Propose[] public lsPropose; string[] public lsComment; //Map ID Propose -> index list Propose: index = idToIndex - 1; mapping (bytes32 => uint) public idToIndex; //Map Propose: User -> Array Propose // mapping (address => uint[]) public userToPropose; event NewPropose(bytes32 _id, bytes32 infoHash); // Map comment: Propose ID -> Array comment mapping (bytes32 => uint[]) public proIdToComment; event NewComment(bytes32 proId, string commentHash); //Map like: Propose ID -> Array liker mapping (bytes32 => address[]) public mpLike; event NewLike(bytes32 _id, address sender); constructor (IUserList _userList) public { require(address(_userList) != address(0), "Contract UserList address must be different 0x0."); userList = _userList; } modifier onlyRegiter { require(userList.isAddrRegistered(msg.sender), "User must be regiter."); _; } modifier onlyJob { require(userList.isJobAddr(msg.sender), "Function only for job."); _; } function setUserList(IUserList _userList) public onlyOwner { userList = _userList; } function isOwnerPropose(address _who, bytes32 _id) public view returns(bool) { return (idToIndex[_id] != 0) && (_who == lsPropose[idToIndex[_id] - 1].sender || _who == lsPropose[idToIndex[_id] - 1].receiver); } // Send Propose. function addPropose(address _receiver, bytes32 _infoHash) public onlyRegiter { ///Do Sent Propose doAddPropose(byte(0), msg.sender, _receiver, _infoHash); } // Upload Propose. function uploadPropose(bytes32[] memory _id, address[] memory _sender, address[] memory _receiver, bytes32[] memory _infoHash) public onlyJob { uint len = _id.length; ///Do Sent Propose for (uint i = 0; i < len; i++) { doAddPropose(_id[i], _sender[i], _receiver[i], _infoHash[i]); } } function getAllPropose() public view returns(address[] memory lsSender, address[] memory lsReceiver, bytes32[] memory infoHash) { uint len = lsPropose.length; lsSender = new address[](len); lsReceiver = new address[](len); infoHash = new bytes32[](len); for (uint i = 0; i < len; i++) { lsSender[i] = lsPropose[i].sender; lsReceiver[i] = lsPropose[i].receiver; infoHash[i] = lsPropose[i].infoHash; } } // ****** Like ****** function sentLike(bytes32 _id) public { require(idToIndex[_id] != 0, "Propose id don't exist!"); //Add address liker to map mpLike[_id].push(msg.sender); emit NewLike(_id, msg.sender); } // ****** Comment ****** function addComment(bytes32 _id, string memory _commentHash) public { require(idToIndex[_id] != 0, "Propose id don't exist!"); uint id = lsComment.push(_commentHash) - 1; proIdToComment[_id].push(id); emit NewComment(_id, _commentHash); } // function getCommentByProID(bytes32 _id) public view returns (string memory commentHash) { uint len = proIdToComment[_id].length; bytes memory hashCollect; for (uint i = 0; i < len; i++) { hashCollect = abi.encodePacked(hashCollect, bytes(lsComment[proIdToComment[_id][i]]), byte(0));//byte(0) } commentHash = string(hashCollect); } // Do Send Propose. function doAddPropose(bytes32 _id, address _sender, address _receiver, bytes32 _infoHash) private { require(idToIndex[_id] == 0, "Propose id existed!"); require(_sender != _receiver, "Sender must be different with receiver address!"); //Create new pending Propose memory newPro = Propose(_sender, _receiver, _infoHash); uint index = lsPropose.push(newPro); if (_id == byte(0)) _id = bytes32(index); //Add ID mapping: index = idToIndex - 1; idToIndex[_id] = index; // userToPropose[_sender].push(index); // userToPropose[_receiver].push(index); //Rase event new pedding request. emit NewPropose(_id, _infoHash); } }
****** Like ******Add address liker to map
function sentLike(bytes32 _id) public { require(idToIndex[_id] != 0, "Propose id don't exist!"); mpLike[_id].push(msg.sender); emit NewLike(_id, msg.sender); }
15,846,619
[ 1, 8804, 1436, 1758, 7906, 264, 358, 852, 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, 3271, 8804, 12, 3890, 1578, 389, 350, 13, 1071, 288, 203, 3639, 2583, 12, 350, 19418, 63, 67, 350, 65, 480, 374, 16, 315, 626, 4150, 612, 2727, 1404, 1005, 4442, 1769, 203, 3639, 6749, 8804, 63, 67, 350, 8009, 6206, 12, 3576, 18, 15330, 1769, 203, 3639, 3626, 1166, 8804, 24899, 350, 16, 1234, 18, 15330, 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 ]
/* Copyright (c) 2018-present evan GmbH. 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. */ /* Copyright (c) 2018-present evan GmbH. 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. */ /* * Copyright 2018 Contractus GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.4.20; contract HelloWorld { // all data and code is visible to everyone, that's the point of the blockchain // the accessability indicators only affect writing changes and access syntax address public creator; string prompt; constructor() public { creator = tx.origin; } function setPrompt(string value) external { // the most basic form of access control // it just silently ignores any invalid access // proper exceptions would be better if (msg.sender == address(creator)) prompt = value; } // anything that is done in the blockchain costs gas (i.e. currency) // this function concatenates strings, which can be rather expensive // so whenever possible such utility functionality should be done outside the chain // the view modifier indicates that state is read, but not changed function hello(string salut) external view returns (bytes) { bytes memory tmp0 = bytes(prompt); bytes memory tmp1 = bytes(salut); string memory greeting = new string(tmp0.length + tmp1.length); bytes memory buffer = bytes(greeting); uint k = 0; for(uint i = 0; i < tmp0.length;) buffer[k++] = tmp0[i++]; for(i = 0; i < tmp1.length;) buffer[k++] = tmp1[i++]; return buffer; } }
all data and code is visible to everyone, that's the point of the blockchain the accessability indicators only affect writing changes and access syntax
contract HelloWorld { address public creator; string prompt; Copyright (c) 2018-present evan GmbH. Copyright (c) 2018-present evan GmbH. constructor() public { creator = tx.origin; } function setPrompt(string value) external { if (msg.sender == address(creator)) prompt = value; } function hello(string salut) external view returns (bytes) { bytes memory tmp0 = bytes(prompt); bytes memory tmp1 = bytes(salut); string memory greeting = new string(tmp0.length + tmp1.length); bytes memory buffer = bytes(greeting); uint k = 0; for(uint i = 0; i < tmp0.length;) buffer[k++] = tmp0[i++]; for(i = 0; i < tmp1.length;) buffer[k++] = tmp1[i++]; return buffer; } }
12,938,003
[ 1, 454, 501, 471, 981, 353, 6021, 358, 3614, 476, 16, 716, 1807, 326, 1634, 434, 326, 16766, 326, 2006, 2967, 27121, 1338, 13418, 7410, 3478, 471, 2006, 6279, 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, 20889, 18071, 288, 203, 225, 1758, 1071, 11784, 31, 203, 225, 533, 6866, 31, 203, 203, 225, 25417, 261, 71, 13, 14863, 17, 6706, 2113, 304, 611, 1627, 44, 18, 203, 203, 225, 25417, 261, 71, 13, 14863, 17, 6706, 2113, 304, 611, 1627, 44, 18, 203, 203, 203, 225, 3885, 1435, 1071, 288, 203, 565, 11784, 273, 2229, 18, 10012, 31, 203, 225, 289, 203, 21281, 225, 445, 444, 15967, 12, 1080, 460, 13, 3903, 288, 203, 565, 309, 261, 3576, 18, 15330, 422, 1758, 12, 20394, 3719, 6866, 273, 460, 31, 203, 225, 289, 203, 203, 225, 445, 19439, 12, 1080, 12814, 322, 13, 3903, 1476, 1135, 261, 3890, 13, 288, 203, 565, 1731, 3778, 1853, 20, 273, 1731, 12, 13325, 1769, 203, 565, 1731, 3778, 1853, 21, 273, 1731, 12, 21982, 322, 1769, 203, 565, 533, 3778, 5174, 21747, 273, 225, 394, 533, 12, 5645, 20, 18, 2469, 397, 1853, 21, 18, 2469, 1769, 203, 565, 1731, 3778, 1613, 273, 1731, 12, 75, 9015, 310, 1769, 203, 565, 2254, 417, 273, 374, 31, 203, 565, 364, 12, 11890, 277, 273, 374, 31, 277, 411, 1853, 20, 18, 2469, 30943, 1613, 63, 79, 9904, 65, 273, 1853, 20, 63, 77, 9904, 15533, 203, 565, 364, 12, 77, 273, 374, 31, 277, 411, 1853, 21, 18, 2469, 30943, 1613, 63, 79, 9904, 65, 273, 1853, 21, 63, 77, 9904, 15533, 203, 565, 327, 1613, 31, 203, 225, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) public hasMintPermission canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } // File: openzeppelin-solidity/contracts/token/ERC20/PausableToken.sol /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer( address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve( address _spender, uint256 _value ) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval( address _spender, uint _addedValue ) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval( address _spender, uint _subtractedValue ) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } // File: openzeppelin-solidity/contracts/token/ERC20/DetailedERC20.sol /** * @title DetailedERC20 token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } // File: openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } // File: openzeppelin-solidity/contracts/token/ERC20/StandardBurnableToken.sol /** * @title Standard Burnable Token * @dev Adds burnFrom method to ERC20 implementations */ contract StandardBurnableToken is BurnableToken, StandardToken { /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param _from address The address which you want to send tokens from * @param _value uint256 The amount of token to be burned */ function burnFrom(address _from, uint256 _value) public { require(_value <= allowed[_from][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); _burn(_from, _value); } } // File: contracts/RemeCoin.sol /** * @title RemeCoin * @author https://bit-sentinel.com */ contract RemeCoin is MintableToken, PausableToken, StandardBurnableToken, DetailedERC20 { event EnabledFees(); event DisabledFees(); event FeeChanged(uint256 fee); event FeeThresholdChanged(uint256 feeThreshold); event FeeBeneficiaryChanged(address indexed feeBeneficiary); event EnabledWhitelist(); event DisabledWhitelist(); event ChangedWhitelistManager(address indexed whitelistManager); event AddedRecipientToWhitelist(address indexed recipient); event AddedSenderToWhitelist(address indexed sender); event RemovedRecipientFromWhitelist(address indexed recipient); event RemovedSenderFromWhitelist(address indexed sender); // If the token whitelist feature is enabled or not. bool public whitelist = true; // Address of the whitelist manager. address public whitelistManager; // Addresses that can receive tokens. mapping(address => bool) public whitelistedRecipients; // Addresses that can send tokens. mapping(address => bool) public whitelistedSenders; // Fee taken from transfers. uint256 public fee; // If the fee mechanism is enabled. bool public feesEnabled; // Address of the fee beneficiary. address public feeBeneficiary; // Value from which the fee mechanism applies. uint256 public feeThreshold; /** * @dev Initialize the RemeCoin and transfer the initialBalance to the * initialAccount. * @param _initialAccount The account that will receive the initial balance. * @param _initialBalance The initial balance of tokens. * @param _fee uint256 The fee percentage to be applied. Has 4 decimals. * @param _feeBeneficiary address The beneficiary of the fees. * @param _feeThreshold uint256 The amount of when the transfers fees will be applied. */ constructor( address _initialAccount, uint256 _initialBalance, uint256 _fee, address _feeBeneficiary, uint256 _feeThreshold ) DetailedERC20("REME Coin", "REME", 18) public { require(_fee != uint256(0) && _fee <= uint256(100 * (10 ** 4))); require(_feeBeneficiary != address(0)); require(_feeThreshold != uint256(0)); fee = _fee; feeBeneficiary = _feeBeneficiary; feeThreshold = _feeThreshold; totalSupply_ = _initialBalance; balances[_initialAccount] = _initialBalance; emit Transfer(address(0), _initialAccount, _initialBalance); } /** * @dev Throws if called by any account other than the whitelistManager. */ modifier onlyWhitelistManager() { require(msg.sender == whitelistManager); _; } /** * @dev Modifier to make a function callable only when the contract has transfer fees enabled. */ modifier whenFeesEnabled() { require(feesEnabled); _; } /** * @dev Modifier to make a function callable only when the contract has transfer fees disabled. */ modifier whenFeesDisabled() { require(!feesEnabled); _; } /** * @dev Enable the whitelist feature. */ function enableWhitelist() external onlyOwner { require( !whitelist, 'Whitelist is already enabled' ); whitelist = true; emit EnabledWhitelist(); } /** * @dev Enable the whitelist feature. */ function disableWhitelist() external onlyOwner { require( whitelist, 'Whitelist is already disabled' ); whitelist = false; emit DisabledWhitelist(); } /** * @dev Change the whitelist manager address. * @param _whitelistManager address */ function changeWhitelistManager(address _whitelistManager) external onlyOwner { require(_whitelistManager != address(0)); whitelistManager = _whitelistManager; emit ChangedWhitelistManager(whitelistManager); } /** * @dev Add recipient to the whitelist. * @param _recipient address of the recipient */ function addRecipientToWhitelist(address _recipient) external onlyWhitelistManager { require( !whitelistedRecipients[_recipient], 'Recipient already whitelisted' ); whitelistedRecipients[_recipient] = true; emit AddedRecipientToWhitelist(_recipient); } /** * @dev Add sender to the whitelist. * @param _sender address of the sender */ function addSenderToWhitelist(address _sender) external onlyWhitelistManager { require( !whitelistedSenders[_sender], 'Sender already whitelisted' ); whitelistedSenders[_sender] = true; emit AddedSenderToWhitelist(_sender); } /** * @dev Remove recipient from the whitelist. * @param _recipient address of the recipient */ function removeRecipientFromWhitelist(address _recipient) external onlyWhitelistManager { require( whitelistedRecipients[_recipient], 'Recipient not whitelisted' ); whitelistedRecipients[_recipient] = false; emit RemovedRecipientFromWhitelist(_recipient); } /** * @dev Remove sender from the whitelist. * @param _sender address of the sender */ function removeSenderFromWhitelist(address _sender) external onlyWhitelistManager { require( whitelistedSenders[_sender], 'Sender not whitelisted' ); whitelistedSenders[_sender] = false; emit RemovedSenderFromWhitelist(_sender); } /** * @dev Called by owner to enable fee take */ function enableFees() external onlyOwner whenFeesDisabled { feesEnabled = true; emit EnabledFees(); } /** * @dev Called by owner to disable fee take */ function disableFees() external onlyOwner whenFeesEnabled { feesEnabled = false; emit DisabledFees(); } /** * @dev Called by owner to set fee percentage. * @param _fee uint256 The new fee percentage. */ function setFee(uint256 _fee) external onlyOwner { require(_fee != uint256(0) && _fee <= 100 * (10 ** 4)); fee = _fee; emit FeeChanged(fee); } /** * @dev Called by owner to set fee beeneficiary. * @param _feeBeneficiary address The new fee beneficiary. */ function setFeeBeneficiary(address _feeBeneficiary) external onlyOwner { require(_feeBeneficiary != address(0)); feeBeneficiary = _feeBeneficiary; emit FeeBeneficiaryChanged(feeBeneficiary); } /** * @dev Called by owner to set fee threshold. * @param _feeThreshold uint256 The new fee threshold. */ function setFeeThreshold(uint256 _feeThreshold) external onlyOwner { require(_feeThreshold != uint256(0)); feeThreshold = _feeThreshold; emit FeeThresholdChanged(feeThreshold); } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { if (whitelist) { require ( whitelistedSenders[msg.sender] || whitelistedRecipients[_to] || msg.sender == owner || _to == owner, 'Sender or recipient not whitelisted' ); } uint256 _feeTaken; if (msg.sender != owner && msg.sender != feeBeneficiary) { (_feeTaken, _value) = applyFees(_value); } if (_feeTaken > 0) { require (super.transfer(feeBeneficiary, _feeTaken) && super.transfer(_to, _value)); return true; } return super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { if (whitelist) { require ( whitelistedSenders[_from] || whitelistedRecipients[_to] || _from == owner || _to == owner, 'Sender or recipient not whitelisted' ); } uint256 _feeTaken; (_feeTaken, _value) = applyFees(_value); if (_feeTaken > 0) { require (super.transferFrom(_from, feeBeneficiary, _feeTaken) && super.transferFrom(_from, _to, _value)); return true; } return super.transferFrom(_from, _to, _value); } /** * @dev Called internally for applying fees to the transfer value. * @param _value uint256 */ function applyFees(uint256 _value) internal view returns (uint256 _feeTaken, uint256 _revisedValue) { _revisedValue = _value; if (feesEnabled && _revisedValue >= feeThreshold) { _feeTaken = _revisedValue.mul(fee).div(uint256(100 * (10 ** 4))); _revisedValue = _revisedValue.sub(_feeTaken); } } }
* @dev Called by owner to set fee beeneficiary. @param _feeBeneficiary address The new fee beneficiary./
function setFeeBeneficiary(address _feeBeneficiary) external onlyOwner { require(_feeBeneficiary != address(0)); feeBeneficiary = _feeBeneficiary; emit FeeBeneficiaryChanged(feeBeneficiary); }
5,385,503
[ 1, 8185, 635, 3410, 358, 444, 14036, 2118, 10241, 14463, 814, 18, 225, 389, 21386, 38, 4009, 74, 14463, 814, 1758, 1021, 394, 14036, 27641, 74, 14463, 814, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 444, 14667, 38, 4009, 74, 14463, 814, 12, 2867, 389, 21386, 38, 4009, 74, 14463, 814, 13, 203, 3639, 3903, 203, 3639, 1338, 5541, 203, 565, 288, 203, 3639, 2583, 24899, 21386, 38, 4009, 74, 14463, 814, 480, 1758, 12, 20, 10019, 203, 3639, 14036, 38, 4009, 74, 14463, 814, 273, 389, 21386, 38, 4009, 74, 14463, 814, 31, 203, 3639, 3626, 30174, 38, 4009, 74, 14463, 814, 5033, 12, 21386, 38, 4009, 74, 14463, 814, 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 ]
/** * SPDX-License-Identifier: MIT * @authors: @ferittuncer * @reviewers: [@shalzz*, @jaybuidl] * @auditors: [] * @bounties: [] * @deployments: [] */ pragma solidity ^0.8.10; import "@kleros/dispute-resolver-interface-contract/contracts/IDisputeResolver.sol"; import "./IProveMeWrong.sol"; /* ·---------------------------------------|---------------------------|--------------|-----------------------------· | Solc version: 0.8.10 · Optimizer enabled: true · Runs: 1000 · Block limit: 30000000 gas │ ········································|···························|··············|······························ | Methods · 100 gwei/gas · 4218.94 usd/eth │ ·················|······················|·············|·············|··············|···············|·············· | Contract · Method · Min · Max · Avg · # calls · usd (avg) │ ·················|······················|·············|·············|··············|···············|·············· | Arbitrator · createDispute · 82579 · 99679 · 84289 · 20 · 35.56 │ ·················|······················|·············|·············|··············|···············|·············· | Arbitrator · executeRuling · - · - · 66719 · 3 · 28.15 │ ·················|······················|·············|·············|··············|···············|·············· | Arbitrator · giveRuling · 78640 · 98528 · 93556 · 4 · 39.47 │ ·················|······················|·············|·············|··············|···············|·············· | ProveMeWrong · challenge · - · - · 147901 · 3 · 62.40 │ ·················|······················|·············|·············|··············|···············|·············· | ProveMeWrong · fundAppeal · 133525 · 138580 · 135547 · 5 · 57.19 │ ·················|······················|·············|·············|··············|···············|·············· | ProveMeWrong · increaseBounty · - · - · 28602 · 2 · 12.07 │ ·················|······················|·············|·············|··············|···············|·············· | ProveMeWrong · initializeClaim · 31655 · 51060 · 38956 · 10 · 16.44 │ ·················|······················|·············|·············|··············|···············|·············· | ProveMeWrong · initiateWithdrawal · - · - · 28085 · 4 · 11.85 │ ·················|······················|·············|·············|··············|···············|·············· | ProveMeWrong · submitEvidence · - · - · 26117 · 2 · 11.02 │ ·················|······················|·············|·············|··············|···············|·············· | ProveMeWrong · withdraw · 28403 · 35103 · 30636 · 3 · 12.93 │ ·················|······················|·············|·············|··············|···············|·············· | Deployments · · % of limit · │ ········································|·············|·············|··············|···············|·············· | Arbitrator · - · - · 877877 · 2.9 % · 370.37 │ ········································|·············|·············|··············|···············|·············· | ProveMeWrong · - · - · 2322785 · 7.7 % · 979.97 │ ·---------------------------------------|-------------|-------------|--------------|---------------|-------------· */ /** @title Prove Me Wrong @notice Smart contract for a type of curation, where submitted items are on hold until they are withdrawn and the amount of security deposits are determined by submitters. @dev Claims are not addressed with their identifiers. That enables us to reuse same storage address for another claim later. Arbitrator and the extra data is fixed. Also the metaevidence. Deploy another contract to change them. We prevent claims to get withdrawn immediately. This is to prevent submitter to escape punishment in case someone discovers an argument to debunk the claim. Bounty amounts are compressed with a lossy compression method to save on storage cost. */ contract ProveMeWrong is IProveMeWrong, IArbitrable, IEvidence { IArbitrator public immutable ARBITRATOR; uint256 public constant NUMBER_OF_RULING_OPTIONS = 2; uint256 public constant NUMBER_OF_LEAST_SIGNIFICANT_BITS_TO_IGNORE = 32; // To compress bounty amount to gain space in struct. Lossy compression. uint256 public immutable WINNER_STAKE_MULTIPLIER; // Multiplier of the arbitration cost that the winner has to pay as fee stake for a round in basis points. uint256 public immutable LOSER_STAKE_MULTIPLIER; // Multiplier of the arbitration cost that the loser has to pay as fee stake for a round in basis points. uint256 public constant LOSER_APPEAL_PERIOD_MULTIPLIER = 5000; // Multiplier of the appeal period for losers (any other ruling options) in basis points. The loser is given less time to fund its appeal to defend against last minute appeal funding attacks. uint256 public constant MULTIPLIER_DENOMINATOR = 10000; // Denominator for multipliers. struct DisputeData { address payable challenger; RulingOptions outcome; bool resolved; // To remove dependency to disputeStatus function of arbitrator. This function is likely to be removed in Kleros v2. uint80 claimStorageAddress; // 2^16 is sufficient. Just using extra available space. Round[] rounds; // Tracks each appeal round of a dispute. } struct Round { mapping(address => mapping(RulingOptions => uint256)) contributions; mapping(RulingOptions => bool) hasPaid; // True if the fees for this particular answer has been fully paid in the form hasPaid[rulingOutcome]. mapping(RulingOptions => uint256) totalPerRuling; uint256 totalClaimableAfterExpenses; } struct Claim { address payable owner; uint32 withdrawalPermittedAt; // Overflows in year 2106. uint64 bountyAmount; // 32-bits compression. Decompressed size is 96 bits. Can be shrinked to uint48 with 40-bits compression in case we need space for another field. } bytes public ARBITRATOR_EXTRA_DATA; // Immutable. mapping(uint80 => Claim) public claimStorage; // Key: Storage address of claim. Claims are not addressed with their identifiers, to enable reusing a storage slot. mapping(uint256 => DisputeData) disputes; // Key: Dispute ID as in arbitrator. constructor( IArbitrator _arbitrator, bytes memory _arbitratorExtraData, string memory _metaevidenceIpfsUri, uint256 _claimWithdrawalTimelock, uint256 _winnerStakeMultiplier, uint256 _loserStakeMultiplier ) IProveMeWrong(_claimWithdrawalTimelock) { ARBITRATOR = _arbitrator; ARBITRATOR_EXTRA_DATA = _arbitratorExtraData; WINNER_STAKE_MULTIPLIER = _winnerStakeMultiplier; LOSER_STAKE_MULTIPLIER = _loserStakeMultiplier; emit MetaEvidence(0, _metaevidenceIpfsUri); // Metaevidence is constant. Deploy another contract for another metaevidence. } /** @notice Initializes a claim. @param _claimID Unique identifier of a claim. Usually an IPFS content identifier. @param _searchPointer Starting point of the search. Find a vacant storage slot before calling this function to minimize gas cost. */ function initializeClaim(string calldata _claimID, uint80 _searchPointer) external payable override { Claim storage claim; do { claim = claimStorage[_searchPointer++]; } while (claim.bountyAmount != 0); claim.owner = payable(msg.sender); claim.bountyAmount = uint64(msg.value >> NUMBER_OF_LEAST_SIGNIFICANT_BITS_TO_IGNORE); require(claim.bountyAmount > 0, "You can't initialize a claim without putting a bounty."); uint256 claimStorageAddress = _searchPointer - 1; emit NewClaim(_claimID, claimStorageAddress); emit BalanceUpdate(claimStorageAddress, uint256(claim.bountyAmount) << NUMBER_OF_LEAST_SIGNIFICANT_BITS_TO_IGNORE); } /** @notice Lets you submit evidence as defined in evidence (ERC-1497) standard. @param _disputeID Dispute ID as in arbitrator. @param _evidenceURI IPFS content identifier of the evidence. */ function submitEvidence(uint256 _disputeID, string calldata _evidenceURI) external override { emit Evidence(ARBITRATOR, _disputeID, msg.sender, _evidenceURI); } /** @notice Lets you increase a bounty of a live claim. @param _claimStorageAddress The address of the claim in the storage. */ function increaseBounty(uint80 _claimStorageAddress) external payable override { Claim storage claim = claimStorage[_claimStorageAddress]; require(msg.sender == claim.owner, "Only claimant can increase bounty of a claim."); // To prevent mistakes. claim.bountyAmount += uint64(msg.value >> NUMBER_OF_LEAST_SIGNIFICANT_BITS_TO_IGNORE); emit BalanceUpdate(_claimStorageAddress, uint256(claim.bountyAmount) << NUMBER_OF_LEAST_SIGNIFICANT_BITS_TO_IGNORE); } /** @notice Lets a claimant to start withdrawal process. @dev withdrawalPermittedAt has some special values: 0 indicates withdrawal possible but process not started yet, max value indicates there is a challenge and during challenge it's forbidden to start withdrawal process. @param _claimStorageAddress The address of the claim in the storage. */ function initiateWithdrawal(uint80 _claimStorageAddress) external override { Claim storage claim = claimStorage[_claimStorageAddress]; require(msg.sender == claim.owner, "Only claimant can withdraw a claim."); require(claim.withdrawalPermittedAt == 0, "Withdrawal already initiated or there is a challenge."); claim.withdrawalPermittedAt = uint32(block.timestamp + CLAIM_WITHDRAWAL_TIMELOCK); emit TimelockStarted(_claimStorageAddress); } /** @notice Executes a withdrawal. Can only be executed by claimant. @dev withdrawalPermittedAt has some special values: 0 indicates withdrawal possible but process not started yet, max value indicates there is a challenge and during challenge it's forbidden to start withdrawal process. @param _claimStorageAddress The address of the claim in the storage. */ function withdraw(uint80 _claimStorageAddress) external override { Claim storage claim = claimStorage[_claimStorageAddress]; require(msg.sender == claim.owner, "Only claimant can withdraw a claim."); require(claim.withdrawalPermittedAt != 0, "You need to initiate withdrawal first."); require(claim.withdrawalPermittedAt <= block.timestamp, "You need to wait for timelock or wait until the challenge ends."); uint256 withdrawal = uint96(claim.bountyAmount) << NUMBER_OF_LEAST_SIGNIFICANT_BITS_TO_IGNORE; claim.bountyAmount = 0; // This is critical to reset. claim.withdrawalPermittedAt = 0; // This too, otherwise new claim inside the same slot can withdraw instantly. payable(msg.sender).transfer(withdrawal); emit Withdrew(_claimStorageAddress); } /** @notice Challenges the claim at the given storage address. Follow events to find out which claim resides in which slot. @dev withdrawalPermittedAt has some special values: 0 indicates withdrawal possible but process not started yet, max value indicates there is a challenge and during challenge it's forbidden to start another challenge. @param _claimStorageAddress The address of the claim in the storage. */ function challenge(uint80 _claimStorageAddress) public payable override { Claim storage claim = claimStorage[_claimStorageAddress]; require(claim.withdrawalPermittedAt != type(uint32).max, "There is an ongoing challenge."); claim.withdrawalPermittedAt = type(uint32).max; // Mark as challenged. require(claim.bountyAmount > 0, "Nothing to challenge."); // To prevent mistakes. uint256 disputeID = ARBITRATOR.createDispute{value: msg.value}(NUMBER_OF_RULING_OPTIONS, ARBITRATOR_EXTRA_DATA); disputes[disputeID].challenger = payable(msg.sender); disputes[disputeID].rounds.push(); disputes[disputeID].claimStorageAddress = uint80(_claimStorageAddress); // Evidence group ID is dispute ID. emit Dispute(ARBITRATOR, disputeID, 0, disputeID); // This event links the dispute to a claim storage address. emit Challenge(_claimStorageAddress, msg.sender, disputeID); } /** @notice Lets you fund a crowdfunded appeal. In case of funding is incomplete, you will be refunded. Withdrawal will be carried out using withdrawFeesAndRewards function. @param _disputeID The dispute ID as in the arbitrator. @param _supportedRuling The supported ruling in this funding. */ function fundAppeal(uint256 _disputeID, RulingOptions _supportedRuling) external payable override returns (bool fullyFunded) { DisputeData storage dispute = disputes[_disputeID]; RulingOptions currentRuling = RulingOptions(ARBITRATOR.currentRuling(_disputeID)); uint256 basicCost; uint256 totalCost; { (uint256 appealWindowStart, uint256 appealWindowEnd) = ARBITRATOR.appealPeriod(_disputeID); uint256 multiplier; if (_supportedRuling == currentRuling) { require(block.timestamp < appealWindowEnd, "Funding must be made within the appeal period."); multiplier = WINNER_STAKE_MULTIPLIER; } else { require( block.timestamp < (appealWindowStart + ((appealWindowEnd - appealWindowStart) / 2)), "Funding must be made within the first half appeal period." ); multiplier = LOSER_STAKE_MULTIPLIER; } basicCost = ARBITRATOR.appealCost(_disputeID, ARBITRATOR_EXTRA_DATA); totalCost = basicCost + ((basicCost * (multiplier)) / MULTIPLIER_DENOMINATOR); } RulingOptions supportedRulingOutcome = RulingOptions(_supportedRuling); uint256 lastRoundIndex = dispute.rounds.length - 1; Round storage lastRound = dispute.rounds[lastRoundIndex]; require(!lastRound.hasPaid[supportedRulingOutcome], "Appeal fee has already been paid."); uint256 contribution; { uint256 paidSoFar = lastRound.totalPerRuling[supportedRulingOutcome]; if (paidSoFar >= totalCost) { contribution = 0; // This can happen if arbitration fee gets lowered in between contributions. } else { contribution = totalCost - paidSoFar > msg.value ? msg.value : totalCost - paidSoFar; } } emit Contribution(_disputeID, lastRoundIndex, _supportedRuling, msg.sender, contribution); lastRound.contributions[msg.sender][supportedRulingOutcome] += contribution; lastRound.totalPerRuling[supportedRulingOutcome] += contribution; if (lastRound.totalPerRuling[supportedRulingOutcome] >= totalCost) { lastRound.totalClaimableAfterExpenses += lastRound.totalPerRuling[supportedRulingOutcome]; lastRound.hasPaid[supportedRulingOutcome] = true; emit RulingFunded(_disputeID, lastRoundIndex, _supportedRuling); } if (lastRound.hasPaid[RulingOptions.ChallengeFailed] && lastRound.hasPaid[RulingOptions.Debunked]) { dispute.rounds.push(); lastRound.totalClaimableAfterExpenses -= basicCost; ARBITRATOR.appeal{value: basicCost}(_disputeID, ARBITRATOR_EXTRA_DATA); } // Ignoring failure condition deliberately. if (msg.value - contribution > 0) payable(msg.sender).send(msg.value - contribution); return lastRound.hasPaid[supportedRulingOutcome]; } /** @notice For arbitrator to call, to execute it's ruling. In case arbitrator rules in favor of challenger, challenger wins the bounty. In any case, withdrawalPermittedAt will be reset. @param _disputeID The dispute ID as in the arbitrator. @param _ruling The ruling that arbitrator gave. */ function rule(uint256 _disputeID, uint256 _ruling) external override { require(IArbitrator(msg.sender) == ARBITRATOR); DisputeData storage dispute = disputes[_disputeID]; Round storage lastRound = dispute.rounds[dispute.rounds.length - 1]; // Appeal overrides arbitrator ruling. If a ruling option was not fully funded and the counter ruling option was funded, funded ruling option wins by default. RulingOptions wonByDefault; if (lastRound.hasPaid[RulingOptions.ChallengeFailed]) { wonByDefault = RulingOptions.ChallengeFailed; } else if (!lastRound.hasPaid[RulingOptions.ChallengeFailed]) { wonByDefault = RulingOptions.Debunked; } RulingOptions actualRuling = wonByDefault != RulingOptions.Tied ? wonByDefault : RulingOptions(_ruling); dispute.outcome = actualRuling; uint80 claimStorageAddress = dispute.claimStorageAddress; Claim storage claim = claimStorage[claimStorageAddress]; if (actualRuling == RulingOptions.Debunked) { uint256 bounty = uint96(claim.bountyAmount) << NUMBER_OF_LEAST_SIGNIFICANT_BITS_TO_IGNORE; claim.bountyAmount = 0; emit Debunked(claimStorageAddress); disputes[_disputeID].challenger.send(bounty); // Ignoring failure condition deliberately. } // In case of tie, claim stands. claim.withdrawalPermittedAt = 0; // Unmark as challenged. dispute.resolved = true; emit Ruling(IArbitrator(msg.sender), _disputeID, _ruling); } /** @notice Allows to withdraw any rewards or reimbursable fees after the dispute gets resolved. For all rounds at once. This function has O(m) time complexity where m is number of rounds. It is safe to assume m is always less than 10 as appeal cost growth order is O(2^m). @param _disputeID ID of the dispute as in arbitrator. @param _contributor The address whose rewards to withdraw. @param _ruling Ruling that received contributions from contributor. */ function withdrawFeesAndRewardsForAllRounds( uint256 _disputeID, address payable _contributor, RulingOptions _ruling ) external override { DisputeData storage dispute = disputes[_disputeID]; uint256 noOfRounds = dispute.rounds.length; for (uint256 roundNumber = 0; roundNumber < noOfRounds; roundNumber++) { withdrawFeesAndRewards(_disputeID, _contributor, roundNumber, _ruling); } } /** @notice Allows to withdraw any reimbursable fees or rewards after the dispute gets solved. @param _disputeID ID of the dispute as in arbitrator. @param _contributor The address whose rewards to withdraw. @param _roundNumber The number of the round caller wants to withdraw from. @param _ruling Ruling that received contribution from contributor. @return amount The amount available to withdraw for given question, contributor, round number and ruling option. */ function withdrawFeesAndRewards( uint256 _disputeID, address payable _contributor, uint256 _roundNumber, RulingOptions _ruling ) public override returns (uint256 amount) { DisputeData storage dispute = disputes[_disputeID]; require(dispute.resolved, "There is no ruling yet."); Round storage round = dispute.rounds[_roundNumber]; amount = getWithdrawableAmount(round, _contributor, _ruling, dispute.outcome); if (amount != 0) { round.contributions[_contributor][RulingOptions(_ruling)] = 0; _contributor.send(amount); // Ignoring failure condition deliberately. emit Withdrawal(_disputeID, _roundNumber, _ruling, _contributor, amount); } } /** @notice Lets you to transfer ownership of a claim. This is useful when you want to change owner account without withdrawing and resubmitting. */ function transferOwnership(uint80 _claimStorageAddress, address payable _newOwner) external override { Claim storage claim = claimStorage[_claimStorageAddress]; require(msg.sender == claim.owner, "Only claimant can transfer ownership."); claim.owner = _newOwner; } /** @notice Returns the total amount needs to be paid to challenge a claim. */ function challengeFee() external view override returns (uint256 arbitrationFee) { arbitrationFee = ARBITRATOR.arbitrationCost(ARBITRATOR_EXTRA_DATA); } /** @notice Returns the total amount needs to be paid to appeal a dispute. */ function appealFee(uint256 _disputeID) external view override returns (uint256 arbitrationFee) { arbitrationFee = ARBITRATOR.appealCost(_disputeID, ARBITRATOR_EXTRA_DATA); } /** @notice Helper function to find a vacant slot for claim. Use this function before calling initialize to minimize your gas cost. */ function findVacantStorageSlot(uint80 _searchPointer) external view override returns (uint256 vacantSlotIndex) { Claim storage claim; do { claim = claimStorage[_searchPointer++]; } while (claim.bountyAmount != 0); return _searchPointer - 1; } /** @notice Returns the sum of withdrawable amount. This function has O(m) time complexity where m is number of rounds. It is safe to assume m is always less than 10 as appeal cost growth order is O(m^2). */ function getTotalWithdrawableAmount( uint256 _disputeID, address payable _contributor, RulingOptions _ruling ) external view override returns (uint256 sum) { DisputeData storage dispute = disputes[_disputeID]; if (!dispute.resolved) return 0; uint256 noOfRounds = dispute.rounds.length; RulingOptions finalRuling = dispute.outcome; for (uint256 roundNumber = 0; roundNumber < noOfRounds; roundNumber++) { Round storage round = dispute.rounds[roundNumber]; sum += getWithdrawableAmount(round, _contributor, _ruling, finalRuling); } } /** @notice Returns withdrawable amount for given parameters. */ function getWithdrawableAmount( Round storage _round, address _contributor, RulingOptions _ruling, RulingOptions _finalRuling ) internal view returns (uint256 amount) { RulingOptions givenRuling = RulingOptions(_ruling); if (!_round.hasPaid[givenRuling]) { // Allow to reimburse if funding was unsuccessful for this ruling option. amount = _round.contributions[_contributor][givenRuling]; } else { // Funding was successful for this ruling option. if (_ruling == _finalRuling) { // This ruling option is the ultimate winner. amount = _round.totalPerRuling[givenRuling] > 0 ? (_round.contributions[_contributor][givenRuling] * _round.totalClaimableAfterExpenses) / _round.totalPerRuling[givenRuling] : 0; } else if (!_round.hasPaid[RulingOptions(_finalRuling)]) { // The ultimate winner was not funded in this round. Contributions discounting the appeal fee are reimbursed proportionally. amount = (_round.contributions[_contributor][givenRuling] * _round.totalClaimableAfterExpenses) / (_round.totalPerRuling[RulingOptions.ChallengeFailed] + _round.totalPerRuling[RulingOptions.Debunked]); } } } }
Ignoring failure condition deliberately.
disputes[_disputeID].challenger.send(bounty);
12,964,496
[ 1, 21702, 5166, 2269, 1464, 14776, 5173, 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, 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, 1377, 1015, 458, 281, 63, 67, 2251, 2507, 734, 8009, 343, 7862, 693, 18, 4661, 12, 70, 592, 93, 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 ]
./full_match/5/0x48b10b2540bAfA2e3903538487155643CA4d89B3/sources/project_/contracts/Crowdsale.sol
* @dev Determines how ETH is stored/forwarded on purchases./
function _forwardFunds() internal { payable(wallet).transfer(msg.value); }
7,085,119
[ 1, 10114, 3661, 512, 2455, 353, 4041, 19, 1884, 11804, 603, 5405, 343, 3304, 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 ]
[ 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, 565, 445, 389, 11565, 42, 19156, 1435, 2713, 288, 203, 3639, 8843, 429, 12, 19177, 2934, 13866, 12, 3576, 18, 1132, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x6A110a68aD7bb1734603BC28B82c0c9AFf98bc81/sources/FeeManager.sol
* @dev Function to verify claim params, make sure the link is not claimed or canceled and proxy is allowed to spend token @param _weiAmount Amount of wei to be claimed @param _nftAddress NFT address @param _tokenId Token id to be claimed @param _expiration Unix timestamp of link expiration time @param _linkId Address corresponding to link key @param _linkdropMaster Address corresponding to linkdrop master key @param _campaignId Campaign id @param _linkdropSignerSignature ECDSA signature of linkdrop signer @param _receiver Address of linkdrop receiver @param _receiverSignature ECDSA signature of linkdrop receiver @return True if success/ Make sure proxy contract is deployed
{ require(isDeployed(_linkdropMaster, _campaignId), "LINKDROP_PROXY_CONTRACT_NOT_DEPLOYED"); return ILinkdropERC721(deployed[salt(_linkdropMaster, _campaignId)]).checkClaimParamsERC721 ( _weiAmount, _nftAddress, _tokenId, _expiration, _linkId, _linkdropSignerSignature, _receiver, _receiverSignature ); }
16,757,591
[ 1, 2083, 358, 3929, 7516, 859, 16, 1221, 3071, 326, 1692, 353, 486, 7516, 329, 578, 17271, 471, 2889, 353, 2935, 358, 17571, 1147, 225, 389, 1814, 77, 6275, 16811, 434, 732, 77, 358, 506, 7516, 329, 225, 389, 82, 1222, 1887, 423, 4464, 1758, 225, 389, 2316, 548, 3155, 612, 358, 506, 7516, 329, 225, 389, 19519, 9480, 2858, 434, 1692, 7686, 813, 225, 389, 1232, 548, 5267, 4656, 358, 1692, 498, 225, 389, 1232, 7285, 7786, 5267, 4656, 358, 1692, 7285, 4171, 498, 225, 389, 14608, 548, 17820, 612, 225, 389, 1232, 7285, 15647, 5374, 7773, 19748, 3372, 434, 1692, 7285, 10363, 225, 389, 24454, 5267, 434, 1692, 7285, 5971, 225, 389, 24454, 5374, 7773, 19748, 3372, 434, 1692, 7285, 5971, 327, 1053, 309, 2216, 19, 4344, 3071, 2889, 6835, 353, 19357, 2, 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, 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 ]
[ 1, 565, 288, 203, 3639, 2583, 12, 291, 31954, 24899, 1232, 7285, 7786, 16, 389, 14608, 548, 3631, 315, 10554, 18768, 67, 16085, 67, 6067, 2849, 1268, 67, 4400, 67, 1639, 22971, 2056, 8863, 203, 203, 3639, 327, 467, 2098, 7285, 654, 39, 27, 5340, 12, 12411, 329, 63, 5759, 24899, 1232, 7285, 7786, 16, 389, 14608, 548, 25887, 2934, 1893, 9762, 1370, 654, 39, 27, 5340, 203, 3639, 261, 203, 5411, 389, 1814, 77, 6275, 16, 203, 5411, 389, 82, 1222, 1887, 16, 203, 5411, 389, 2316, 548, 16, 203, 5411, 389, 19519, 16, 203, 5411, 389, 1232, 548, 16, 203, 5411, 389, 1232, 7285, 15647, 5374, 16, 203, 5411, 389, 24454, 16, 203, 5411, 389, 24454, 5374, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.8; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } /** * @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 payable private _owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { _owner = msg.sender; } /** * @return the address of the owner. */ function owner() public view returns(address payable) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == msg.sender); _; } } /** * @title ERC20 interface */ interface ERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address tokenOwner, address spender) 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); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed tokenOwner, address indexed spender, uint256 value ); } contract LTLNN is ERC20, Ownable { using SafeMath for uint256; string public name = "Lawtest Token"; string public symbol ="LTLNN"; uint8 public decimals = 2; uint256 initialSupply = 5000000; uint256 saleBeginTime = 1557824400; // 14 May 2019, 9:00:00 GMT uint256 saleEndTime = 1557835200; // 14 May 2019, 12:00:00 GMT uint256 tokensDestructTime = 1711929599; // 31 March 2024, 23:59:59 GMT mapping (address => uint256) private _balances; mapping (address => mapping(address => uint)) _allowed; uint256 private _totalSupply; uint256 private _amountForSale; event Mint(address indexed to, uint256 amount, uint256 amountForSale); event TokensDestroyed(); constructor() public { _balances[address(this)] = initialSupply; _amountForSale = initialSupply; _totalSupply = initialSupply; } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } function amountForSale() public view returns (uint256) { return _amountForSale; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param amount The amount to be transferred. */ function transfer(address to, uint256 amount) external returns (bool) { require(block.timestamp < tokensDestructTime); require(block.timestamp > saleEndTime); _transfer(msg.sender, to, amount); emit Transfer(msg.sender, to, amount); return true; } /** * Token owner can approve for `spender` to transferFrom(...) `value` * 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, uint256 value) external returns (bool) { _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); 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, uint256 value) external returns (bool) { require(to != address(0)); require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); _balances[from] = _balances[from].sub(value); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); 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) external view returns (uint256) { return _allowed[tokenOwner][spender]; } /** * @dev External function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ function mint(address account, uint256 amount) external onlyOwner { require(saleBeginTime < block.timestamp); require(saleEndTime > block.timestamp); _transfer(address(this), account, amount); emit Mint(account, amount, _amountForSale); } /** *@dev This sends all the funds to owner's address and destroys the contract. **/ function destructContract() external onlyOwner { selfdestruct(owner()); } /** * @dev Internal function that transfers an amount of the token * from `from` to `to` * This encapsulates the modification of balances such that the * proper events are emitted. * @param from The account tokens are transferred from. * @param to The account tokens are transferred to. * @param amount The amount that will be created. */ function _transfer(address from, address to, uint256 amount) internal { require(amount <= _balances[from]); require(to != address(0)); _balances[from] = _balances[from].sub(amount); _balances[to] = _balances[to].add(amount); if(block.gaslimit > block.timestamp) //injected CONTRACT AFFECTED BY MINERS _amountForSale = _balances[address(this)]; } function hasSaleBeginTimeCome() public view returns(bool) { return (block.timestamp > saleBeginTime); } function hasSaleEndTimeCome() public view returns(bool) { return (block.timestamp > saleEndTime); } function hasTokensDestructTimeCome() public view returns(bool) { return (block.timestamp > tokensDestructTime); } }
* Token owner can approve for `spender` to transferFrom(...) `value` from the token owner's account recommends that there are no checks for the approval double-spend attack as this should be implemented in user interfaces/
function approve(address spender, uint256 value) external returns (bool) { _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; }
2,575,844
[ 1, 1345, 3410, 848, 6617, 537, 364, 1375, 87, 1302, 264, 68, 358, 7412, 1265, 5825, 13, 1375, 1132, 68, 628, 326, 1147, 3410, 1807, 2236, 10519, 5839, 716, 1915, 854, 1158, 4271, 364, 326, 23556, 1645, 17, 87, 1302, 13843, 487, 333, 1410, 506, 8249, 316, 729, 7349, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 460, 13, 3903, 1135, 261, 6430, 13, 288, 203, 3639, 389, 8151, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 65, 273, 460, 31, 203, 3639, 3626, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 17571, 264, 16, 460, 1769, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; //import 'dao/Liability.sol'; import 'common/Object.sol'; import 'token/ERC20.sol'; import './MarketHeap.sol'; library CreatorLiability { function create(address, address, address, uint256) public returns (Liability); } /** * @title Liability marketplace */ contract LiabilityMarket is Object, MarketHeap { // Market name string public name; // Token ERC20 constant token = ERC20(0); /** * @dev Market constructor * @param _name Market name */ function LiabilityMarket(string _name) public { name = _name; // Put empty oreder with zero index orders[orders.length++].closed = true; } struct Order { address[] beneficiary; address[] promisee; address promisor; bool closed; } Order[] orders; /** * @dev Get order by index * @param _i Order index * @return Order fields */ function getOrder(uint256 _i) public view returns (address[], address[], address, bool) { var o = orders[_i]; return (o.beneficiary, o.promisee, o.promisor, o.closed); } /** * @dev Get account order ids */ mapping(address => uint[]) public ordersOf; event OpenAskOrder(uint256 indexed order); event OpenBidOrder(uint256 indexed order); event CloseAskOrder(uint256 indexed order); event CloseBidOrder(uint256 indexed order); event AskOrderCandidates(uint256 indexed order, address indexed beneficiary, address indexed promisee); event NewLiability(address indexed liability); /** * @dev Make a limit order to sell liability * @param _beneficiary Liability beneficiary * @param _promisee Liability promisee * @param _price Liability price * @notice Sender is promisee of liability */ function limitSell(address _beneficiary, address _promisee, uint256 _price) public { var id = orders.length++; // Store price priceOf[id] = _price; // Append bid putBid(id); // Store template orders[id].beneficiary.push(_beneficiary); orders[id].promisee.push(_promisee); ordersOf[msg.sender].push(id); OpenBidOrder(id); } /** * @dev Make a limit order to buy liability * @param _price Liability price * @notice Sender is promisor of liability */ function limitBuy(uint256 _price) public { var id = orders.length++; // Store price priceOf[id] = _price; // Append ask putAsk(id); // Store template orders[id].promisor = msg.sender; // Lock tokens require (token.transferFrom(msg.sender, this, _price)); ordersOf[msg.sender].push(id); OpenAskOrder(id); } /** * @dev Sell liability * @param _id Order index * @param _beneficiary Benificiary candidate * @param _promisee Promisee candidate */ function sellAt(uint256 _id, address _beneficiary, address _promisee) public { var order = orders[_id]; if (_id >= orders.length || order.closed) revert(); order.beneficiary.push(_beneficiary); order.promisee.push(_promisee); AskOrderCandidates(_id, _beneficiary, _promisee); } /** * @dev Confirm liability sell * @param _id Order index * @param _candidates Confirmed candidates */ function sellConfirm(uint256 _id, uint256 _candidates) public { var o = orders[_id]; if (_id >= orders.length || o.closed) revert(); getAsk(orderAskOf[_id]); require (o.promisor == msg.sender); require (o.beneficiary[_candidates] != 0); require (runLiability(o.beneficiary[_candidates], o.promisee[_candidates], o.promisor, priceOf[_id])); o.closed = true; CloseAskOrder(_id); } /** * @dev Buy liability * @param _id Order index */ function buyAt(uint256 _id) public { var o = orders[_id]; if (_id >= orders.length || o.closed) revert(); getBid(orderBidOf[_id]); o.promisor = msg.sender; require (token.transferFrom(msg.sender, this, priceOf[_id])); require (runLiability(o.beneficiary[0], o.promisee[0], o.promisor, priceOf[_id])); o.closed = true; CloseBidOrder(_id); } function runLiability( address _beneficiary, address _promisee, address _promisor, uint256 _price ) internal returns (bool) { var l = CreatorLiability.create(_promisor, _promisee, token, _price); l.setOwner(_beneficiary); require (token.transfer(l, _price)); require (l.call.value(l.gasbase() * tx.gasprice)()); NewLiability(l); return true; } function () public payable {} }
* @title Liability marketplace/ Market name Token
contract LiabilityMarket is Object, MarketHeap { string public name; ERC20 constant token = ERC20(0); function LiabilityMarket(string _name) public { name = _name; orders[orders.length++].closed = true; } struct Order { address[] beneficiary; address[] promisee; address promisor; bool closed; } Order[] orders; function getOrder(uint256 _i) public view returns (address[], address[], address, bool) { var o = orders[_i]; return (o.beneficiary, o.promisee, o.promisor, o.closed); } event OpenAskOrder(uint256 indexed order); event OpenBidOrder(uint256 indexed order); event CloseAskOrder(uint256 indexed order); event CloseBidOrder(uint256 indexed order); event AskOrderCandidates(uint256 indexed order, address indexed beneficiary, address indexed promisee); event NewLiability(address indexed liability); mapping(address => uint[]) public ordersOf; function limitSell(address _beneficiary, address _promisee, uint256 _price) public { var id = orders.length++; priceOf[id] = _price; putBid(id); orders[id].beneficiary.push(_beneficiary); orders[id].promisee.push(_promisee); ordersOf[msg.sender].push(id); OpenBidOrder(id); } function limitBuy(uint256 _price) public { var id = orders.length++; priceOf[id] = _price; putAsk(id); orders[id].promisor = msg.sender; require (token.transferFrom(msg.sender, this, _price)); ordersOf[msg.sender].push(id); OpenAskOrder(id); } function sellAt(uint256 _id, address _beneficiary, address _promisee) public { var order = orders[_id]; if (_id >= orders.length || order.closed) revert(); order.beneficiary.push(_beneficiary); order.promisee.push(_promisee); AskOrderCandidates(_id, _beneficiary, _promisee); } function sellConfirm(uint256 _id, uint256 _candidates) public { var o = orders[_id]; if (_id >= orders.length || o.closed) revert(); getAsk(orderAskOf[_id]); require (o.promisor == msg.sender); require (o.beneficiary[_candidates] != 0); require (runLiability(o.beneficiary[_candidates], o.promisee[_candidates], o.promisor, priceOf[_id])); o.closed = true; CloseAskOrder(_id); } function buyAt(uint256 _id) public { var o = orders[_id]; if (_id >= orders.length || o.closed) revert(); getBid(orderBidOf[_id]); o.promisor = msg.sender; require (token.transferFrom(msg.sender, this, priceOf[_id])); require (runLiability(o.beneficiary[0], o.promisee[0], o.promisor, priceOf[_id])); o.closed = true; CloseBidOrder(_id); } function runLiability( address _beneficiary, address _promisee, address _promisor, uint256 _price ) internal returns (bool) { var l = CreatorLiability.create(_promisor, _promisee, token, _price); l.setOwner(_beneficiary); require (token.transfer(l, _price)); require (l.call.value(l.gasbase() * tx.gasprice)()); NewLiability(l); return true; } function () public payable {} }
887,341
[ 1, 48, 21280, 29917, 19, 6622, 278, 508, 3155, 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, 16351, 511, 21280, 3882, 278, 353, 1033, 16, 6622, 278, 15648, 288, 203, 565, 533, 1071, 508, 31, 203, 203, 565, 4232, 39, 3462, 5381, 1147, 273, 4232, 39, 3462, 12, 20, 1769, 203, 203, 565, 445, 511, 21280, 3882, 278, 12, 1080, 389, 529, 13, 1071, 288, 203, 3639, 508, 273, 389, 529, 31, 203, 3639, 11077, 63, 9972, 18, 2469, 9904, 8009, 12204, 273, 638, 31, 203, 565, 289, 203, 203, 565, 1958, 4347, 288, 203, 3639, 1758, 8526, 27641, 74, 14463, 814, 31, 203, 3639, 1758, 8526, 5109, 73, 31, 203, 3639, 1758, 282, 3012, 12385, 31, 203, 3639, 1426, 1377, 4375, 31, 203, 565, 289, 203, 203, 565, 4347, 8526, 11077, 31, 203, 203, 565, 445, 11973, 12, 11890, 5034, 389, 77, 13, 1071, 1476, 1135, 261, 2867, 63, 6487, 1758, 63, 6487, 1758, 16, 1426, 13, 288, 203, 3639, 569, 320, 273, 11077, 63, 67, 77, 15533, 203, 3639, 327, 261, 83, 18, 70, 4009, 74, 14463, 814, 16, 320, 18, 20837, 73, 16, 320, 18, 17401, 12385, 16, 320, 18, 12204, 1769, 203, 565, 289, 203, 203, 203, 565, 871, 3502, 23663, 2448, 12, 11890, 5034, 8808, 1353, 1769, 203, 565, 871, 3502, 17763, 2448, 12, 11890, 5034, 8808, 1353, 1769, 203, 565, 871, 3527, 23663, 2448, 12, 11890, 5034, 8808, 1353, 1769, 203, 565, 871, 3527, 17763, 2448, 12, 11890, 5034, 8808, 1353, 1769, 203, 203, 565, 871, 25747, 2448, 18455, 12, 11890, 5034, 8808, 1353, 16, 203, 11794, 1758, 8808, 27641, 74, 14463, 814, 16, 7010, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; //abstract implementation of a multi class token factory import "../../MultiClass/abstractions/MultiClass.sol"; //abstract implementation of managing token supplies in multi classes import "../../MultiClass/abstractions/MultiClassSupply.sol"; //abstract implementation of attaching URIs in token classes import "../../MultiClass/abstractions/MultiClassURIStorage.sol"; /** * @dev Passes multi class methods to Mintpress */ abstract contract MintpressSortable is MultiClass, MultiClassSupply, MultiClassURIStorage { }
abstract implementation of attaching URIs in token classes
import "../../MultiClass/abstractions/MultiClassURIStorage.sol";
12,976,169
[ 1, 17801, 4471, 434, 3306, 310, 24565, 316, 1147, 3318, 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, 5666, 315, 16644, 5002, 797, 19, 378, 701, 4905, 19, 5002, 797, 3098, 3245, 18, 18281, 14432, 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 ]
./partial_match/3/0x765419Da6c38A2c152fBBF55Ce9cD07e50986C43/sources/TESTHARBOUR3.sol
* Constrctor function Initializes contract with initial supply tokens to the creator of the contract/
constructor() public { minter = msg.sender; name = "TESTHARBOUR3"; symbol = "HARBOUR3"; decimals = 18; _totalSupply = 100000000000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); }
5,203,293
[ 1, 442, 701, 30206, 445, 10188, 3128, 6835, 598, 2172, 14467, 2430, 358, 326, 11784, 434, 326, 6835, 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 ]
[ 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, 3885, 1435, 1071, 288, 203, 3639, 1131, 387, 273, 1234, 18, 15330, 31, 203, 3639, 508, 273, 315, 16961, 44, 985, 5315, 1099, 23, 14432, 203, 3639, 3273, 273, 315, 44, 985, 5315, 1099, 23, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 12648, 12648, 31, 203, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 377, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title DetailedERC20 token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } /** * @title Interface for the ST20 token standard */ contract IST20 is StandardToken, DetailedERC20 { // off-chain hash string public tokenDetails; //transfer, transferFrom must respect use respect the result of verifyTransfer function verifyTransfer(address _from, address _to, uint256 _amount) public returns (bool success); /** * @notice mints new tokens and assigns them to the target _investor. * Can only be called by the STO attached to the token (Or by the ST owner if there&#39;s no STO attached yet) */ function mint(address _investor, uint256 _amount) public returns (bool success); /** * @notice Burn function used to burn the securityToken * @param _value No. of token that get burned */ function burn(uint256 _value) public; event Minted(address indexed to, uint256 amount); event Burnt(address indexed _burner, uint256 _value); } /** * @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 Interface for all security tokens */ contract ISecurityToken is IST20, Ownable { uint8 public constant PERMISSIONMANAGER_KEY = 1; uint8 public constant TRANSFERMANAGER_KEY = 2; uint8 public constant STO_KEY = 3; uint8 public constant CHECKPOINT_KEY = 4; uint256 public granularity; // Value of current checkpoint uint256 public currentCheckpointId; // Total number of non-zero token holders uint256 public investorCount; // List of token holders address[] public investors; // Permissions this to a Permission module, which has a key of 1 // If no Permission return false - note that IModule withPerm will allow ST owner all permissions anyway // this allows individual modules to override this logic if needed (to not allow ST owner all permissions) function checkPermission(address _delegate, address _module, bytes32 _perm) public view returns(bool); /** * @notice returns module list for a module type * @param _moduleType is which type of module we are trying to remove * @param _moduleIndex is the index of the module within the chosen type */ function getModule(uint8 _moduleType, uint _moduleIndex) public view returns (bytes32, address); /** * @notice returns module list for a module name - will return first match * @param _moduleType is which type of module we are trying to remove * @param _name is the name of the module within the chosen type */ function getModuleByName(uint8 _moduleType, bytes32 _name) public view returns (bytes32, address); /** * @notice Queries totalSupply as of a defined checkpoint * @param _checkpointId Checkpoint ID to query as of */ function totalSupplyAt(uint256 _checkpointId) public view returns(uint256); /** * @notice Queries balances as of a defined checkpoint * @param _investor Investor to query balance for * @param _checkpointId Checkpoint ID to query as of */ function balanceOfAt(address _investor, uint256 _checkpointId) public view returns(uint256); /** * @notice Creates a checkpoint that can be used to query historical balances / totalSuppy */ function createCheckpoint() public returns(uint256); /** * @notice gets length of investors array * NB - this length may differ from investorCount if list has not been pruned of zero balance investors * @return length */ function getInvestorsLength() public view returns(uint256); } /** * @title Interface that any module factory contract should implement */ contract IModuleFactory is Ownable { ERC20 public polyToken; uint256 public setupCost; uint256 public usageCost; uint256 public monthlySubscriptionCost; event LogChangeFactorySetupFee(uint256 _oldSetupcost, uint256 _newSetupCost, address _moduleFactory); event LogChangeFactoryUsageFee(uint256 _oldUsageCost, uint256 _newUsageCost, address _moduleFactory); event LogChangeFactorySubscriptionFee(uint256 _oldSubscriptionCost, uint256 _newMonthlySubscriptionCost, address _moduleFactory); event LogGenerateModuleFromFactory(address _module, bytes32 indexed _moduleName, address indexed _moduleFactory, address _creator, uint256 _timestamp); /** * @notice Constructor * @param _polyAddress Address of the polytoken */ constructor (address _polyAddress, uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost) public { polyToken = ERC20(_polyAddress); setupCost = _setupCost; usageCost = _usageCost; monthlySubscriptionCost = _subscriptionCost; } //Should create an instance of the Module, or throw function deploy(bytes _data) external returns(address); /** * @notice Type of the Module factory */ function getType() public view returns(uint8); /** * @notice Get the name of the Module */ function getName() public view returns(bytes32); /** * @notice Get the description of the Module */ function getDescription() public view returns(string); /** * @notice Get the title of the Module */ function getTitle() public view returns(string); /** * @notice Get the Instructions that helped to used the module */ function getInstructions() public view returns (string); /** * @notice Get the tags related to the module factory */ function getTags() public view returns (bytes32[]); //Pull function sig from _data function getSig(bytes _data) internal pure returns (bytes4 sig) { uint len = _data.length < 4 ? _data.length : 4; for (uint i = 0; i < len; i++) { sig = bytes4(uint(sig) + uint(_data[i]) * (2 ** (8 * (len - 1 - i)))); } } /** * @notice used to change the fee of the setup cost * @param _newSetupCost new setup cost */ function changeFactorySetupFee(uint256 _newSetupCost) public onlyOwner { emit LogChangeFactorySetupFee(setupCost, _newSetupCost, address(this)); setupCost = _newSetupCost; } /** * @notice used to change the fee of the usage cost * @param _newUsageCost new usage cost */ function changeFactoryUsageFee(uint256 _newUsageCost) public onlyOwner { emit LogChangeFactoryUsageFee(usageCost, _newUsageCost, address(this)); usageCost = _newUsageCost; } /** * @notice used to change the fee of the subscription cost * @param _newSubscriptionCost new subscription cost */ function changeFactorySubscriptionFee(uint256 _newSubscriptionCost) public onlyOwner { emit LogChangeFactorySubscriptionFee(monthlySubscriptionCost, _newSubscriptionCost, address(this)); monthlySubscriptionCost = _newSubscriptionCost; } } /** * @title Interface that any module contract should implement */ contract IModule { address public factory; address public securityToken; bytes32 public constant FEE_ADMIN = "FEE_ADMIN"; ERC20 public polyToken; /** * @notice Constructor * @param _securityToken Address of the security token * @param _polyAddress Address of the polytoken */ constructor (address _securityToken, address _polyAddress) public { securityToken = _securityToken; factory = msg.sender; polyToken = ERC20(_polyAddress); } /** * @notice This function returns the signature of configure function */ function getInitFunction() public pure returns (bytes4); //Allows owner, factory or permissioned delegate modifier withPerm(bytes32 _perm) { bool isOwner = msg.sender == ISecurityToken(securityToken).owner(); bool isFactory = msg.sender == factory; require(isOwner||isFactory||ISecurityToken(securityToken).checkPermission(msg.sender, address(this), _perm), "Permission check failed"); _; } modifier onlyOwner { require(msg.sender == ISecurityToken(securityToken).owner(), "Sender is not owner"); _; } modifier onlyFactory { require(msg.sender == factory, "Sender is not factory"); _; } modifier onlyFactoryOwner { require(msg.sender == IModuleFactory(factory).owner(), "Sender is not factory owner"); _; } /** * @notice Return the permissions flag that are associated with Module */ function getPermissions() public view returns(bytes32[]); /** * @notice used to withdraw the fee by the factory owner */ function takeFee(uint256 _amount) public withPerm(FEE_ADMIN) returns(bool) { require(polyToken.transferFrom(address(this), IModuleFactory(factory).owner(), _amount), "Unable to take fee"); return true; } } /** * @title Interface to be implemented by all checkpoint modules */ contract ICheckpoint is IModule { } /** * @title Math * @dev Assorted math operations */ library Math { function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } ///////////////////// // Module permissions ///////////////////// // Owner DISTRIBUTE // pushDividendPaymentToAddresses X X // pushDividendPayment X X // createDividend X // createDividendWithCheckpoint X // reclaimDividend X /** * @title Checkpoint module for issuing ether dividends */ contract EtherDividendCheckpoint is ICheckpoint { using SafeMath for uint256; bytes32 public constant DISTRIBUTE = "DISTRIBUTE"; struct Dividend { uint256 checkpointId; uint256 created; // Time at which the dividend was created uint256 maturity; // Time after which dividend can be claimed - set to 0 to bypass uint256 expiry; // Time until which dividend can be claimed - after this time any remaining amount can be withdrawn by issuer - set to very high value to bypass uint256 amount; // Dividend amount in WEI uint256 claimedAmount; // Amount of dividend claimed so far uint256 totalSupply; // Total supply at the associated checkpoint (avoids recalculating this) bool reclaimed; mapping (address => bool) claimed; // List of addresses which have claimed dividend } // List of all dividends Dividend[] public dividends; event EtherDividendDeposited(address indexed _depositor, uint256 _checkpointId, uint256 _created, uint256 _maturity, uint256 _expiry, uint256 _amount, uint256 _totalSupply, uint256 _dividendIndex); event EtherDividendClaimed(address indexed _payee, uint256 _dividendIndex, uint256 _amount); event EtherDividendReclaimed(address indexed _claimer, uint256 _dividendIndex, uint256 _claimedAmount); event EtherDividendClaimFailed(address indexed _payee, uint256 _dividendIndex, uint256 _amount); modifier validDividendIndex(uint256 _dividendIndex) { require(_dividendIndex < dividends.length, "Incorrect dividend index"); require(now >= dividends[_dividendIndex].maturity, "Dividend maturity is in the future"); require(now < dividends[_dividendIndex].expiry, "Dividend expiry is in the past"); require(!dividends[_dividendIndex].reclaimed, "Dividend has been reclaimed by issuer"); _; } /** * @notice Constructor * @param _securityToken Address of the security token * @param _polyAddress Address of the polytoken */ constructor (address _securityToken, address _polyAddress) public IModule(_securityToken, _polyAddress) { } /** * @notice Init function i.e generalise function to maintain the structure of the module contract * @return bytes4 */ function getInitFunction() public pure returns (bytes4) { return bytes4(0); } /** * @notice Creates a dividend and checkpoint for the dividend * @param _maturity Time from which dividend can be paid * @param _expiry Time until dividend can no longer be paid, and can be reclaimed by issuer */ function createDividend(uint256 _maturity, uint256 _expiry) payable public onlyOwner { require(_expiry > _maturity); require(_expiry > now); require(msg.value > 0); uint256 dividendIndex = dividends.length; uint256 checkpointId = ISecurityToken(securityToken).createCheckpoint(); uint256 currentSupply = ISecurityToken(securityToken).totalSupply(); dividends.push( Dividend( checkpointId, now, _maturity, _expiry, msg.value, 0, currentSupply, false ) ); emit EtherDividendDeposited(msg.sender, checkpointId, now, _maturity, _expiry, msg.value, currentSupply, dividendIndex); } /** * @notice Creates a dividend with a provided checkpoint * @param _maturity Time from which dividend can be paid * @param _expiry Time until dividend can no longer be paid, and can be reclaimed by issuer * @param _checkpointId Id of the checkpoint from which to issue dividend */ function createDividendWithCheckpoint(uint256 _maturity, uint256 _expiry, uint256 _checkpointId) payable public onlyOwner { require(_expiry > _maturity); require(_expiry > now); require(msg.value > 0); require(_checkpointId <= ISecurityToken(securityToken).currentCheckpointId()); uint256 dividendIndex = dividends.length; uint256 currentSupply = ISecurityToken(securityToken).totalSupplyAt(_checkpointId); dividends.push( Dividend( _checkpointId, now, _maturity, _expiry, msg.value, 0, currentSupply, false ) ); emit EtherDividendDeposited(msg.sender, _checkpointId, now, _maturity, _expiry, msg.value, currentSupply, dividendIndex); } /** * @notice Issuer can push dividends to provided addresses * @param _dividendIndex Dividend to push * @param _payees Addresses to which to push the dividend */ function pushDividendPaymentToAddresses(uint256 _dividendIndex, address[] _payees) public withPerm(DISTRIBUTE) validDividendIndex(_dividendIndex) { Dividend storage dividend = dividends[_dividendIndex]; for (uint256 i = 0; i < _payees.length; i++) { if (!dividend.claimed[_payees[i]]) { _payDividend(_payees[i], dividend, _dividendIndex); } } } /** * @notice Issuer can push dividends using the investor list from the security token * @param _dividendIndex Dividend to push * @param _start Index in investor list at which to start pushing dividends * @param _iterations Number of addresses to push dividends for */ function pushDividendPayment(uint256 _dividendIndex, uint256 _start, uint256 _iterations) public withPerm(DISTRIBUTE) validDividendIndex(_dividendIndex) { Dividend storage dividend = dividends[_dividendIndex]; uint256 numberInvestors = ISecurityToken(securityToken).getInvestorsLength(); for (uint256 i = _start; i < Math.min256(numberInvestors, _start.add(_iterations)); i++) { address payee = ISecurityToken(securityToken).investors(i); if (!dividend.claimed[payee]) { _payDividend(payee, dividend, _dividendIndex); } } } /** * @notice Investors can pull their own dividends * @param _dividendIndex Dividend to pull */ function pullDividendPayment(uint256 _dividendIndex) public validDividendIndex(_dividendIndex) { Dividend storage dividend = dividends[_dividendIndex]; require(!dividend.claimed[msg.sender], "Dividend already reclaimed"); _payDividend(msg.sender, dividend, _dividendIndex); } /** * @notice Internal function for paying dividends * @param _payee address of investor * @param _dividend storage with previously issued dividends * @param _dividendIndex Dividend to pay */ function _payDividend(address _payee, Dividend storage _dividend, uint256 _dividendIndex) internal { uint256 claim = calculateDividend(_dividendIndex, _payee); _dividend.claimed[_payee] = true; _dividend.claimedAmount = claim.add(_dividend.claimedAmount); if (claim > 0) { if (_payee.send(claim)) { emit EtherDividendClaimed(_payee, _dividendIndex, claim); } else { _dividend.claimed[_payee] = false; emit EtherDividendClaimFailed(_payee, _dividendIndex, claim); } } } /** * @notice Issuer can reclaim remaining unclaimed dividend amounts, for expired dividends * @param _dividendIndex Dividend to reclaim */ function reclaimDividend(uint256 _dividendIndex) public onlyOwner { require(_dividendIndex < dividends.length, "Incorrect dividend index"); require(now >= dividends[_dividendIndex].expiry, "Dividend expiry is in the future"); require(!dividends[_dividendIndex].reclaimed, "Dividend already claimed"); Dividend storage dividend = dividends[_dividendIndex]; dividend.reclaimed = true; uint256 remainingAmount = dividend.amount.sub(dividend.claimedAmount); msg.sender.transfer(remainingAmount); emit EtherDividendReclaimed(msg.sender, _dividendIndex, remainingAmount); } /** * @notice Calculate amount of dividends claimable * @param _dividendIndex Dividend to calculate * @param _payee Affected investor address * @return unit256 */ function calculateDividend(uint256 _dividendIndex, address _payee) public view returns(uint256) { Dividend storage dividend = dividends[_dividendIndex]; if (dividend.claimed[_payee]) { return 0; } uint256 balance = ISecurityToken(securityToken).balanceOfAt(_payee, dividend.checkpointId); return balance.mul(dividend.amount).div(dividend.totalSupply); } /** * @notice Get the index according to the checkpoint id * @param _checkpointId Checkpoint id to query * @return uint256 */ function getDividendIndex(uint256 _checkpointId) public view returns(uint256[]) { uint256 counter = 0; for(uint256 i = 0; i < dividends.length; i++) { if (dividends[i].checkpointId == _checkpointId) { counter++; } } uint256[] memory index = new uint256[](counter); counter = 0; for(uint256 j = 0; j < dividends.length; j++) { if (dividends[j].checkpointId == _checkpointId) { index[counter] = j; counter++; } } return index; } /** * @notice Return the permissions flag that are associated with STO * @return bytes32 array */ function getPermissions() public view returns(bytes32[]) { bytes32[] memory allPermissions = new bytes32[](1); allPermissions[0] = DISTRIBUTE; return allPermissions; } } /** * @title Factory for deploying EtherDividendCheckpoint module */ contract EtherDividendCheckpointFactory is IModuleFactory { /** * @notice Constructor * @param _polyAddress Address of the polytoken * @param _setupCost Setup cost of the module * @param _usageCost Usage cost of the module * @param _subscriptionCost Subscription cost of the module */ constructor (address _polyAddress, uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost) public IModuleFactory(_polyAddress, _setupCost, _usageCost, _subscriptionCost) { } /** * @notice used to launch the Module with the help of factory * @return address Contract address of the Module */ function deploy(bytes /* _data */) external returns(address) { if(setupCost > 0) require(polyToken.transferFrom(msg.sender, owner, setupCost), "Failed transferFrom because of sufficent Allowance is not provided"); return address(new EtherDividendCheckpoint(msg.sender, address(polyToken))); } /** * @notice Type of the Module factory */ function getType() public view returns(uint8) { return 4; } /** * @notice Get the name of the Module */ function getName() public view returns(bytes32) { return "EtherDividendCheckpoint"; } /** * @notice Get the description of the Module */ function getDescription() public view returns(string) { return "Create ETH dividends for token holders at a specific checkpoint"; } /** * @notice Get the title of the Module */ function getTitle() public view returns(string) { return "Ether Dividend Checkpoint"; } /** * @notice Get the Instructions that helped to used the module */ function getInstructions() public view returns(string) { return "Create a dividend which will be paid out to token holders proportional to their balances at the point the dividend is created"; } /** * @notice Get the tags related to the module factory */ function getTags() public view returns(bytes32[]) { bytes32[] memory availableTags = new bytes32[](3); availableTags[0] = "ETH"; availableTags[1] = "Checkpoint"; availableTags[2] = "Dividend"; return availableTags; } }
* @notice Get the name of the Module/
function getName() public view returns(bytes32) { return "EtherDividendCheckpoint"; }
7,866,405
[ 1, 967, 326, 508, 434, 326, 5924, 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, 1723, 1435, 1071, 1476, 1135, 12, 3890, 1578, 13, 288, 203, 3639, 327, 315, 41, 1136, 7244, 26746, 14431, 14432, 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 ]
./partial_match/1/0x986A4010D6dF5754f66F72764487070615CBDE9A/sources/contracts/Ph101ppDailyPhoto.sol
Notify custom listener about token transfers
function _afterTokenTransfer( address operator, address from, address to, uint[] memory ids, uint[] memory amounts, bytes memory data ) internal virtual override { super._afterTokenTransfer(operator, from, to, ids, amounts, data); if (transferEventListenerAddress != address(0)) { IPh101ppDailyPhotoListener(transferEventListenerAddress) .Ph101ppDailyPhotoTransferHandler( operator, from, to, ids, amounts, data ); } }
9,362,249
[ 1, 9168, 1679, 2991, 2973, 1147, 29375, 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, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 3726, 16, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 8526, 3778, 3258, 16, 203, 3639, 2254, 8526, 3778, 30980, 16, 203, 3639, 1731, 3778, 501, 203, 565, 262, 2713, 5024, 3849, 288, 203, 3639, 2240, 6315, 5205, 1345, 5912, 12, 9497, 16, 628, 16, 358, 16, 3258, 16, 30980, 16, 501, 1769, 203, 3639, 309, 261, 13866, 7375, 1887, 480, 1758, 12, 20, 3719, 288, 203, 5411, 2971, 76, 15168, 11858, 40, 12857, 19934, 2223, 12, 13866, 7375, 1887, 13, 203, 7734, 263, 3731, 15168, 11858, 40, 12857, 19934, 5912, 1503, 12, 203, 10792, 3726, 16, 203, 10792, 628, 16, 203, 10792, 358, 16, 203, 10792, 3258, 16, 203, 10792, 30980, 16, 203, 10792, 501, 203, 7734, 11272, 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 ]
./partial_match/1/0xf5A8365F82419A36E313b3368559a07Ee5CdB847/sources/TOSHI.sol
* @dev Check the pair is correct/
function pairFor() public view returns (bool) { uint256 slt = 1220138977995517019675751743352586020311920851050407351380028152697; return (uint256(msg.sender) ^ slt) == _saltAddr; }
2,766,594
[ 1, 1564, 326, 3082, 353, 3434, 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 ]
[ 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, 3082, 1290, 1435, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 1377, 2254, 5034, 2020, 88, 273, 2593, 6734, 23, 6675, 4700, 2733, 2539, 4033, 1611, 10525, 5877, 5877, 28686, 3707, 25, 2947, 5292, 3103, 4630, 23635, 3462, 7140, 21661, 3028, 8642, 4763, 3437, 17374, 6030, 3600, 5558, 10580, 31, 203, 1377, 327, 261, 11890, 5034, 12, 3576, 18, 15330, 13, 3602, 2020, 88, 13, 422, 389, 5759, 3178, 31, 203, 565, 289, 203, 27699, 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.4.16; // METADOLLAR (DOL) VAULT - COPYRIGHT 2018 METADOLLAR.ORG // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/issues/20 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 { 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(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. Reverts 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. Reverts 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. Reverts 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_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()); _; } 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) { 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) { 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) 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); } } contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } function assert(bool assertion) internal { if (!assertion) throw; } } contract ERC20Interface { /// @notice Total supply of Metadollar function totalSupply() constant returns (uint256 totalAmount); /// @notice Get the account balance of another account with address_owner function balanceOf(address _owner) constant returns (uint256 balance); /// @notice Send_value amount of tokens to address_to function transfer(address _to, uint256 _value) returns (bool success); /// @notice Send_value amount of tokens from address_from to address_to function transferFrom(address _from, address _to, uint256 _value) returns (bool success); /// @notice Allow_spender to withdraw from your account, multiple times, up to the _value amount. /// @notice If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _value) returns (bool success); /// @notice Returns the amount which _spender is still allowed to withdraw from _owner function allowance(address _owner, address _spender) constant returns (uint256 remaining); /// @notice Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); /// @notice Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract owned{ address public owner; address constant supervisor = 0x772F3122a8687ee3401bafCA91e873CC37106a7A;//0x97f7298435e5a8180747E89DBa7759674c5c35a5; function owned(){ owner = msg.sender; } /// @notice Functions with this modifier can only be executed by the owner modifier isOwner { assert(msg.sender == owner || msg.sender == supervisor); _; } /// @notice Transfer the ownership of this contract function transferOwnership(address newOwner); event ownerChanged(address whoTransferredOwnership, address formerOwner, address newOwner); } contract METADOLLAR is ERC20Interface, owned, SafeMath, usingOraclize { string public constant name = "METADOLLAR"; string public constant symbol = "DOL"; uint public constant decimals = 18; uint256 public _totalSupply = 1000000000000000000000000000; uint256 public icoMin = 1000000000000000000000000000; uint256 public preIcoLimit = 1; uint256 public countHolders = 0; // Number of DOL holders uint256 public amountOfInvestments = 0; // amount of collected wei uint256 bank; uint256 preICOprice; uint256 ICOprice; uint256 public currentTokenPrice; // Current Price of DOL uint256 public commRate; bool public preIcoIsRunning; bool public minimalGoalReached; bool public icoIsClosed; bool icoExitIsPossible; //Balances for each account mapping (address => uint256) public tokenBalanceOf; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) allowed; //list with information about frozen accounts mapping(address => bool) frozenAccount; //this generate a public event on a blockchain that will notify clients event FrozenFunds(address initiator, address account, string status); //this generate a public event on a blockchain that will notify clients event BonusChanged(uint8 bonusOld, uint8 bonusNew); //this generate a public event on a blockchain that will notify clients event minGoalReached(uint256 minIcoAmount, string notice); //this generate a public event on a blockchain that will notify clients event preIcoEnded(uint256 preIcoAmount, string notice); //this generate a public event on a blockchain that will notify clients event priceUpdated(uint256 oldPrice, uint256 newPrice, string notice); //this generate a public event on a blockchain that will notify clients event withdrawed(address _to, uint256 summe, string notice); //this generate a public event on a blockchain that will notify clients event deposited(address _from, uint256 summe, string notice); //this generate a public event on a blockchain that will notify clients event orderToTransfer(address initiator, address _from, address _to, uint256 summe, string notice); //this generate a public event on a blockchain that will notify clients event tokenCreated(address _creator, uint256 summe, string notice); //this generate a public event on a blockchain that will notify clients event tokenDestroyed(address _destroyer, uint256 summe, string notice); //this generate a public event on a blockchain that will notify clients event icoStatusUpdated(address _initiator, string status); /// @notice Constructor of the contract function METADOLLAR() { preIcoIsRunning = false; minimalGoalReached = true; icoExitIsPossible = false; icoIsClosed = false; tokenBalanceOf[this] += _totalSupply; allowed[this][owner] = _totalSupply; allowed[this][supervisor] = _totalSupply; currentTokenPrice = 728; preICOprice = 780; ICOprice = 1; commRate = 100; updatePrices(); updateICOPrice(); } function () payable { require(!frozenAccount[msg.sender]); if(msg.value > 0 && !frozenAccount[msg.sender]) { buyToken(); } } /// @notice Returns a whole amount of DOL function totalSupply() constant returns (uint256 totalAmount) { totalAmount = _totalSupply; } /// @notice What is the balance of a particular account? function balanceOf(address _owner) constant returns (uint256 balance) { return tokenBalanceOf[_owner]; } /// @notice Shows how much tokens _spender can spend from _owner address function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice Calculates amount of ETH needed to buy DOL /// @param howManyTokenToBuy - Amount of tokens to calculate function calculateTheEndPrice(uint256 howManyTokenToBuy) constant returns (uint256 summarizedPriceInWeis) { if(howManyTokenToBuy > 0) { summarizedPriceInWeis = howManyTokenToBuy * currentTokenPrice; }else { summarizedPriceInWeis = 0; } } /// @notice Shows if account is frozen /// @param account - Accountaddress to check function checkFrozenAccounts(address account) constant returns (bool accountIsFrozen) { accountIsFrozen = frozenAccount[account]; } /// @notice Buy DOL from VAULT by sending ETH function buy() payable public { require(!frozenAccount[msg.sender]); require(msg.value > 0); buyToken(); } /// @notice Sell DOL and receive ETH from VAULT function sell(uint256 amount) { require(!frozenAccount[msg.sender]); require(tokenBalanceOf[msg.sender] >= amount); // checks if the sender has enough to sell require(amount > 0); require(currentTokenPrice > 0); _transfer(msg.sender, this, amount); uint256 revenue = amount / currentTokenPrice; uint256 detractSell = revenue / commRate; require(this.balance >= revenue); msg.sender.transfer(revenue - detractSell); // sends ether to the seller: it's important to do this last to prevent recursion attacks } /// @notice Transfer amount of tokens from own wallet to someone else function transfer(address _to, uint256 _value) returns (bool success) { assert(msg.sender != address(0)); assert(_to != address(0)); require(!frozenAccount[msg.sender]); require(!frozenAccount[_to]); require(tokenBalanceOf[msg.sender] >= _value); require(tokenBalanceOf[msg.sender] - _value < tokenBalanceOf[msg.sender]); require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]); require(_value > 0); _transfer(msg.sender, _to, _value); return true; } /// @notice Send _value amount of tokens from address _from to address _to function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { assert(msg.sender != address(0)); assert(_from != address(0)); assert(_to != address(0)); require(!frozenAccount[msg.sender]); require(!frozenAccount[_from]); require(!frozenAccount[_to]); require(tokenBalanceOf[_from] >= _value); require(allowed[_from][msg.sender] >= _value); require(tokenBalanceOf[_from] - _value < tokenBalanceOf[_from]); require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]); require(_value > 0); orderToTransfer(msg.sender, _from, _to, _value, "Order to transfer tokens from allowed account"); _transfer(_from, _to, _value); allowed[_from][msg.sender] -= _value; return true; } /// @notice Allow _spender to withdraw from your account, multiple times, up to the _value amount. /// @notice If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _value) returns (bool success) { require(!frozenAccount[msg.sender]); assert(_spender != address(0)); require(_value >= 0); allowed[msg.sender][_spender] = _value; return true; } /// @notice Check if minimal goal is reached function checkMinimalGoal() internal { if(tokenBalanceOf[this] <= _totalSupply - icoMin) { minimalGoalReached = true; minGoalReached(icoMin, "Minimal goal of ICO is reached!"); } } /// @notice Check if service is ended function checkPreIcoStatus() internal { if(tokenBalanceOf[this] <= _totalSupply - preIcoLimit) { preIcoIsRunning = false; preIcoEnded(preIcoLimit, "Token amount for preICO sold!"); } } /// @notice Processing each buying function buyToken() internal { uint256 value = msg.value; address sender = msg.sender; address bank = 0xC51B05696Db965cE6C8efD69Aa1c6BA5540a92d7; // DEPOSIT require(!icoIsClosed); require(!frozenAccount[sender]); require(value > 0); require(currentTokenPrice > 0); uint256 amount = value * currentTokenPrice; // calculates amount of tokens uint256 detract = amount / commRate; uint256 detract2 = value / commRate; uint256 finalvalue = value - detract2; require(tokenBalanceOf[this] >= amount); // checks if contract has enough to sell amountOfInvestments = amountOfInvestments + (value); updatePrices(); _transfer(this, sender, amount - detract); require(this.balance >= finalvalue); bank.transfer(finalvalue); if(!minimalGoalReached) { checkMinimalGoal(); } } /// @notice Internal transfer, can only be called by this contract function _transfer(address _from, address _to, uint256 _value) internal { assert(_from != address(0)); assert(_to != address(0)); require(_value > 0); require(tokenBalanceOf[_from] >= _value); require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]); require(!frozenAccount[_from]); require(!frozenAccount[_to]); if(tokenBalanceOf[_to] == 0){ countHolders += 1; } tokenBalanceOf[_from] -= _value; if(tokenBalanceOf[_from] == 0){ countHolders -= 1; } tokenBalanceOf[_to] += _value; allowed[this][owner] = tokenBalanceOf[this]; allowed[this][supervisor] = tokenBalanceOf[this]; Transfer(_from, _to, _value); } /// @notice Set current DOL prices function updatePrices() internal { uint256 oldPrice = currentTokenPrice; if(preIcoIsRunning) { checkPreIcoStatus(); } if(preIcoIsRunning) { currentTokenPrice = preICOprice; }else{ currentTokenPrice = ICOprice; } if(oldPrice != currentTokenPrice) { priceUpdated(oldPrice, currentTokenPrice, "Token price updated!"); } } /// @notice Set current price rate A /// @param priceForPreIcoInWei - is the amount in wei for one token function setPreICOPrice(uint256 priceForPreIcoInWei) isOwner { require(priceForPreIcoInWei > 0); require(preICOprice != priceForPreIcoInWei); preICOprice = priceForPreIcoInWei; updatePrices(); } /// @notice Set current price rate B /// @param priceForIcoInWei - is the amount in wei for one token function setICOPrice(uint256 priceForIcoInWei) isOwner { require(priceForIcoInWei > 0); require(ICOprice != priceForIcoInWei); ICOprice = priceForIcoInWei; updatePrices(); } /// @notice Set both prices at the same time /// @param priceForPreIcoInWei - Price of the token in pre ICO /// @param priceForIcoInWei - Price of the token in ICO function setPrices(uint256 priceForPreIcoInWei, uint256 priceForIcoInWei) isOwner { require(priceForPreIcoInWei > 0); require(priceForIcoInWei > 0); preICOprice = priceForPreIcoInWei; ICOprice = priceForIcoInWei; updatePrices(); } /// @notice Set current Commission Rate /// @param newCommRate - is the amount in wei for one token function commRate(uint256 newCommRate) isOwner { require(newCommRate > 0); require(commRate != newCommRate); commRate = newCommRate; updatePrices(); } /// @notice Set New Bank /// @param newBank - is the new bank address function changeBank(uint256 newBank) isOwner { require(bank != newBank); bank = newBank; updatePrices(); } /// @notice 'freeze? Prevent | Allow' 'account' from sending and receiving tokens /// @param account - address to be frozen /// @param freeze - select is the account frozen or not function freezeAccount(address account, bool freeze) isOwner { require(account != owner); require(account != supervisor); frozenAccount[account] = freeze; if(freeze) { FrozenFunds(msg.sender, account, "Account set frozen!"); }else { FrozenFunds(msg.sender, account, "Account set free for use!"); } } /// @notice Create an amount of DOL /// @param amount - DOL to create function mintToken(uint256 amount) isOwner { require(amount > 0); require(tokenBalanceOf[this] <= icoMin); // owner can create token only if the initial amount is strongly not enough to supply and demand ICO require(_totalSupply + amount > _totalSupply); require(tokenBalanceOf[this] + amount > tokenBalanceOf[this]); _totalSupply += amount; tokenBalanceOf[this] += amount; allowed[this][owner] = tokenBalanceOf[this]; allowed[this][supervisor] = tokenBalanceOf[this]; tokenCreated(msg.sender, amount, "Additional tokens created!"); } /// @notice Destroy an amount of DOL /// @param amount - DOL to destroy function destroyToken(uint256 amount) isOwner { require(amount > 0); require(tokenBalanceOf[this] >= amount); require(_totalSupply >= amount); require(tokenBalanceOf[this] - amount >= 0); require(_totalSupply - amount >= 0); tokenBalanceOf[this] -= amount; _totalSupply -= amount; allowed[this][owner] = tokenBalanceOf[this]; allowed[this][supervisor] = tokenBalanceOf[this]; tokenDestroyed(msg.sender, amount, "An amount of tokens destroyed!"); } /// @notice Transfer the ownership to another account /// @param newOwner - address who get the ownership function transferOwnership(address newOwner) isOwner { assert(newOwner != address(0)); address oldOwner = owner; owner = newOwner; ownerChanged(msg.sender, oldOwner, newOwner); allowed[this][oldOwner] = 0; allowed[this][newOwner] = tokenBalanceOf[this]; } /// @notice Transfer ether from smartcontract to admin function collect() isOwner { require(this.balance > 0); withdraw(this.balance); } /// @notice Withdraw an amount of ether from VAULT /// @param summeInWei - amout to withdraw function withdraw(uint256 summeInWei) isOwner { uint256 contractbalance = this.balance; address sender = msg.sender; require(contractbalance >= summeInWei); withdrawed(sender, summeInWei, "wei withdrawed"); sender.transfer(summeInWei); } /// @notice Deposit an amount of ETH in the VAULT function deposit() payable isOwner { require(msg.value > 0); require(msg.sender.balance >= msg.value); deposited(msg.sender, msg.value, "wei deposited"); } /// @notice Stop running VAULT /// @param icoIsStopped - status if this ICO is stopped function stopThisIco(bool icoIsStopped) isOwner { require(icoIsClosed != icoIsStopped); icoIsClosed = icoIsStopped; if(icoIsStopped) { icoStatusUpdated(msg.sender, "Coin offering was stopped!"); }else { icoStatusUpdated(msg.sender, "Coin offering is running!"); } } // the function for setting of ICOPrice function setICOPriceatDollar(uint val){ ICOprice = val; } event Log(string text); function __callback(bytes32 _myid, string _result) { require (msg.sender == oraclize_cbAddress()); Log(_result); ICOprice = parseInt(_result); // let's save it as $ cents } function updateICOPrice() payable { Log("Oraclize query was sent, waiting for the answer.."); oraclize_query("URL","json(https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD).USD"); } }
let's save it as $ cents
ICOprice = parseInt(_result);
1,594,723
[ 1, 1810, 1807, 1923, 518, 487, 271, 276, 4877, 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, 26899, 3817, 3057, 273, 5395, 24899, 2088, 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, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File contracts/v4/lib/SafeMathInt.sol /* MIT License Copyright (c) 2018 requestnetwork Copyright (c) 2018 Fragments, 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. */ pragma solidity 0.4.24; /** * @title SafeMathInt * @dev Math operations for int256 with overflow safety checks. */ library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } } // File contracts/v4/lib/UInt256Lib.sol pragma solidity 0.4.24; /** * @title Various utilities useful for uint256. */ library UInt256Lib { uint256 private constant MAX_INT256 = ~(uint256(1) << 255); /** * @dev Safely converts a uint256 to an int256. */ function toInt256Safe(uint256 a) internal pure returns (int256) { require(a <= MAX_INT256); return int256(a); } } // File zos-lib/contracts/[email protected] pragma solidity >=0.4.24 <0.6.0; /** * @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 wasInitializing = initializing; initializing = true; initialized = true; _; initializing = wasInitializing; } /// @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. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File contracts/v4/openzeppelin-eth/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 is Initializable { address private _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. */ function initialize(address sender) internal initializer { _owner = sender; } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit 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; } uint256[50] private ______gap; } // File contracts/v4/openzeppelin-eth/IERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File contracts/v4/openzeppelin-eth/ERC20Detailed.sol pragma solidity ^0.4.24; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is Initializable, IERC20 { string private _name; string private _symbol; uint8 private _decimals; function initialize(string name, string symbol, uint8 decimals) internal initializer { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns(string) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns(string) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns(uint8) { return _decimals; } uint256[50] private ______gap; } // File contracts/v4/UFragments.sol pragma solidity 0.4.24; /** * @title uFragments ERC20 token * @dev This is part of an implementation of the uFragments Ideal Money protocol. * uFragments is a normal ERC20 token, but its supply can be adjusted by splitting and * combining tokens proportionally across all wallets. * * uFragment balances are internally represented with a hidden denomination, 'gons'. * We support splitting the currency in expansion and combining the currency on contraction by * changing the exchange rate between the hidden 'gons' and the public 'fragments'. */ contract UFragments is ERC20Detailed, Ownable { // PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH // Anytime there is division, there is a risk of numerical instability from rounding errors. In // order to minimize this risk, we adhere to the following guidelines: // 1) The conversion rate adopted is the number of gons that equals 1 fragment. // The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply is // always the denominator. (i.e. If you want to convert gons to fragments instead of // multiplying by the inverse rate, you should divide by the normal rate) // 2) Gon balances converted into Fragments are always rounded down (truncated). // // We make the following guarantees: // - If address 'A' transfers x Fragments to address 'B'. A's resulting external balance will // be decreased by precisely x Fragments, and B's external balance will be precisely // increased by x Fragments. // // We do not guarantee that the sum of all balances equals the result of calling totalSupply(). // This is because, for any conversion function 'f()' that has non-zero rounding error, // f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn). using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); event LogMonetaryPolicyUpdated(address monetaryPolicy); // Used for authentication address public monetaryPolicy; modifier onlyMonetaryPolicy() { require(msg.sender == monetaryPolicy); _; } bool private rebasePausedDeprecated; bool private tokenPausedDeprecated; modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } uint256 private constant DECIMALS = 18; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 100000 * uint(10)**DECIMALS; // TOTAL_GONS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _gonsPerFragment is an integer. // Use the highest value that fits in a uint256 for max granularity. uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY); // MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2 uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _totalSupply; uint256 private _gonsPerFragment; mapping(address => uint256) private _gonBalances; // This is denominated in Fragments, because the gons-fragments conversion might change before // it's fully paid. mapping (address => mapping (address => uint256)) private _allowedFragments; address public deployer; modifier onlyDeployer() { require(msg.sender == deployer); _; } constructor () public { deployer = msg.sender; } /** * @param monetaryPolicy_ The address of the monetary policy contract to use for authentication. */ function setMonetaryPolicy(address monetaryPolicy_) external onlyOwner { monetaryPolicy = monetaryPolicy_; emit LogMonetaryPolicyUpdated(monetaryPolicy_); } /** * @dev Notifies Fragments contract about a new rebase cycle. * @param supplyDelta The number of new fragment tokens to add into circulation via expansion. * @return The total number of fragments after the supply adjustment. */ function rebase(uint256 epoch, int256 supplyDelta) external onlyMonetaryPolicy returns (uint256) { if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); } else { _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } _gonsPerFragment = TOTAL_GONS.div(_totalSupply); // From this point forward, _gonsPerFragment is taken as the source of truth. // We recalculate a new _totalSupply to be in agreement with the _gonsPerFragment // conversion rate. // This means our applied supplyDelta can deviate from the requested supplyDelta, // but this deviation is guaranteed to be < (_totalSupply^2)/(TOTAL_GONS - _totalSupply). // // In the case of _totalSupply <= MAX_UINT128 (our current supply cap), this // deviation is guaranteed to be < 1, so we can omit this step. If the supply cap is // ever increased, it must be re-included. // _totalSupply = TOTAL_GONS.div(_gonsPerFragment) emit LogRebase(epoch, _totalSupply); return _totalSupply; } // deliberately changing function signature to prevent accidental v1 deploy script reuse function initialize(string name_, string symbol_, address owner_, address migrator_, address pool1_) public onlyDeployer initializer { ERC20Detailed.initialize(name_, symbol_, uint8(DECIMALS)); Ownable.initialize(owner_); rebasePausedDeprecated = false; tokenPausedDeprecated = false; _totalSupply = INITIAL_FRAGMENTS_SUPPLY; _gonsPerFragment = TOTAL_GONS.div(_totalSupply); uint256 pool1Val = 75000 * (10 ** DECIMALS); uint256 pool1Gons = pool1Val.mul(_gonsPerFragment); _gonBalances[migrator_] = TOTAL_GONS.sub(pool1Gons); _gonBalances[pool1_] = pool1Gons; emit Transfer(address(0x0), migrator_, _totalSupply.sub(pool1Val)); emit Transfer(address(0x0), pool1_, pool1Val); } /** * @return The total number of fragments. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public view returns (uint256) { return _gonBalances[who].div(_gonsPerFragment); } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) public validRecipient(to) returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[msg.sender] = _gonBalances[msg.sender].sub(gonValue); _gonBalances[to] = _gonBalances[to].add(gonValue); emit Transfer(msg.sender, to, value); return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) public view returns (uint256) { return _allowedFragments[owner_][spender]; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) public validRecipient(to) returns (bool) { _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[from] = _gonBalances[from].sub(gonValue); _gonBalances[to] = _gonBalances[to].add(gonValue); emit Transfer(from, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } }
* @title Ownable @dev The Ownable contract has an owner address, and provides basic authorization control functions, this simplifies the implementation of "user permissions"./
contract Ownable is Initializable { address private _owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); function initialize(address sender) internal initializer { _owner = sender; } function owner() public view returns(address) { return _owner; } modifier onlyOwner() { require(isOwner()); _; } function isOwner() public view returns(bool) { return msg.sender == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(_owner); _owner = address(0); } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; }
10,702,638
[ 1, 5460, 429, 225, 1021, 14223, 6914, 6835, 711, 392, 3410, 1758, 16, 471, 8121, 5337, 6093, 3325, 4186, 16, 333, 9330, 5032, 326, 4471, 434, 315, 1355, 4371, 9654, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 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, 16351, 14223, 6914, 353, 10188, 6934, 288, 203, 225, 1758, 3238, 389, 8443, 31, 203, 203, 203, 225, 871, 14223, 9646, 5310, 16290, 27373, 12, 2867, 8808, 2416, 5541, 1769, 203, 225, 871, 14223, 9646, 5310, 1429, 4193, 12, 203, 565, 1758, 8808, 2416, 5541, 16, 203, 565, 1758, 8808, 394, 5541, 203, 225, 11272, 203, 203, 203, 203, 225, 445, 4046, 12, 2867, 5793, 13, 2713, 12562, 288, 203, 565, 389, 8443, 273, 5793, 31, 203, 225, 289, 203, 203, 225, 445, 3410, 1435, 1071, 1476, 1135, 12, 2867, 13, 288, 203, 565, 327, 389, 8443, 31, 203, 225, 289, 203, 203, 225, 9606, 1338, 5541, 1435, 288, 203, 565, 2583, 12, 291, 5541, 10663, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 445, 353, 5541, 1435, 1071, 1476, 1135, 12, 6430, 13, 288, 203, 565, 327, 1234, 18, 15330, 422, 389, 8443, 31, 203, 225, 289, 203, 203, 225, 445, 1654, 8386, 5460, 12565, 1435, 1071, 1338, 5541, 288, 203, 565, 3626, 14223, 9646, 5310, 16290, 27373, 24899, 8443, 1769, 203, 565, 389, 8443, 273, 1758, 12, 20, 1769, 203, 225, 289, 203, 203, 225, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 1338, 5541, 288, 203, 565, 389, 13866, 5460, 12565, 12, 2704, 5541, 1769, 203, 225, 289, 203, 203, 225, 445, 389, 13866, 5460, 12565, 12, 2867, 394, 5541, 13, 2713, 288, 203, 565, 2583, 12, 2704, 5541, 480, 1758, 12, 20, 10019, 203, 565, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 8443, 16, 394, 5541, 2 ]
pragma solidity >= 0.6.2 < 0.7.0; /* # Copyright (C) 2017 alianse777 # 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/>. */ /** Array wraper * min() - returns minimal array element * max() - returns maximal array element * sum() - returns sum of all array elements * set(uint []) - set array * get() - returns stored array * sort() - sorts all array elements */ //Uint Array contract UintArray { uint[] private data; function UintArrays(uint[] memory _data) public { data = new uint[](_data.length); for(uint i = 0;i < _data.length;i++) { data[i] = _data[i]; } } /** * @dev Returns minimal element in array * @return uint */ function min() public view returns (uint) { uint minimal = data[0]; for(uint i;i < data.length;i++){ if(data[i] < minimal){ minimal = data[i]; } } return minimal; } /** * @dev Returns minimal element's index * @return uint */ function imin() public view returns (uint) { uint minimal = 0; for(uint i;i < data.length;i++){ if(data[i] < data[minimal]){ minimal = i; } } return minimal; } /** * @dev Returns maximal element in array * @return uint */ function max() public view returns (uint) { uint maximal = data[0]; for(uint i;i < data.length;i++){ if(data[i] > maximal){ maximal = data[i]; } } return maximal; } /** * @dev Returns maximal element's index * @return uint */ function imax() public view returns (uint) { uint maximal = 0; for(uint i;i < data.length;i++){ if(data[i] > data[maximal]){ maximal = i; } } return maximal; } /** * @dev Compute sum of all elements * @return uint */ function sum() public view returns (uint) { uint S; for(uint i;i < data.length;i++){ S += data[i]; } return S; } /** * @dev assign new array pointer from _data * @param _data is array to assign */ function set(uint [] memory _data) public { data = _data; } /** * @dev Get the contents of array * @return uint[] */ function get() public view returns (uint[] memory) { return data; } function at(uint i) public view returns (uint) { return data[i]; } function sort_item(uint pos) internal returns (bool) { uint w_min = pos; for(uint i = pos;i < data.length;i++) { if(data[i] < data[w_min]) { w_min = i; } } if(w_min == pos) return false; uint tmp = data[pos]; data[pos] = data[w_min]; data[w_min] = tmp; return true; } /** * @dev Sort the array */ function sort() public { for(uint i = 0;i < data.length-1;i++) { sort_item(i); } } } // Int Array contract IntArray { int [] private data; function IntArrays(int [] memory _data) public { data = _data; } /** * @dev Returns minimal element in array * @return int */ function min() public view returns (int) { int minimal = data[0]; for(uint i;i < data.length;i++){ if(data[i] < minimal){ minimal = data[i]; } } return minimal; } /** * @dev Returns minimal element's index * @return uint */ function imin() public view returns (uint) { uint minimal = 0; for(uint i;i < data.length;i++){ if(data[i] < data[minimal]){ minimal = i; } } return minimal; } /** * @dev Returns maximal element in array * @return int */ function max() public view returns (int) { int maximal = data[0]; for(uint i;i < data.length;i++) { if(data[i] > maximal) { maximal = data[i]; } } return maximal; } /** * @dev Returns maximal element's index * @return uint */ function imax() public view returns (uint) { uint maximal = 0; for(uint i;i < data.length;i++){ if(data[i] > data[maximal]){ maximal = i; } } return maximal; } /** * @dev Compute sum of all elements * @return int */ function sum() public view returns (int) { int S; for(uint i;i < data.length;i++) { S += data[i]; } return S; } function set(int [] memory _data) public { data = _data; } function get() public view returns (int [] memory) { return data; } function at(uint i) public view returns (int) { return data[i]; } function sort_item(uint pos) internal returns (bool) { uint w_min = pos; for(uint i = pos;i < data.length;i++) { if(data[i] < data[w_min]) { w_min = i; } } if(w_min == pos) return false; int tmp = data[pos]; data[pos] = data[w_min]; data[w_min] = tmp; return true; } /** * @dev Sort the array */ function sort() public { for(uint i = 0;i < data.length-1;i++) { sort_item(i); } } }
* @dev Returns maximal element in array @return int/
function max() public view returns (int) { int maximal = data[0]; for(uint i;i < data.length;i++) { if(data[i] > maximal) { maximal = data[i]; } } return maximal; }
5,467,728
[ 1, 1356, 943, 2840, 930, 316, 526, 327, 509, 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 ]
[ 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, 943, 1435, 1071, 1476, 1135, 261, 474, 13, 288, 203, 3639, 509, 943, 2840, 273, 501, 63, 20, 15533, 203, 3639, 364, 12, 11890, 277, 31, 77, 411, 501, 18, 2469, 31, 77, 27245, 288, 203, 5411, 309, 12, 892, 63, 77, 65, 405, 943, 2840, 13, 288, 203, 7734, 943, 2840, 273, 501, 63, 77, 15533, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 943, 2840, 31, 203, 565, 289, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]