file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
//SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import {IERC20} from "../interfaces/IERC20.sol"; // Some of the code is taken and modified from OpenZeppelin's contracts: https://github.com/OpenZeppelin/openzeppelin-contracts/ // helper methods for interacting with ERC20 tokens that do not consistently return true/false library SafeERC20 { 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; } function safeTransfer(address _token, address _to, uint _value) internal { require(isContract(_token), "Address: call to non-contract"); (bool success, bytes memory returndata) = _token.call(abi.encodeWithSelector(IERC20.transfer.selector, _to, _value)); verifyCallResult(success, returndata, "ERC20 transfer failed"); } function safeTransferFrom(address _token, address _from, address _to, uint _value) internal { require(isContract(_token), "Address: call to non-contract"); (bool success, bytes memory returndata) = _token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, _from, _to, _value)); verifyCallResult(success, returndata, "ERC20 transferFrom failed"); } function verifyCallResult( bool _success, bytes memory _returndata, string memory _errorMessage ) internal pure { if (_success) { if (_returndata.length > 0) { // Return data is optional require(abi.decode(_returndata, (bool)), _errorMessage); } } 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); } } } }
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.
function isContract(address _account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(_account) } return size > 0; }
12,891,509
/** *Submitted for verification at Etherscan.io on 2022-03-01 */ /* __ __ __ ____ _ | \/ |/ _| ___ _ __ / ___|_ __ __ _ _ __ _ __ (_) ___ ___ | |\/| | |_ / _ \ '__| | _| '__/ _` | '_ \| '_ \| |/ _ \/ __| | | | | _| __/ | | |_| | | | (_| | | | | | | | | __/\__ \ |_| |_|_| \___|_| \____|_| \__,_|_| |_|_| |_|_|\___||___/ MferGrannies No official Discord. No Roadmap. No Drama. Just Mfing Vibing! This art came into being with the inspiration drawn from Sartoshi’s philosophy that “we all mfers” mfing around in this mfing world. Website: https://www.mfergrannies.xyz Twitter: https://twitter.com/MferGrannies */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } 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; } 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); } } pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } 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; } } pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } 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); } 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); } pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } 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; } } pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } pragma solidity >=0.7.0 <0.9.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). */ 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 public immutable maxBatchSize; // 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"); } /** * @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( _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 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 {} } pragma solidity >=0.7.0 <0.9.0; contract MferGrannies is ERC721A, Ownable { using SafeMath for uint256; using Strings for uint256; uint256 public constant MAX_PER_MINT = 50; address public constant walletOwner = 0x4dbE341DAe30e9e6986Ec104E833064721f68693; uint256 public price = 0.02 ether; uint256 public maxSupply = 6666; bool public publicSaleStarted = true; string public baseURI = "https://ipfs.mfergrannies.xyz/"; constructor() ERC721A("MferGrannies", "MFG", 50) { } function togglePublicSaleStarted() external onlyOwner { publicSaleStarted = !publicSaleStarted; } function setBaseURI(string memory _newBaseURI) external onlyOwner { baseURI = _newBaseURI; } function setPrice(uint256 _newPrice) external onlyOwner { price = _newPrice * (1 ether); } function setmaxSupply(uint256 _newMaxSupply) public onlyOwner { maxSupply = _newMaxSupply; } function _baseURI() internal view override returns (string memory) { return baseURI; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: Nonexistent token"); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), ".json")) : ""; } function mint(uint256 tokens) external payable { require(publicSaleStarted, "Public sale has not started"); require(tokens <= MAX_PER_MINT, "Cannot purchase this many tokens in a transaction"); require(totalSupply() + tokens <= maxSupply, "Minting would exceed max supply"); require(tokens > 0, "Must mint at least one token"); require(price * tokens <= msg.value, "ETH amount is incorrect"); _safeMint(_msgSender(), tokens); } function ownerMint(address to, uint256 tokens) external onlyOwner { require(totalSupply() + tokens <= maxSupply, "Minting would exceed max supply"); require(tokens > 0, "Must mint at least one token"); _safeMint(to, tokens); } function withdrawAll() public onlyOwner { uint256 balance = address(this).balance; require(balance > 0, "Insufficent balance"); _withdraw(walletOwner, address(this).balance); } function _withdraw(address _address, uint256 _amount) private { (bool success, ) = _address.call{value: _amount}(""); require(success, "Failed to withdraw Ether"); } }
Interface of the ERC165 standard, as defined in the Implementers can declare support of contract interfaces, which can then be queried by others ({ERC165Checker}). For an implementation, see {ERC165}./
interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); __ __ __ ____ _ }
6,779,698
./partial_match/8453/0x4e30112363A4a047002E93FAf1ee99b30DeDA666/sources/contracts/zCloakSBT.sol
todo : here, need to modify the EIP712 domain struct, etc./
function DOMAIN_SEPARATOR() public view virtual returns (bytes32) { return computeDomainSeparator(); }
16,737,524
// SPDX-License-Identifier: MIXED // File @violinio/defi-interfaces/contracts/[email protected] // License-Identifier: MIT pragma solidity ^0.8.0; interface IPancakeSwapMC { function BONUS_MULTIPLIER() external view returns (uint256); function deposit(uint256 _pid, uint256 _amount) external; function devaddr() external view returns (address); function emergencyWithdraw(uint256 _pid) external; function enterStaking(uint256 _amount) external; function getMultiplier(uint256 _from, uint256 _to) external view returns (uint256); function leaveStaking(uint256 _amount) external; function massUpdatePools() external; function migrate(uint256 _pid) external; function migrator() external view returns (address); function owner() external view returns (address); function poolInfo(uint256) external view returns ( address lpToken, uint256 allocPoint, uint256 lastRewardBlock, uint256 accCakePerShare ); function poolLength() external view returns (uint256); function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external; function startBlock() external view returns (uint256); function totalAllocPoint() external view returns (uint256); function updatePool(uint256 _pid) external; function userInfo(uint256, address) external view returns (uint256 amount, uint256 rewardDebt); function withdraw(uint256 _pid, uint256 _amount) external; } // File @openzeppelin/contracts/token/ERC20/[email protected] // License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/interfaces/IStrategy.sol // License-Identifier: MIT pragma solidity ^0.8.6; interface IStrategy { /** * @notice Gets the token this strategy compounds. * @dev This token might have a transfer-tax. * @dev Invariant: This variable may never change. */ function underlyingToken() external view returns (IERC20); /** * @notice Gets the total amount of tokens either idle in this strategy or staked in an underlying strategy. */ function totalUnderlying() external view returns (uint256 totalUnderlying); /** * @notice Gets the total amount of tokens either idle in this strategy or staked in an underlying strategy and only the tokens actually staked. */ function totalUnderlyingAndStaked() external view returns (uint256 totalUnderlying, uint256 totalUnderlyingStaked); /** * @notice The panic function unstakes all staked funds from the strategy and leaves them idle in the strategy for withdrawal * @dev Authority: This function must only be callable by the VaultChef. */ function panic() external; /** * @notice Executes a harvest on the underlying vaultchef. * @dev Authority: This function must only be callable by the vaultchef. */ function harvest() external; /** * @notice Deposits `amount` amount of underlying tokens in the underlying strategy * @dev Authority: This function must only be callable by the VaultChef. */ function deposit(uint256 amount) external; /** * @notice Withdraws `amount` amount of underlying tokens to `to`. * @dev Authority: This function must only be callable by the VaultChef. */ function withdraw(address to, uint256 amount) external; /** * @notice Withdraws `amount` amount of `token` to `to`. * @notice This function is used to withdraw non-staking and non-native tokens accidentally sent to the strategy. * @notice It will also be used to withdraw tokens airdropped to the strategies. * @notice The underlying token can never be withdrawn through this method because VaultChef prevents it. * @dev Requirement: This function should in no way allow withdrawal of staking tokens * @dev Requirement: This function should in no way allow for the decline in shares or share value (this is also checked in the VaultChef); * @dev Validation is already done in the VaultChef that the staking token cannot be withdrawn. * @dev Authority: This function must only be callable by the VaultChef. */ function inCaseTokensGetStuck( IERC20 token, uint256 amount, address to ) external; } // File @openzeppelin/contracts/utils/introspection/[email protected] // License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/token/ERC1155/[email protected] // License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // File contracts/interfaces/IVaultChefCore.sol // License-Identifier: MIT pragma solidity ^0.8.6; /** * @notice The VaultChef is a vault management contract that manages vaults, their strategies and the share positions of investors in these vaults. * @notice Positions are not hardcoded into the contract like traditional staking contracts, instead they are managed as ERC-1155 receipt tokens. * @notice This receipt-token mechanism is supposed to simplify zapping and other derivative protocols. * @dev The VaultChef contract has the following design principles. * @dev 1. Simplicity of Strategies: Strategies should be as simple as possible. * @dev 2. Control of Governance: Governance should never be able to steal underlying funds. * @dev 3. Auditability: It should be easy for third-party reviewers to assess the safety of the VaultChef. */ interface IVaultChefCore is IERC1155 { /// @notice A vault is a strategy users can stake underlying tokens in to receive a share of the vault value. struct Vault { /// @notice The token this strategy will compound. IERC20 underlyingToken; /// @notice The timestamp of the last harvest, set to zero while no harvests have happened. uint96 lastHarvestTimestamp; /// @notice The strategy contract. IStrategy strategy; /// @notice The performance fee portion of the harvests that is sent to the feeAddress, denominated by 10,000. uint16 performanceFeeBP; /// @notice Whether deposits are currently paused. bool paused; /// @notice Whether the vault has panicked which means the funds are pulled from the strategy and it is paused forever. bool panicked; } /** * @notice Deposit `underlyingAmount` amount of underlying tokens into the vault and receive `sharesReceived` proportional to the actually staked amount. * @notice Deposits mint `sharesReceived` receipt tokens as ERC-1155 tokens to msg.sender with the tokenId equal to the vaultId. * @notice The tokens are transferred from `msg.sender` which requires approval if pulled is set to false, otherwise `msg.sender` needs to implement IPullDepositor. * @param vaultId The id of the vault. * @param underlyingAmount The intended amount of tokens to deposit (this might not equal the actual deposited amount due to tx/stake fees or the pull mechanism). * @param pulled Uses a pull-based deposit hook if set to true, otherwise traditional safeTransferFrom. The pull-based mechanism allows the depositor to send tokens using a hook. * @param minSharesReceived The minimum amount of shares that must be received, or the transaction reverts. * @dev This pull-based methodology is extremely valuable for zapping transfer-tax tokens more economically. * @dev `msg.sender` must be a smart contract implementing the `IPullDepositor` interface. * @return sharesReceived The number of shares minted to the msg.sender. */ function depositUnderlying( uint256 vaultId, uint256 underlyingAmount, bool pulled, uint256 minSharesReceived ) external returns (uint256 sharesReceived); /** * @notice Withdraws `shares` from the vault into underlying tokens to the `msg.sender`. * @notice Burns `shares` receipt tokens from the `msg.sender`. * @param vaultId The id of the vault. * @param shares The amount of shares to burn, underlying tokens will be sent to msg.sender proportionally. * @param minUnderlyingReceived The minimum amount of underlying tokens that must be received, or the transaction reverts. */ function withdrawShares( uint256 vaultId, uint256 shares, uint256 minUnderlyingReceived ) external returns (uint256 underlyingReceived); /** * @notice Withdraws `shares` from the vault into underlying tokens to the `to` address. * @notice To prevent phishing, we require msg.sender to be a contract as this is intended for more economical zapping of transfer-tax token withdrawals. * @notice Burns `shares` receipt tokens from the `msg.sender`. * @param vaultId The id of the vault. * @param shares The amount of shares to burn, underlying tokens will be sent to msg.sender proportionally. * @param minUnderlyingReceived The minimum amount of underlying tokens that must be received, or the transaction reverts. */ function withdrawSharesTo( uint256 vaultId, uint256 shares, uint256 minUnderlyingReceived, address to ) external returns (uint256 underlyingReceived); /** * @notice Total amount of shares in circulation for a given vaultId. * @param vaultId The id of the vault. * @return The total number of shares currently in circulation. */ function totalSupply(uint256 vaultId) external view returns (uint256); /** * @notice Calls harvest on the underlying strategy to compound pending rewards to underlying tokens. * @notice The performance fee is minted to the owner as shares, it can never be greater than 5% of the underlyingIncrease. * @return underlyingIncrease The amount of underlying tokens generated. * @dev Can only be called by owner. */ function harvest(uint256 vaultId) external returns (uint256 underlyingIncrease); /** * @notice Adds a new vault to the vaultchef. * @param strategy The strategy contract that manages the allocation of the funds for this vault, also defines the underlying token * @param performanceFeeBP The percentage of the harvest rewards that are given to the governance, denominated by 10,000 and maximum 5%. * @dev Can only be called by owner. */ function addVault(IStrategy strategy, uint16 performanceFeeBP) external; /** * @notice Updates the performanceFee of the vault. * @param vaultId The id of the vault. * @param performanceFeeBP The percentage of the harvest rewards that are given to the governance, denominated by 10,000 and maximum 5%. * @dev Can only be called by owner. */ function setVault(uint256 vaultId, uint16 performanceFeeBP) external; /** * @notice Allows the `pullDepositor` to create pull-based deposits (useful for zapping contract). * @notice Having a whitelist is not necessary for this functionality as it is safe but upon defensive code recommendations one was added in. * @dev Can only be called by owner. */ function setPullDepositor(address pullDepositor, bool isAllowed) external; /** * @notice Withdraws funds from the underlying staking contract to the strategy and irreversibly pauses the vault. * @param vaultId The id of the vault. * @dev Can only be called by owner. */ function panicVault(uint256 vaultId) external; /** * @notice Returns true if there is a vault associated with the `vaultId`. * @param vaultId The id of the vault. */ function isValidVault(uint256 vaultId) external returns (bool); /** * @notice Returns the Vault information of the vault at `vaultId`, returns if non-existent. * @param vaultId The id of the vault. */ function vaultInfo(uint256 vaultId) external returns (IERC20 underlyingToken, uint96 lastHarvestTimestamp, IStrategy strategy, uint16 performanceFeeBP, bool paused, bool panicked); /** * @notice Pauses the vault which means deposits and harvests are no longer permitted, reverts if already set to the desired value. * @param vaultId The id of the vault. * @param paused True to pause, false to unpause. * @dev Can only be called by owner. */ function pauseVault(uint256 vaultId, bool paused) external; /** * @notice Transfers tokens from the VaultChef to the `to` address. * @notice Cannot be abused by governance since the protocol never ever transfers tokens to the VaultChef. Any tokens stored there are accidentally sent there. * @param token The token to withdraw from the VaultChef. * @param to The address to send the token to. * @dev Can only be called by owner. */ function inCaseTokensGetStuck(IERC20 token, address to) external; /** * @notice Transfers tokens from the underlying strategy to the `to` address. * @notice Cannot be abused by governance since VaultChef prevents token to be equal to the underlying token. * @param token The token to withdraw from the strategy. * @param to The address to send the token to. * @param amount The amount of tokens to withdraw. * @dev Can only be called by owner. */ function inCaseVaultTokensGetStuck( uint256 vaultId, IERC20 token, address to, uint256 amount ) external; } // File contracts/interfaces/IMasterChef.sol // License-Identifier: MIT pragma solidity ^0.8.6; /// @dev The VaultChef implements the masterchef interface for compatibility with third-party tools. interface IMasterChef { /// @dev An active vault has a dummy allocPoint of 1 while an inactive one has an allocPoint of zero. /// @dev This is done for better compatibility with third-party tools. function poolInfo(uint256 pid) external view returns ( IERC20 lpToken, uint256 allocPoint, uint256 lastRewardBlock, uint256 accTokenPerShare ); function userInfo(uint256 pid, address user) external view returns (uint256 amount, uint256 rewardDebt); function startBlock() external view returns (uint256); function poolLength() external view returns (uint256); /// @dev Returns the total number of active vaults. function totalAllocPoint() external view returns (uint256); function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function emergencyWithdraw(uint256 _pid) external; } // File contracts/interfaces/IERC20Metadata.sol // License-Identifier: MIT // Based on: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/1b27c13096d6e4389d62e7b0766a1db53fbb3f1b/contracts/token/ERC20/extensions/IERC20Metadata.sol pragma solidity ^0.8.6; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata { /** * @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/IVaultChefWrapper.sol // License-Identifier: MIT pragma solidity ^0.8.6; interface IVaultChefWrapper is IMasterChef, IERC20Metadata{ /** * @notice Interface function to fetch the total underlying tokens inside a vault. * @notice Calls the totalUnderlying function on the vault strategy. * @param vaultId The id of the vault. */ function totalUnderlying(uint256 vaultId) external view returns (uint256); /** * @notice Changes the ERC-20 metadata for etherscan listing. * @param newName The new ERC-20-like token name. * @param newSymbol The new ERC-20-like token symbol. * @param newDecimals The new ERC-20-like token decimals. */ function changeMetadata( string memory newName, string memory newSymbol, uint8 newDecimals ) external; /** * @notice Sets the ERC-1155 metadata URI. * @param newURI The new ERC-1155 metadata URI. */ function setURI(string memory newURI) external; /// @notice mapping that returns true if the strategy is set as a vault. function strategyExists(IStrategy strategy) external view returns(bool); /// @notice Utility mapping for UI to figure out the vault id of a strategy. function strategyVaultId(IStrategy strategy) external view returns(uint256); } // File contracts/interfaces/IVaultChef.sol // License-Identifier: MIT pragma solidity ^0.8.6; /// @notice Interface for derivative protocols. interface IVaultChef is IVaultChefWrapper, IVaultChefCore { function owner() external view returns (address); } // File contracts/interfaces/ISubFactory.sol // License-Identifier: MIT pragma solidity ^0.8.6; interface ISubFactory { function deployStrategy( IVaultChef vaultChef, IERC20 underlyingToken, bytes calldata projectData, bytes calldata strategyData ) external returns (IStrategy); } // File @openzeppelin/contracts/utils/[email protected] // License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/utils/[email protected] // License-Identifier: MIT pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/interfaces/IZapHandler.sol // License-Identifier: MIT pragma solidity ^0.8.6; /// @notice The IZap interface allows contracts to swap a token for another token without having to directly interact with verbose AMMs directly. /// @notice It furthermore allows to zap to and from an LP pair within a single transaction. interface IZapHandler { struct Factory { /// @dev The address of the factory. address factory; /// @dev The fee nominator of the AMM, usually set to 997 for a 0.3% fee. uint32 amountsOutNominator; /// @dev The fee denominator of the AMM, usually set to 1000. uint32 amountsOutDenominator; } function setFactory( address factory, uint32 amountsOutNominator, uint32 amountsOutDenominator ) external; function setRoute( IERC20 from, IERC20 to, address[] memory inputRoute ) external; function factories(address factoryAddress) external view returns (Factory memory); function routeLength(IERC20 token0, IERC20 token1) external view returns (uint256); function owner() external view returns (address); } // File contracts/interfaces/IZap.sol // License-Identifier: MIT pragma solidity ^0.8.6; /// @notice The IZap interface allows contracts to swap a token for another token without having to directly interact with verbose AMMs directly. /// @notice It furthermore allows to zap to and from an LP pair within a single transaction. interface IZap { /** * @notice Swap `amount` of `fromToken` to `toToken` and send them to the `recipient`. * @notice The `fromToken` and `toToken` arguments can be AMM pairs. * @notice Reverts if the `recipient` received less tokens than `minReceived`. * @notice Requires approval. * @param fromToken The token to take from `msg.sender` and exchange for `toToken`. * @param toToken The token that will be bought and sent to the `recipient`. * @param recipient The destination address to receive the `toToken`. * @param amount The amount that the zapper should take from the `msg.sender` and swap. * @param minReceived The minimum amount of `toToken` the `recipient` should receive. Otherwise the transaction reverts. */ function swapERC20(IERC20 fromToken, IERC20 toToken, address recipient, uint256 amount, uint256 minReceived) external returns (uint256 received); /** * @notice Swap `amount` of `fromToken` to `toToken` and send them to the `msg.sender`. * @notice The `fromToken` and `toToken` arguments can be AMM pairs. * @notice Requires approval. * @param fromToken The token to take from `msg.sender` and exchange for `toToken`. * @param toToken The token that will be bought and sent to the `msg.sender`. * @param amount The amount that the zapper should take from the `msg.sender` and swap. */ function swapERC20Fast(IERC20 fromToken, IERC20 toToken, uint256 amount) external; function implementation() external view returns (IZapHandler); } // File contracts/strategies/BaseStrategy.sol // License-Identifier: MIT pragma solidity ^0.8.6; /** * @notice The BaseStrategy implements reusable logic for all Violin strategies that earn some single asset "rewardToken". * @dev It exposes a very simple interface which the actual strategies can implement. * @dev The zapper contract does not have excessive privileges and withdrawals should always be possible even if it reverts. */ abstract contract BaseStrategy is IStrategy { using SafeERC20 for IERC20; /// @dev Set to true once _initializeBase is called by the implementation. bool initialized; /// @dev The vaultchef contract this strategy is managed by. IVaultChef public vaultchef; /// @dev The zapper contract to swap earned for underlying tokens. IZap public zap; /// @dev The token that is actually staked into the underlying protocol. IERC20 public override underlyingToken; /// @dev The token the underlying protocol gives as a reward. IERC20 public rewardToken; modifier onlyVaultchef() { require(msg.sender == address(vaultchef), "!vaultchef"); _; } modifier initializer() { require(!initialized, "!already initialized"); _; // We unsure that the implementation has called _initializeBase during the external initialize function. require(initialized, "!not initialized"); } /// @notice Initializes the base strategy variables, should be called together with contract deployment by a contract factory. function _initializeBase( IVaultChef _vaultchef, IZap _zap, IERC20 _underlyingToken, IERC20 _rewardToken ) internal { assert(!initialized); // No implementation should call _initializeBase without using the initialize modifier, hence we can assert. initialized = true; vaultchef = _vaultchef; zap = _zap; underlyingToken = _underlyingToken; rewardToken = _rewardToken; } /// @notice Deposits `amount` amount of underlying tokens in the underlying strategy. /// @dev Authority: This function must only be callable by the VaultChef. function deposit(uint256 amount) external override onlyVaultchef { _deposit(amount); } /// @notice Withdraws `amount` amount of underlying tokens to `to`. /// @dev Authority: This function must only be callable by the VaultChef. function withdraw(address to, uint256 amount) external override onlyVaultchef { uint256 idleUnderlying = underlyingToken.balanceOf(address(this)); if (idleUnderlying < amount) { _withdraw(amount - idleUnderlying); } uint256 toWithdraw = underlyingToken.balanceOf(address(this)); if (amount < toWithdraw) { toWithdraw = amount; } underlyingToken.safeTransfer(to, toWithdraw); } /// @notice Withdraws all funds from the underlying staking contract into the strategy. /// @dev This should ideally always work (eg. emergencyWithdraw instead of a normal withdraw on masterchefs). function panic() external override onlyVaultchef { _panic(); } /// @notice Harvests the reward token from the underlying protocol, converts it to underlying tokens and deposits it again. /// @dev The whole rewardToken balance will be converted to underlying tokens, this might include tokens send to the contract by accident. /// @dev There is no way to exploit this, even when reward and earned tokens are identical since the vaultchef does not allow harvesting after a panic occurs. function harvest() external override onlyVaultchef { _harvest(); if (rewardToken != underlyingToken) { uint256 rewardBalance = rewardToken.balanceOf(address(this)); if (rewardBalance > 0) { rewardToken.approve(address(zap), rewardBalance); zap.swapERC20Fast(rewardToken, underlyingToken, rewardBalance); } } uint256 toDeposit = underlyingToken.balanceOf(address(this)); if (toDeposit > 0) { _deposit(toDeposit); } } /// @notice Withdraws stuck ERC-20 tokens inside the strategy contract, cannot be staking or underlying. function inCaseTokensGetStuck( IERC20 token, uint256 amount, address to ) external override onlyVaultchef { require( token != underlyingToken && token != rewardToken, "invalid token" ); require(!isTokenProhibited(token), "token prohibited"); token.safeTransfer(to, amount); } function isTokenProhibited(IERC20) internal virtual returns(bool) { return false; } /// @notice Gets the total amount of tokens either idle in this strategy or staked in an underlying strategy. function totalUnderlying() external view override returns (uint256) { return underlyingToken.balanceOf(address(this)) + _totalStaked(); } /// @notice Gets the total amount of tokens either idle in this strategy or staked in an underlying strategy and only the tokens actually staked. function totalUnderlyingAndStaked() external view override returns (uint256 _totalUnderlying, uint256 _totalUnderlyingStaked) { uint256 totalStaked = _totalStaked(); return ( underlyingToken.balanceOf(address(this)) + totalStaked, totalStaked ); } ///** INTERFACE FOR IMPLEMENTATIONS **/ /// @notice Should withdraw all staked funds to the strategy. function _panic() internal virtual; /// @notice Should harvest all earned rewardTokens to the strategy. function _harvest() internal virtual; /// @notice Should deposit `amount` from the strategy into the staking contract. function _deposit(uint256 amount) internal virtual; /// @notice Should withdraw `amount` from the staking contract, it is okay if there is a transfer tax and less is actually received. function _withdraw(uint256 amount) internal virtual; /// @notice Should withdraw `amount` from the staking contract, it is okay if there is a transfer tax and less is actually received. function _totalStaked() internal view virtual returns (uint256); } // File contracts/strategies/StrategyPancakeSwap.sol // License-Identifier: MIT pragma solidity ^0.8.6; contract StrategyPancakeSwap is BaseStrategy { IPancakeSwapMC public masterchef; uint256 public pid; address deployer; constructor() { deployer = msg.sender; } function initialize( IVaultChef _vaultchef, IZap _zap, IERC20 _underlyingToken, IERC20 _rewardToken, IPancakeSwapMC _masterchef, uint256 _pid ) external initializer { require(msg.sender == deployer); _initializeBase(_vaultchef, _zap, _underlyingToken, _rewardToken); masterchef = _masterchef; pid = _pid; } function _panic() internal override { masterchef.emergencyWithdraw(pid); } function _harvest() internal override { masterchef.deposit(pid, 0); } function _deposit(uint256 amount) internal override { underlyingToken.approve(address(masterchef), amount); masterchef.deposit(pid, amount); } function _withdraw(uint256 amount) internal override { masterchef.withdraw(pid, amount); } function _totalStaked() internal view override returns (uint256) { (uint256 amount, ) = masterchef.userInfo(pid, address(this)); return amount; } } // File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected] // License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // File @openzeppelin/contracts-upgradeable/utils/structs/[email protected] // License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // File @openzeppelin/contracts-upgradeable/access/[email protected] // License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // File @openzeppelin/contracts-upgradeable/access/[email protected] // License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // File @openzeppelin/contracts-upgradeable/utils/[email protected] // License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/utils/[email protected] // License-Identifier: MIT 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); } } // File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected] // License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface 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); } // File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected] // License-Identifier: MIT 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 ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/access/[email protected] // License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // File @openzeppelin/contracts-upgradeable/access/[email protected] // License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); } function __AccessControlEnumerable_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } uint256[49] private __gap; } // File contracts/factories/StrategyFactory.sol // License-Identifier: MIT pragma solidity ^0.8.6; /// @notice The strategy factory is a utility contracts used by Violin to deploy new strategies more swiftly and securely. /// @notice The admin can register strategy types together with a SubFactory that creates instances of the relevant strategy type. /// @notice Examples of strategy types are MC_PCS_V1, MC_GOOSE_V1, MC_PANTHER_V1... /// @notice Once a few types are registered, new strategies can be easily deployed by registering the relevant project and then instantiating strategies on that project. /// @dev All strategy types, projects and individual strategies are stored as keccak256 hashes. The deployed strategies are identified by keccak256(keccak256(projectId), keccak256(strategyId)). /// @dev VAULTCHEF AUTH: The StrategyFactory must have the ADD_VAULT_ROLE on the governor. /// @dev ZAPGOVERNANCE AUTH: The StrategyFactory must have the /// TODO: There is no createVault function! contract StrategyFactory is AccessControlEnumerableUpgradeable { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.Bytes32Set; /// @notice The instance of the vaultChef to deploy strategies to. IVaultChef public vaultChef; /// @notice The zapper IZap public zap; //** STRATEGY TYPES **/ /// @notice strategyTypes contains all registered hashed strategy types. EnumerableSetUpgradeable.Bytes32Set private strategyTypes; /// @notice Returns the registered subfactory of the strategy type. The subfactory is responsible for instantiating factories. mapping(bytes32 => ISubFactory) public subfactoryByType; mapping(address => bool) public isSubfactory; //** PROJECTS **/ /// @notice All registered projects. EnumerableSetUpgradeable.Bytes32Set private projects; /// @notice The associated strategy type hash of the project. All strategies under the project will thus be deployed using the subfactory of this strategy type. mapping(bytes32 => bytes32) public projectStrategyType; /// @notice Generic parameters that will always be forwarded to the subfactory. This could for example be the native token. mapping(bytes32 => bytes) public projectParams; /// @notice Metadata associated with the project that can be used on the frontend, expected to be encoded in UTF-8 JSON. /// @notice Even though not ideomatic, this is a cheap solution to avoid infrastructure downtime within the first months after launch. mapping(bytes32 => bytes) public projectMetadata; /// @notice List of strategies registered for the project. mapping(bytes32 => EnumerableSetUpgradeable.Bytes32Set) private projectStrategies; //** STRATEGIES **/ /// @notice All registered strategies. /// @dev These are identified as keccak256(abi.encodePacked(keccak256(projectId), keccak256(strategyId))). EnumerableSetUpgradeable.Bytes32Set private strategies; /// @notice Metadata associated with the strategy that can be used on the frontend, expected to be encoded in UTF-8 JSON. /// @notice Even though not ideomatic, this is a cheap solution to avoid infrastructure downtime within the first months after launch. mapping(bytes32 => bytes) public strategyMetadata; /// @notice Gets the vaultId associated with the strategyId. mapping(bytes32 => uint256) private strategyToVaultId; /// @notice Gets the strategy id associated with the vaultId. mapping(uint256 => bytes32) public vaultIdToStrategy; /// @notice gets all strategy ids associated with an underlying token. mapping(IERC20 => EnumerableSetUpgradeable.Bytes32Set) private underlyingToStrategies; bytes32 public constant REGISTER_STRATEGY_ROLE = keccak256("REGISTER_STRATEGY_ROLE"); bytes32 public constant REGISTER_PROJECT_ROLE = keccak256("REGISTER_PROJECT_ROLE"); bytes32 public constant CREATE_VAULT_ROLE = keccak256("CREATE_VAULT_ROLE"); event StrategyTypeAdded( bytes32 indexed strategyType, ISubFactory indexed subfactory ); event ProjectRegistered( bytes32 indexed projectId, bytes32 indexed strategyType, bool indexed isUpdate ); event VaultRegistered( uint256 indexed vaultId, bytes32 indexed projectId, bytes32 indexed strategyId, bool isUpdate ); function initialize(IVaultChef _vaultChef, IZap _zap, address owner) external initializer { __AccessControlEnumerable_init(); vaultChef = _vaultChef; zap = _zap; vaultChef.poolLength(); // validate vaultChef _setupRole(DEFAULT_ADMIN_ROLE, owner); _setupRole(REGISTER_STRATEGY_ROLE, owner); _setupRole(REGISTER_PROJECT_ROLE, owner); _setupRole(CREATE_VAULT_ROLE, owner); } function registerStrategyType( string calldata strategyType, ISubFactory subfactory ) external onlyRole(REGISTER_STRATEGY_ROLE) { registerStrategyTypeRaw( keccak256(abi.encodePacked(strategyType)), subfactory ); } function registerStrategyTypeRaw( bytes32 strategyType, ISubFactory subfactory ) public onlyRole(REGISTER_STRATEGY_ROLE) { require(!strategyTypes.contains(strategyType), "!exists"); strategyTypes.add(strategyType); subfactoryByType[strategyType] = subfactory; isSubfactory[address(subfactory)] = true; emit StrategyTypeAdded(strategyType, subfactory); } function registerProject( string calldata projectId, string calldata strategyType, bytes calldata params, bytes calldata metadata ) external onlyRole(REGISTER_PROJECT_ROLE) { registerProjectRaw( keccak256(abi.encodePacked(projectId)), keccak256(abi.encodePacked(strategyType)), params, metadata ); } function registerProjectRaw( bytes32 projectId, bytes32 strategyType, bytes calldata params, bytes calldata metadata ) public onlyRole(REGISTER_PROJECT_ROLE) { require( strategyTypes.contains(strategyType), "!strategyType not found" ); bool exists = projects.contains(projectId); projectStrategyType[projectId] = strategyType; projectParams[projectId] = params; projectMetadata[projectId] = metadata; emit ProjectRegistered(projectId, strategyType, exists); } struct CreateVaultVars { bytes32 strategyUID; bool exists; IStrategy strategy; uint256 vaultId; bytes projectParams; } function createVault( string calldata projectId, string calldata strategyId, IERC20 underlyingToken, bytes calldata params, bytes calldata metadata, uint16 performanceFee ) external onlyRole(CREATE_VAULT_ROLE) returns (uint256, IStrategy) { return createVaultRaw( keccak256(abi.encodePacked(projectId)), keccak256(abi.encodePacked(strategyId)), underlyingToken, params, metadata, performanceFee ); } function createVaultRaw( bytes32 projectId, bytes32 strategyId, IERC20 underlyingToken, bytes calldata params, bytes calldata metadata, uint16 performanceFee ) public onlyRole(CREATE_VAULT_ROLE) returns (uint256, IStrategy) { CreateVaultVars memory vars; vars.strategyUID = getStrategyUID(projectId, strategyId); vars.exists = strategies.contains(vars.strategyUID); vars.projectParams = projectParams[projectId]; vars.strategy = subfactoryByType[projectStrategyType[projectId]] .deployStrategy( vaultChef, underlyingToken, vars.projectParams, params ); vars.vaultId = vaultChef.poolLength(); IVaultChef(vaultChef.owner()).addVault(vars.strategy, performanceFee); // .owner to get the governor which inherits the vaultchef interface strategyMetadata[vars.strategyUID] = metadata; // Indexing projectStrategies[projectId].add(vars.strategyUID); vaultIdToStrategy[vars.vaultId] = vars.strategyUID; strategyToVaultId[vars.strategyUID] = vars.vaultId; underlyingToStrategies[vars.strategy.underlyingToken()].add( vars.strategyUID ); emit VaultRegistered(vars.vaultId, projectId, strategyId, vars.exists); return (vars.vaultId, vars.strategy); } function setRoute(address[] calldata route) external { require(isSubfactory[msg.sender], "!subfactory"); // Only set the route if it actually exists. if (route.length > 0) { IERC20 from = IERC20(route[0]); IERC20 to = IERC20(route[route.length - 1]); IZapHandler zapHandler = IZapHandler( IZapHandler(zap.implementation()).owner() ); // go to the governance contract which mimics the IZapHandler interface if (zapHandler.routeLength(from, to) == 0) { zapHandler.setRoute(from, to, route); } } } function getStrategyUID(bytes32 projectId, bytes32 strategyId) internal pure returns (bytes32) { return keccak256(abi.encodePacked(projectId, strategyId)); } //** VIEW FUNCTIONS **// //** strategy types **/ /// @notice Returns whether the unhashed `strategyType` is registered. function isStrategyType(string calldata strategyType) external view returns (bool) { return isStrategyTypeRaw(keccak256(abi.encodePacked(strategyType))); } /// @notice Returns whether the hashed `strategyType` is registered. function isStrategyTypeRaw(bytes32 strategyType) public view returns (bool) { return strategyTypes.contains(strategyType); } /// @notice Gets the length of the strategyType listing. function getStrategyTypeLength() public view returns (uint256) { return strategyTypes.length(); } /// @notice Gets the strategyType hash at a specific index in the listing. function getStrategyTypeAt(uint256 index) public view returns (bytes32) { return strategyTypes.at(index); } /// @notice Lists the strategyType hashes within a specific range in the listing. function getStrategyTypes(uint256 from, uint256 amount) public view returns (bytes32[] memory) { return getPaginated(strategyTypes, from, amount); } //** projects **/ /// @notice Returns whether the unhashed `projectId` is registered. function isProject(string calldata projectId) external view returns (bool) { return isStrategyTypeRaw(keccak256(abi.encodePacked(projectId))); } /// @notice Returns whether the hashed `projectId` is registered. function isProjectRaw(bytes32 projectId) public view returns (bool) { return strategyTypes.contains(projectId); } /// @notice Gets the length of the projects listing. function getProjectsLength() public view returns (uint256) { return projects.length(); } /// @notice Gets the project hash at a specific index in the listing. function getProjectAt(uint256 index) public view returns (bytes32) { return projects.at(index); } /// @notice Lists the project hashes within a specific range in the listing. function getProjects(uint256 from, uint256 amount) public view returns (bytes32[] memory) { return getPaginated(projects, from, amount); } /// @notice Gets the length (number) of strategies of a project listing. function getProjectStrategiesLength(string calldata projectId) external view returns (uint256) { return getProjectStrategiesLengthRaw( keccak256(abi.encodePacked(projectId)) ); } /// @notice Gets the length (number) of strategies of a project listing. function getProjectStrategiesLengthRaw(bytes32 projectId) public view returns (uint256) { return projectStrategies[projectId].length(); } /// @notice Gets the project's strategy hash at a specific index in the listing. function getProjectStrategyAt(string calldata projectId, uint256 index) external view returns (bytes32) { return getProjectStrategyAtRaw( keccak256(abi.encodePacked(projectId)), index ); } /// @notice Gets the project's strategy hash at a specific index in the listing. function getProjectStrategyAtRaw(bytes32 projectId, uint256 index) public view returns (bytes32) { return projectStrategies[projectId].at(index); } /// @notice Lists the project's strategy hashes within a specific range in the listing. function getProjectStrategies( string calldata projectId, uint256 from, uint256 amount ) external view returns (bytes32[] memory) { return getProjectStrategiesRaw( keccak256(abi.encodePacked(projectId)), from, amount ); } /// @notice Lists the project's strategy hashes within a specific range in the listing. function getProjectStrategiesRaw( bytes32 projectId, uint256 from, uint256 amount ) public view returns (bytes32[] memory) { return getPaginated(projectStrategies[projectId], from, amount); } //** strategies **/ /// @notice Gets the length (number) of strategies of a project listing. function getStrategiesLength() external view returns (uint256) { return strategies.length(); } /// @notice Gets the strategy hash at a specific index in the listing. function getStrategyAt(uint256 index) external view returns (bytes32) { return strategies.at(index); } /// @notice Lists the strategy hashes within a specific range in the listing. function getStrategies(uint256 from, uint256 amount) external view returns (bytes32[] memory) { return getPaginated(strategies, from, amount); } //** underlying */ /// @notice Gets the length (number) of strategies of a project listing. function getUnderlyingStrategiesLength(IERC20 token) external view returns (uint256) { return underlyingToStrategies[token].length(); } /// @notice Gets the underlying tokens's strategy hash at a specific index in the listing. function getUnderlyingStrategyAt(IERC20 token, uint256 index) external view returns (bytes32) { return underlyingToStrategies[token].at(index); } /// @notice Lists the underlying tokens's strategy hashes within a specific range in the listing. function getUnderlyingStrategies( IERC20 token, uint256 from, uint256 amount ) external view returns (bytes32[] memory) { return getPaginated(underlyingToStrategies[token], from, amount); } function getPaginated( EnumerableSetUpgradeable.Bytes32Set storage set, uint256 from, uint256 amount ) private view returns (bytes32[] memory) { uint256 length = set.length(); if (from >= length) { return new bytes32[](0); } if (from + amount > length) { amount = length - from; } bytes32[] memory types = new bytes32[](amount); for (uint256 i = 0; i < amount; i++) { types[i] == strategyTypes.at(from + i); } return types; } } // File contracts/factories/PancakeSwapFactory.sol // License-Identifier: MIT pragma solidity ^0.8.6; /** * Project data: (address masterchef, address rewardToken) * Strategy data: (uint256 pid) */ contract PancakeSwapFactory is ISubFactory { StrategyFactory public immutable strategyFactory; IZap public zap; constructor(StrategyFactory _strategyFactory, IZap _zap) { strategyFactory = _strategyFactory; zap = _zap; } function deployStrategy( IVaultChef vaultChef, IERC20 underlyingToken, bytes calldata projectData, bytes calldata strategyData ) external override returns (IStrategy) { require(msg.sender == address(strategyFactory)); (address masterchefAddress, address rewardToken) = abi.decode(projectData, (address, address)); (uint256 pid, address[] memory route) = abi.decode(strategyData, (uint256, address[])); // validate underlying masterchef IPancakeSwapMC masterchef = IPancakeSwapMC(masterchefAddress); _validateMasterchef(masterchef, underlyingToken, pid); // initialize strategy StrategyPancakeSwap strategy = new StrategyPancakeSwap(); strategy.initialize(vaultChef, zap, underlyingToken, IERC20(rewardToken), masterchef, pid); // set swap route if (route.length > 0) { strategyFactory.setRoute(route); } return strategy; } function _validateMasterchef(IPancakeSwapMC masterchef, IERC20 /*underlyingToken*/, uint256 pid) internal view { try masterchef.poolLength() returns ( uint256 length ) { require(pid < length, "pool nonexistent"); } catch { revert("!incorrect poolLength"); } try masterchef.userInfo(pid, address(this)) returns (uint256 amount, uint256 rewardDebt) { amount;rewardDebt;//sh } catch { revert("!incorrect userInfo"); } } }
validate underlying masterchef initialize strategy set swap route
function deployStrategy( IVaultChef vaultChef, IERC20 underlyingToken, bytes calldata projectData, bytes calldata strategyData ) external override returns (IStrategy) { require(msg.sender == address(strategyFactory)); (address masterchefAddress, address rewardToken) = abi.decode(projectData, (address, address)); (uint256 pid, address[] memory route) = abi.decode(strategyData, (uint256, address[])); IPancakeSwapMC masterchef = IPancakeSwapMC(masterchefAddress); _validateMasterchef(masterchef, underlyingToken, pid); StrategyPancakeSwap strategy = new StrategyPancakeSwap(); strategy.initialize(vaultChef, zap, underlyingToken, IERC20(rewardToken), masterchef, pid); if (route.length > 0) { strategyFactory.setRoute(route); } return strategy; }
993,951
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; // OpenZeppelin import "./openzeppelin-solidity/contracts/ERC20/SafeERC20.sol"; import "./openzeppelin-solidity/contracts/ERC20/IERC20.sol"; import "./openzeppelin-solidity/contracts/SafeMath.sol"; // Inheritance import './interfaces/IExecutionPrice.sol'; // Interfaces import './interfaces/IPriceManager.sol'; import './interfaces/ILiquidityBond.sol'; contract ExecutionPrice is IExecutionPrice { using SafeERC20 for IERC20; using SafeMath for uint256; struct Order { address user; uint256 quantity; uint256 amountFilled; } struct Params { uint256 price; // Number of TGEN per bond token uint256 maximumNumberOfInvestors; uint256 tradingFee; uint256 minimumOrderSize; address owner; } uint256 constant MIN_MINIMUM_ORDER_VALUE = 1e18; // $1 uint256 constant MAX_MINIMUM_ORDER_VALUE = 1e20; // $100 uint256 constant MIN_MAXIMUM_NUMBER_OF_INVESTORS = 10; uint256 constant MAX_MAXIMUM_NUMBER_OF_INVESTORS = 50; uint256 constant MAX_TRADING_FEE = 300; // 3%, with 10000 as denominator IERC20 immutable TGEN; IERC20 immutable bondToken; address factory; address immutable marketplace; address immutable xTGEN; Params public params; uint256 public startIndex = 1; uint256 public endIndex = 1; // Number of tokens in the queue. // When the queue is a 'buy queue', this represents uint256 public numberOfTokensAvailable; // Order index => order info. mapping(uint256 => Order) public orderBook; // If a user's index is < startIndex, the order is considered filled. mapping(address => uint256) public orderIndex; // Specifies whether the queue consists of orders to buy bond tokens or orders to sell bond tokens. // If true, the queue will hold TGEN and executing an order will act as a 'sell' (users receive bond tokens). // If false, the queue will hold bond tokens and executing an order will act as a 'buy' (users receive TGEN). bool public isBuyQueue; bool internal initialized; constructor(address _TGEN, address _bondToken, address _marketplace, address _xTGEN) { TGEN = IERC20(_TGEN); bondToken = IERC20(_bondToken); factory = msg.sender; marketplace = _marketplace; xTGEN = _xTGEN; isBuyQueue = true; params = Params({ price: 1e18, maximumNumberOfInvestors: 20, tradingFee: 50, minimumOrderSize: 1e16, owner: address(0) }); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @dev Creates an order to buy bond tokens. * @notice Executes existing 'sell' orders before adding this order. * @param _amount number of bond tokens to buy. */ function buy(uint256 _amount) public override isInitialized { require(_amount >= params.minimumOrderSize, "ExecutionPrice: amount must be above minimum order size."); TGEN.safeTransferFrom(msg.sender, address(this), _amount.mul(params.price).div(1e18)); // Add order to queue or update existing order. if (isBuyQueue) { // Update existing order. if (orderIndex[msg.sender] >= startIndex) { orderBook[orderIndex[msg.sender]].quantity = orderBook[orderIndex[msg.sender]].quantity.add(_amount); numberOfTokensAvailable = numberOfTokensAvailable.add(_amount); } // Add order to queue. else { require(endIndex.sub(startIndex) <= params.maximumNumberOfInvestors, "ExecutionPrice: queue is full."); _append(msg.sender, _amount); } emit Buy(msg.sender, _amount, 0); } // Fill as much of the order as possible, and add remainder as a new order. else { uint256 filledAmount = _executeOrder(_amount); // Not enough sell orders to fill this buy order. // Queue becomes a 'buy queue' and this becomes the first order in the queue. if (filledAmount < _amount) { isBuyQueue = !isBuyQueue; _append(msg.sender, _amount.sub(filledAmount)); } bondToken.safeTransfer(msg.sender, filledAmount); emit Buy(msg.sender, _amount, filledAmount); } } /** * @dev Creates an order to sell bond tokens. * @notice Executes existing 'buy' orders before adding this order. * @param _amount number of bond tokens to sell. */ function sell(uint256 _amount) public override isInitialized { require(_amount >= params.minimumOrderSize, "ExecutionPrice: amount must be above minimum order size."); bondToken.safeTransferFrom(msg.sender, address(this), _amount); // Fill as much of the order as possible, and add remainder as a new order. if (isBuyQueue) { uint256 filledAmount = _executeOrder(_amount); // Not enough buy orders to fill this sell order. // Queue becomes a 'sell queue' and this becomes the first order in the queue. if (filledAmount < _amount) { isBuyQueue = !isBuyQueue; _append(msg.sender, _amount.sub(filledAmount)); } TGEN.safeTransfer(msg.sender, filledAmount); emit Sell(msg.sender, _amount, filledAmount); } // Add order to queue. else { // Update existing order. if (orderIndex[msg.sender] >= startIndex) { orderBook[orderIndex[msg.sender]].quantity = orderBook[orderIndex[msg.sender]].quantity.add(_amount); numberOfTokensAvailable = numberOfTokensAvailable.add(_amount); } // Add order to queue. else { require(endIndex.sub(startIndex) <= params.maximumNumberOfInvestors, "ExecutionPrice: queue is full."); _append(msg.sender, _amount); } emit Sell(msg.sender, _amount, 0); } } /** * @dev Updates the order quantity and transaction type (buy vs. sell). * @notice If the transaction type is different from the original type, * existing orders will be executed before updating this order. * @param _amount number of bond tokens to buy/sell. * @param _buy whether this is a 'buy' order. */ function updateOrder(uint256 _amount, bool _buy) external override isInitialized { require(_amount >= params.minimumOrderSize, "ExecutionPrice: amount must be above minimum order size."); // User's previous order is filled, so treat this as a new order. if (orderIndex[msg.sender] < startIndex) { if (_buy) { buy(_amount); } else { sell(_amount); } return; } // Order is same type as the queue. if ((_buy && isBuyQueue) || (!_buy && !isBuyQueue)) { // Cancels the order if the new amount is less than the filled amount. if (_amount < orderBook[orderIndex[msg.sender]].amountFilled) { numberOfTokensAvailable = numberOfTokensAvailable.sub(orderBook[orderIndex[msg.sender]].quantity.sub(orderBook[orderIndex[msg.sender]].amountFilled)); orderBook[orderIndex[msg.sender]].quantity = orderBook[orderIndex[msg.sender]].amountFilled; } // Amount is less than previous amount, so release tokens held in escrow. else if (_amount <= orderBook[orderIndex[msg.sender]].quantity) { numberOfTokensAvailable = numberOfTokensAvailable.sub(orderBook[orderIndex[msg.sender]].quantity.sub(_amount)); if (_buy) { TGEN.transfer(msg.sender, (orderBook[orderIndex[msg.sender]].quantity.sub(_amount)).mul(params.price).div(1e18)); } else { bondToken.transfer(msg.sender, orderBook[orderIndex[msg.sender]].quantity.sub(_amount)); } orderBook[orderIndex[msg.sender]].quantity = _amount; emit UpdatedOrder(msg.sender, _amount, _buy); } // Amount is more than previous amount, so transfer tokens to this contract to hold in escrow. else { numberOfTokensAvailable = numberOfTokensAvailable.add(_amount).sub(orderBook[orderIndex[msg.sender]].quantity); if (_buy) { TGEN.safeTransferFrom(msg.sender, address(this), (_amount.sub(orderBook[orderIndex[msg.sender]].quantity)).mul(params.price).div(1e18)); } else { bondToken.safeTransferFrom(msg.sender, address(this), _amount.sub(orderBook[orderIndex[msg.sender]].quantity)); } orderBook[orderIndex[msg.sender]].quantity = _amount; emit UpdatedOrder(msg.sender, _amount, _buy); } } // Order type is different from that of the queue. // Releases user's tokens from escrow, cancels the existing order, and create order opposite the queue's type. else { numberOfTokensAvailable = numberOfTokensAvailable.sub(orderBook[orderIndex[msg.sender]].quantity.sub(orderBook[orderIndex[msg.sender]].amountFilled)); if (_buy) { bondToken.transfer(msg.sender, orderBook[orderIndex[msg.sender]].quantity.sub(orderBook[orderIndex[msg.sender]].amountFilled)); orderBook[orderIndex[msg.sender]].amountFilled = 0; orderBook[orderIndex[msg.sender]].quantity = 0; buy(_amount); } else { TGEN.transfer(msg.sender, orderBook[orderIndex[msg.sender]].quantity.sub(orderBook[orderIndex[msg.sender]].amountFilled)); orderBook[orderIndex[msg.sender]].amountFilled = 0; orderBook[orderIndex[msg.sender]].quantity = 0; sell(_amount); } } } /* ========== INTERNAL FUNCTIONS ========== */ /** * @dev Adds an order to the end of the queue. * @param _user address of the user placing this order. * @param _amount number of bond tokens. */ function _append(address _user, uint256 _amount) internal { orderBook[endIndex] = Order({ user: _user, quantity: _amount, amountFilled: 0 }); numberOfTokensAvailable = numberOfTokensAvailable.add(_amount); orderIndex[_user] = endIndex; endIndex = endIndex.add(1); } /** * @dev Executes an order based on the queue type. * @notice If queue is a 'buy queue', this will be treated as a 'sell' order. * @notice Fee is paid in bond tokens if queue is a 'sell queue'. * @param _amount number of bond tokens. * @return totalFilledAmount - number of bond tokens bought/sold. */ function _executeOrder(uint256 _amount) internal returns (uint256 totalFilledAmount) { uint256 filledAmount; // Claim bond token rewards accumulated while tokens were in escrow. uint256 initialBalance = TGEN.balanceOf(address(this)); ILiquidityBond(address(bondToken)).getReward(); uint256 newBalance = TGEN.balanceOf(address(this)); { // Save gas by getting endIndex once, instead of after each loop iteration. uint256 start = startIndex; uint256 end = endIndex; // Iterate over each open order until given order is filled or there's no more open orders. // This loop is bounded by 'maximumNumberOfInvestors', which cannot be more than 50. for (; start < end; start++) { filledAmount = (_amount.sub(totalFilledAmount) > orderBook[start].quantity.sub(orderBook[start].amountFilled)) ? orderBook[start].quantity.sub(orderBook[start].amountFilled) : _amount.sub(totalFilledAmount); totalFilledAmount = totalFilledAmount.add(filledAmount); orderBook[start].amountFilled = orderBook[start].amountFilled.add(filledAmount); if (isBuyQueue) { bondToken.transfer(orderBook[start].user, filledAmount.mul(10000 - params.tradingFee).div(10000)); } else { TGEN.transfer(orderBook[start].user, filledAmount.mul(params.price).mul(10000 - params.tradingFee).div(1e18).div(10000)); } // Exit early when order is filled. if (totalFilledAmount == _amount) { break; } // Avoid skipping last order if it was partially filled. if (totalFilledAmount < _amount && filledAmount < orderBook[start].quantity) { break; } } startIndex = start; } // Send trading fee to contract owner. // If owner is the marketplace contract (NFT held in escrow while listed for sale), transfer TGEN to xTGEN contract // and burn bond tokens. if (isBuyQueue) { bondToken.transfer((params.owner == marketplace) ? address(0) : params.owner, totalFilledAmount.mul(params.tradingFee).div(10000)); } else { TGEN.transfer((params.owner == marketplace) ? xTGEN : params.owner, totalFilledAmount.mul(params.price).mul(params.tradingFee).div(1e18).div(10000)); } numberOfTokensAvailable = numberOfTokensAvailable.sub(totalFilledAmount); // Transfer accumulated rewards to xTGEN contract. TGEN.safeTransfer(xTGEN, newBalance.sub(initialBalance)); } /* ========== RESTRICTED FUNCTIONS ========== */ /** * @dev Updates the trading fee for this ExecutionPrice. * @notice This function is meant to be called by the contract owner. * @param _newFee the new trading fee. */ function updateTradingFee(uint256 _newFee) external override onlyOwner isInitialized { require(_newFee >= 0 && _newFee <= MAX_TRADING_FEE, "ExecutionPrice: trading fee out of range."); params.tradingFee = _newFee; emit UpdatedTradingFee(_newFee); } /** * @dev Updates the minimum order size for this ExecutionPrice. * @notice This function is meant to be called by the contract owner. * @param _newSize the new minimum order size. */ function updateMinimumOrderSize(uint256 _newSize) external override onlyOwner isInitialized { require(_newSize.mul(params.price).div(1e18) >= MIN_MINIMUM_ORDER_VALUE, "ExecutionPrice: minimum order size is too low."); require(_newSize.mul(params.price).div(1e18) <= MAX_MINIMUM_ORDER_VALUE, "ExecutionPrice: minimum order size is too high."); params.minimumOrderSize = _newSize; emit UpdatedMinimumOrderSize(_newSize); } /** * @dev Updates the owner of this ExecutionPrice. * @notice This function is meant to be called by the ExecutionPriceFactory contract whenever the * ExecutionPrice NFT is purchased by another user. * @param _newOwner the new contract owner. */ function updateContractOwner(address _newOwner) external override onlyFactory isInitialized { require(_newOwner != address(0) && _newOwner != params.owner, "ExecutionPrice: invalid address for new owner."); params.owner = _newOwner; emit UpdatedOwner(_newOwner); } /** * @dev Initializes the contract's parameters. * @notice This function is meant to be called by the ExecutionPriceFactory contract when creating this contract. * @param _price the price of each bond token. * @param _maximumNumberOfInvestors the maximum number of open orders the queue can have. * @param _tradingFee fee that is paid to the contract owner whenever an order is filled; denominated by 10000. * @param _minimumOrderSize minimum number of bond tokens per order. * @param _owner address of the contract owner. */ function initialize(uint256 _price, uint256 _maximumNumberOfInvestors, uint256 _tradingFee, uint256 _minimumOrderSize, address _owner) external override onlyFactory isNotInitialized { require(_maximumNumberOfInvestors >= MIN_MAXIMUM_NUMBER_OF_INVESTORS, "ExecutionPrice: maximum number of investors is too low."); require(_maximumNumberOfInvestors <= MAX_MAXIMUM_NUMBER_OF_INVESTORS, "ExecutionPrice: maximum number of investors is too high."); require(_tradingFee >= 0 && _tradingFee <= MAX_TRADING_FEE, "ExecutionPrice: trading fee out of range."); require(_minimumOrderSize.mul(_price).div(1e18) >= MIN_MINIMUM_ORDER_VALUE, "ExecutionPrice: minimum order size is too low."); require(_minimumOrderSize.mul(_price).div(1e18) <= MAX_MINIMUM_ORDER_VALUE, "ExecutionPrice: minimum order size is too high."); params = Params({ price: _price, maximumNumberOfInvestors: _maximumNumberOfInvestors, tradingFee: _tradingFee, minimumOrderSize: _minimumOrderSize, owner: _owner }); initialized = true; emit InitializedContract(_price, _maximumNumberOfInvestors, _tradingFee, _minimumOrderSize, _owner); } /* ========== MODIFIERS ========== */ modifier onlyFactory() { require(msg.sender == factory, "ExecutionPrice: only the ExecutionPriceFactory contract can call this function."); _; } modifier onlyOwner() { require(msg.sender == params.owner, "ExecutionPrice: only the contract owner can call this function."); _; } modifier isNotInitialized() { require(!initialized, "ExecutionPrice: contract must not be initialized."); _; } modifier isInitialized() { require(initialized, "ExecutionPrice: contract must be initialized."); _; } /* ========== EVENTS ========== */ event Buy(address indexed user, uint256 numberOfTokens, uint256 filledAmount); event Sell(address indexed user, uint256 numberOfTokens, uint256 filledAmount); event UpdatedOwner(address newOwner); event UpdatedTradingFee(uint256 newFee); event UpdatedMinimumOrderSize(uint256 newOrderSize); event UpdatedOrder(address indexed user, uint256 numberOfTokens, bool isBuyOrder); event InitializedContract(uint256 price, uint256 maximumNumberOfInvestors, uint256 tradingFee, uint256 minimumOrderSize, address owner); }
Updates the owner of this ExecutionPrice. This function is meant to be called by the ExecutionPriceFactory contract whenever the ExecutionPrice NFT is purchased by another user. _newOwner the new contract owner./
function updateContractOwner(address _newOwner) external override onlyFactory isInitialized { require(_newOwner != address(0) && _newOwner != params.owner, "ExecutionPrice: invalid address for new owner."); params.owner = _newOwner; emit UpdatedOwner(_newOwner); }
14,076,414
./full_match/1/0x4599E4F3Eea04BADD41501bF79183e67f6Cf569d/sources/contracts/HighTableVault.sol
Internal function for claiming owed assets
function _internalClaimOwedAssets(address _receiver) internal returns (uint256 assets) { _convertPreviousRequests(msg.sender); if (userState[msg.sender].owedAssets > 0) { assets = userState[msg.sender].owedAssets; globalState.lockedAssets -= userState[msg.sender].owedAssets; userState[msg.sender].owedAssets = 0; emit ClaimOwedAssets(msg.sender, _receiver, assets); } }
17,149,090
./partial_match/1/0x0e2A6Cf9df1F13a1dD1cf151585ea090c280F47a/sources/CouponClipperV3.sol
Internal logic used to redeem coupons on the coupon holder's bahalf _user Address of the user holding the coupons (and who has approved this contract) _epoch The epoch in which the _user purchased the coupons _couponAmount The number of coupons to redeem (18 decimals) pull user's coupons into this contract (requires that the user has approved this contract) redeem the coupons for ESD pay the fees send the ESD to the user
function _redeem(address _user, uint256 _epoch, uint256 _couponAmount) internal { uint256 totalFeeRate = getOffer(_user); uint256 totalFee = _couponAmount.mul(totalFeeRate).div(10_000); uint256 houseFee = totalFee.mul(houseRate).div(10_000); uint256 botFee = totalFee.sub(houseFee); }
3,555,392
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "hardhat/console.sol"; contract WakalaEscrow { /** * Encription keys used to enxcrypt phone numbers. **/ string private encryptionKey; uint private nextTransactionID = 0; uint private agentFee = 50000000000000000; uint private wakalaFee = 40000000000000000; uint private successfulTransactionsCounter = 0; event AgentPairingEvent(WakalaTransaction wtx); event TransactionInitEvent(uint wtxIndex, address initiatorAddress); event ClientConfirmationEvent(WakalaTransaction wtx); event AgentConfirmationEvent(WakalaTransaction wtx); event ConfirmationCompletedEvent(WakalaTransaction wtx); event TransactionCompletionEvent(WakalaTransaction wtx); /** * Holds the wakala treasury address funds. Default account for alfajores test net. */ address internal wakalaTreasuryAddress = 0xfF096016A3B65cdDa688a8f7237Ac94f3EFBa245; /** * Address of the cUSD (default token on Alfajores). */ address internal cUsdTokenAddress = 0x874069Fa1Eb16D44d622F2e0Ca25eeA172369bC1; // Maps unique payment IDs to escrowed payments. // These payment IDs are the temporary wallet addresses created with the escrowed payments. mapping(uint => WakalaTransaction) private escrowedPayments; /** * An enum of the transaction types. either deposit or withdrawal. */ enum TransactionType { DEPOSIT, WITHDRAWAL } /** * An enum of all the states of a transaction. * AWAITING_AGENT :- transaction initialized and waitning for agent pairing. * AWAITING_CONFIRMATIONS :- agent paired awaiting for approval by the agent and client. * CONFIRMED :- transactions confirmed by both client and aagent. * DONE :- transaction completed, currency moved from escrow to destination addess. */ enum Status { AWAITING_AGENT, AWAITING_CONFIRMATIONS, CONFIRMED, CANCELED, DONE } /** * Object of escrow transactions. **/ struct WakalaTransaction { uint id; TransactionType txType; address clientAddress; address agentAddress; Status status; uint256 netAmount; uint256 agentFee; uint256 wakalaFee; uint256 grossAmount; bool agentApproval; bool clientApproval; string agentPhoneNumber; string clientPhoneNumber; } /** * Constructor. */ constructor(address _cUSDTokenAddress, uint256 _agentFee, uint256 _wakalaFee, address _wakalaTreasuryAddress) { // Allow for default value. if (_cUSDTokenAddress != address(0)) { cUsdTokenAddress = _cUSDTokenAddress; } // Allow for default value. if (_wakalaTreasuryAddress != address(0)) { wakalaTreasuryAddress = _wakalaTreasuryAddress; } // Allow for default value. if (_agentFee > 0) { agentFee = _agentFee; } // Allow for default value. if (_wakalaFee > 0) { wakalaFee = _wakalaFee; } } /** * Get the wakala fees from the smart contract. */ function getWakalaFee() public view returns(uint) { return wakalaFee; } /** * Get the agent fees from the smart contract. */ function getAgentFee() public view returns(uint) { return agentFee; } /** * Get the number of transactions in the smart contract. */ function getNextTransactionIndex() public view returns(uint) { return nextTransactionID; } /** * Get the number of successful transactions within the smart contract. */ function countSuccessfulTransactions() public view returns (uint) { return successfulTransactionsCounter; } /** * Client initialize withdrawal transaction. * @param _amount the amount to be withdrawn. * @param _phoneNumber the client`s phone number. **/ function initializeWithdrawalTransaction(uint256 _amount, string calldata _phoneNumber) public payable { require(_amount > 0, "Amount to deposit must be greater than 0."); uint wtxID = nextTransactionID; nextTransactionID++; uint grossAmount = _amount; WakalaTransaction storage newPayment = escrowedPayments[wtxID]; newPayment.clientAddress = msg.sender; newPayment.id = wtxID; newPayment.txType = TransactionType.WITHDRAWAL; newPayment.netAmount = grossAmount - (wakalaFee + agentFee); newPayment.agentFee = agentFee; newPayment.wakalaFee = wakalaFee; newPayment.grossAmount = grossAmount; newPayment.status = Status.AWAITING_AGENT; newPayment.clientPhoneNumber = _phoneNumber; // newPayment.clientPhoneNo = keccak256(abi.encodePacked(_phoneNumber, encryptionKey)); newPayment.agentApproval = false; newPayment.clientApproval = false; ERC20(cUsdTokenAddress).transferFrom( msg.sender, address(this), grossAmount); emit TransactionInitEvent(wtxID, msg.sender); } /** * Client initialize deposit transaction. * @param _amount the amount to be deposited. * @param _phoneNumber the client`s phone number. **/ function initializeDepositTransaction(uint256 _amount, string calldata _phoneNumber) public { require(_amount > 0, "Amount to deposit must be greater than 0."); uint wtxID = nextTransactionID; nextTransactionID++; WakalaTransaction storage newPayment = escrowedPayments[wtxID]; uint grossAmount = _amount; newPayment.clientAddress = msg.sender; newPayment.id = wtxID; newPayment.txType = TransactionType.DEPOSIT; newPayment.netAmount = grossAmount - (wakalaFee + agentFee); newPayment.agentFee = agentFee; newPayment.wakalaFee = wakalaFee; newPayment.grossAmount = grossAmount; newPayment.status = Status.AWAITING_AGENT; newPayment.clientPhoneNumber = _phoneNumber; // newPayment.clientPhoneNo = keccak256(abi.encodePacked(_phoneNumber, encryptionKey)); newPayment.agentApproval = false; newPayment.clientApproval = false; emit TransactionInitEvent(wtxID, msg.sender); } /** * Marks pairs the client to an agent to attent to the transaction. * @param _transactionid the identifire of the transaction. * @param _phoneNumber the agents phone number. */ function agentAcceptWithdrawalTransaction(uint _transactionid, string calldata _phoneNumber) public awaitAgent(_transactionid) withdrawalsOnly(_transactionid) nonClientOnly(_transactionid) { WakalaTransaction storage wtx = escrowedPayments[_transactionid]; wtx.agentAddress = msg.sender; wtx.status = Status.AWAITING_CONFIRMATIONS; wtx.agentPhoneNumber = _phoneNumber; emit AgentPairingEvent(wtx); } /** * Marks pairs the client to an agent to attent to the transaction. * @param _transactionid the identifire of the transaction. * @param _phoneNumber the agents phone number. */ function agentAcceptDepositTransaction(uint _transactionid, string calldata _phoneNumber) public awaitAgent(_transactionid) depositsOnly(_transactionid) nonClientOnly(_transactionid) balanceGreaterThanAmount(_transactionid) payable { WakalaTransaction storage wtx = escrowedPayments[_transactionid]; wtx.agentAddress = msg.sender; wtx.status = Status.AWAITING_CONFIRMATIONS; require( ERC20(cUsdTokenAddress).transferFrom( msg.sender, address(this), wtx.grossAmount ), "You don't have enough cUSD to accept this request." ); wtx.agentPhoneNumber = _phoneNumber; emit AgentPairingEvent(wtx); } /** * Client confirms that s/he has sent money to the agent. */ function clientConfirmPayment(uint _transactionid) public awaitConfirmation(_transactionid) clientOnly(_transactionid) { WakalaTransaction storage wtx = escrowedPayments[_transactionid]; require(!wtx.clientApproval, "Client already confirmed payment!!"); wtx.clientApproval = true; emit ClientConfirmationEvent(wtx); if (wtx.agentApproval) { wtx.status = Status.CONFIRMED; emit ConfirmationCompletedEvent(wtx); finalizeTransaction(_transactionid); } } /** * Agent comnfirms that the payment has been made. */ function agentConfirmPayment(uint _transactionid) public awaitConfirmation(_transactionid) agentOnly(_transactionid) { WakalaTransaction storage wtx = escrowedPayments[_transactionid]; require(!wtx.agentApproval, "Agent already confirmed payment!!"); wtx.agentApproval = true; emit AgentConfirmationEvent(wtx); if (wtx.clientApproval) { wtx.status = Status.CONFIRMED; emit ConfirmationCompletedEvent(wtx); finalizeTransaction(_transactionid); } } /** * Can be automated in the frontend by use of event listeners. eg on confirmation event. **/ function finalizeTransaction(uint _transactionid) public { WakalaTransaction storage wtx = escrowedPayments[_transactionid]; require(wtx.clientAddress == msg.sender || wtx.agentAddress == msg.sender, "Only the involved parties can finalize the transaction.!!"); require(wtx.status == Status.CONFIRMED, "Transaction not yet confirmed by both parties!!"); if (wtx.txType == TransactionType.DEPOSIT) { ERC20(cUsdTokenAddress).transfer( wtx.clientAddress, wtx.netAmount); } else { // Transafer the amount to the agent address. require(ERC20(cUsdTokenAddress).transfer(wtx.agentAddress, wtx.netAmount), "Transaction failed."); } // Transafer the agents fees to the agents address. require(ERC20(cUsdTokenAddress).transfer( wtx.agentAddress, wtx.agentFee), "Agent fee transfer failed."); // Transafer the agents total (amount + agent fees) require(ERC20(cUsdTokenAddress).transfer( wakalaTreasuryAddress, wtx.wakalaFee), "Transaction fee transfer failed."); successfulTransactionsCounter++; wtx.status = Status.DONE; emit TransactionCompletionEvent(wtx); } /** * Gets transactions by index. * @param _transactionID the transaction id. * @return the transaction in questsion. */ function getTransactionByIndex(uint _transactionID) public view returns (WakalaTransaction memory) { WakalaTransaction memory wtx = escrowedPayments[_transactionID]; return wtx; } /** * Gets the next unpaired transaction from the map. * @param _transactionID the transaction id. * @return the transaction in questsion. */ function getNextUnpairedTransaction(uint _transactionID) public view returns (WakalaTransaction memory) { uint transactionID = _transactionID; WakalaTransaction storage wtx; // prevent an extravagant loop. if (_transactionID > nextTransactionID) { transactionID = nextTransactionID; } // Loop through the transactions map by index. for (int index = int(transactionID); index >= 0; index--) { wtx = escrowedPayments[uint(index)]; if (wtx.clientAddress != address(0) && wtx.agentAddress == address(0)) { // the next unparied transaction. return wtx; } } // return empty wtx object. wtx = escrowedPayments[nextTransactionID]; return wtx; } /** * Prevents users othe than the agent from running the logic. * @param _transactionid the transaction being processed. */ modifier agentOnly(uint _transactionid) { WakalaTransaction storage wtx = escrowedPayments[_transactionid]; require(msg.sender == wtx.agentAddress, "Action can only be performed by the agent"); _; } /** * Run the method for deposit transactions only. */ modifier depositsOnly(uint _transactionid) { WakalaTransaction storage wtx = escrowedPayments[_transactionid]; require(wtx.txType == TransactionType.DEPOSIT, "Action can only be performed for deposit transactions only!!"); _; } /** * Run the method for withdrawal transactions only. * @param _transactionid the transaction being processed. */ modifier withdrawalsOnly(uint _transactionid) { WakalaTransaction storage wtx = escrowedPayments[_transactionid]; require(wtx.txType == TransactionType.WITHDRAWAL, "Action can only be performed for withdrawal transactions only!!"); _; } /** * Prevents users othe than the client from running the logic. * @param _transactionid the transaction being processed. */ modifier clientOnly(uint _transactionid) { WakalaTransaction storage wtx = escrowedPayments[_transactionid]; require(msg.sender == wtx.clientAddress, "Action can only be performed by the client!!"); _; } /** * Prevents the client from running the logic. * @param _transactionid the transaction being processed. */ modifier nonClientOnly(uint _transactionid) { WakalaTransaction storage wtx = escrowedPayments[_transactionid]; require(msg.sender != wtx.clientAddress, "Action can not be performed by the client!!"); _; } /** * Only alows method to be excecuted in tx in question is waiting confirmation. * @param _transactionid the transaction being processed. */ modifier awaitConfirmation(uint _transactionid) { WakalaTransaction storage wtx = escrowedPayments[_transactionid]; require(wtx.status == Status.AWAITING_CONFIRMATIONS, "Transaction is not awaiting confirmation from anyone."); _; } /** * Prevents prevents double pairing of agents to transactions. * @param _transactionid the transaction being processed. */ modifier awaitAgent(uint _transactionid) { WakalaTransaction storage wtx = escrowedPayments[_transactionid]; require(wtx.status == Status.AWAITING_AGENT, "Transaction already paired to an agent!!"); _; } /** * Prevents users othe than the client from running the logic * @param _transactionid the transaction being processed. */ modifier balanceGreaterThanAmount(uint _transactionid) { WakalaTransaction storage wtx = escrowedPayments[_transactionid]; require(ERC20(cUsdTokenAddress).balanceOf(address(msg.sender)) > wtx.grossAmount, "Your balance must be greater than the transaction gross amount."); _; } }
Get the wakala fees from the smart contract./
function getWakalaFee() public view returns(uint) { return wakalaFee; }
5,476,521
./partial_match/42/0xC241F942180AC337cA4AA55DC02054D257B0BD70/sources/StrategyUSDTCompound.sol
Compound auto distributes COMP rewards on deposit and withdraw, no need to claim
function _claimReward() internal virtual override { }
3,326,407
./partial_match/56/0x2ea36cD78F24cA535Fb66E020d7963E7731dD371/sources/MasterChef.sol
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.accKickPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeKickTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accKickPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); }
11,109,006
./full_match/11155111/0x1fB8Fa57DAaF534fF5B249A3E01b6F22b8420991/sources/project_/contracts/Krakatoa.sol
Withdraw orders funds orders orders to withdraw signature signature of the order/
function withdrawOrders(uint64[] calldata orders, bytes calldata signature) external checkSignature(abi.encode(orders), signature) { bool[] memory isWithdraw; _processOrders(orders, isWithdraw, 1); }
3,787,739
./full_match/97/0x0eb2eBa66E6a325e15C1E42548D49bA50896f88A/sources/contracts/ExampleTREX.sol
See {ITREX-batchBurn}./
function batchBurn(address[] calldata _userAddresses, uint256[] calldata _amounts) external override { for (uint256 i = 0; i < _userAddresses.length; i++) { burn(_userAddresses[i], _amounts[i]); } }
5,018,972
pragma solidity ^0.4.18; import "../node_modules/zeppelin-solidity/contracts/math/SafeMath.sol"; import "../node_modules/zeppelin-solidity/contracts/ownership/Ownable.sol"; // UbiatarCoin Abstract Contract contract UACAC { function transfer(address _to, uint256 _value) public returns(bool); } /* This contract holds 12000000 founders UAC. They will be locked for 1 year and then will be gradually unlocked in the next year. */ contract FoundersVesting is Ownable { // SafeMath standard lib using SafeMath for uint; // Flag that indicates if ICO is finished bool public icoFinished = false; // ICO contract address address public icoContractAddress = 0x0; // UbiatarCoin contract address address public uacTokenAddress = 0x0; // Founders Token cold wallet address public foundersTokenHolder = 0x0; // Last withdraw epoch time uint public lastWithdrawTime; // UbiatarCoin contract reference UACAC public uacToken; // Current UAC Token balance in this contract uint public currentBalance = 12000000 * 1 ether; // It is the fraction that it could be withdrawn every day uint public balanceFraction; // FoundersVesting constructor function FoundersVesting(address _uacTokenAddress) public { require(_uacTokenAddress != 0x0); uacToken = UACAC(_uacTokenAddress); uacTokenAddress = _uacTokenAddress; // Amount of tokens to be sent in a single day balanceFraction = ((currentBalance.mul(1 ether)).div(360)).div(1 ether); } /// Modifiers // Only by ICO contract modifier byIcoContract() { require(msg.sender == icoContractAddress); _; } // Only when ICO is finished modifier onlyIcoFinished() { require(icoFinished == true); _; } /// Setters // ICO contract address setter function setIcoContractAddress(address _icoContractAddress) public onlyOwner { icoContractAddress = _icoContractAddress; } // UbiatarCoin contract address setter function setUacTokenAddress(address _uacTokenAddress) public onlyOwner { uacTokenAddress = _uacTokenAddress; uacToken = UACAC(_uacTokenAddress); } // Founders wallet address setter function setFoundersTokenHolder(address _foundersTokenHolder) public onlyOwner { foundersTokenHolder = _foundersTokenHolder; } /// Functions // Function called by ICO contract when it is finished function finishIco() public byIcoContract { lastWithdrawTime=uint(now).add(360 days); icoFinished = true; } // It allows Founders to withdraw their tokens // It can withdraw a fraction of its total supply day by day until the end of 1 year function withdrawTokens() public onlyOwner onlyIcoFinished { // Checks if we have already set the foundersTokenHolder wallet address require(foundersTokenHolder != 0x0); uint amountToSend = 0; // Calculates the number of days passed from the last time tokens were withdrawn uint daysPassed = (uint(now).sub(lastWithdrawTime)).div(1 days); amountToSend = balanceFraction.mul(daysPassed); lastWithdrawTime = uint(now); require(amountToSend != 0); if (currentBalance < amountToSend) { amountToSend = currentBalance; } currentBalance = currentBalance.sub(amountToSend); uacToken.transfer(foundersTokenHolder, amountToSend); amountToSend = 0; } // It doesn't allow to send money directly to this contract function() payable public { revert(); } }
Function called by ICO contract when it is finished
function finishIco() public byIcoContract { lastWithdrawTime=uint(now).add(360 days); icoFinished = true; }
1,805,364
./full_match/5/0x40a14bb4c7f4b6a6083cf2a6686daAd3cd3aF60E/sources/contracts/Contract.sol
internal function to end the battle battleEnder winner address _battle battle; taken from attackOrDefend function
function _endBattle(address battleEnder, Battle memory _battle) internal nonReentrant returns (bool) { _sendBattleReward(_battle.name, _battle.token, battleEnder, _battle.betReward); _battle.winner = battleEnder; updateBattleEndStatus(_battle); address battleLoser = battleEnder == _battle.players[0] ? _battle.players[1] : _battle.players[0]; players[playerInfo[battleEnder]].totalWin++; players[playerInfo[battleLoser]].totalLose++; resetPlayerStatus(playerInfo[battleEnder]); resetPlayerStatus(playerInfo[battleLoser]); for (uint i; i < _battle.players.length; i++){ battleHistory[_battle.players[i]].push(_battle); } return true; }
1,907,542
/** *Submitted for verification at Etherscan.io on 2022-03-19 */ // SPDX-License-Identifier: MIT pragma solidity 0.8.11; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IERC20 { 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); } interface IERC20Metadata is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return 9; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } 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 virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } 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; } } contract Ownable is Context { address private _owner; 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; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } function div(int256 a, int256 b) internal pure returns (int256) { require(b != -1 || a != MIN_INT256); return a / b; } function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract SHIBETOSHI is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; mapping (address => bool) private _isSniper; bool private _swapping; uint256 private _launchTime; address public feeWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 private _buyMarketingFee; uint256 private _buyLiquidityFee; uint256 private _buyDevFee; uint256 public sellTotalFees; uint256 private _sellMarketingFee; uint256 private _sellLiquidityFee; uint256 private _sellDevFee; uint256 private _tokensForMarketing; uint256 private _tokensForLiquidity; uint256 private _tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event feeWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("SHIBETOSHI NAKAMOTO", "SHIBETOSHI") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 buyMarketingFee = 1; uint256 buyLiquidityFee = 1; uint256 buyDevFee = 11; uint256 sellMarketingFee = 1; uint256 sellLiquidityFee = 1; uint256 sellDevFee = 11; uint256 totalSupply = 1e18 * 1e9; maxTransactionAmount = totalSupply * 1 / 100; // 1% maxTransactionAmountTxn maxWallet = totalSupply * 3 / 100; // 3% maxWallet swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet _buyMarketingFee = buyMarketingFee; _buyLiquidityFee = buyLiquidityFee; _buyDevFee = buyDevFee; buyTotalFees = _buyMarketingFee + _buyLiquidityFee + _buyDevFee; _sellMarketingFee = sellMarketingFee; _sellLiquidityFee = sellLiquidityFee; _sellDevFee = sellDevFee; sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee; feeWallet = address(owner()); // set as fee wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; _launchTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000) / 1e9, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * 1e9; } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e9, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * 1e9; } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function updateBuyFees(uint256 marketingFee, uint256 liquidityFee, uint256 devFee) external onlyOwner { _buyMarketingFee = marketingFee; _buyLiquidityFee = liquidityFee; _buyDevFee = devFee; buyTotalFees = _buyMarketingFee + _buyLiquidityFee + _buyDevFee; require(buyTotalFees <= 10, "Must keep fees at 10% or less"); } function updateSellFees(uint256 marketingFee, uint256 liquidityFee, uint256 devFee) external onlyOwner { _sellMarketingFee = marketingFee; _sellLiquidityFee = liquidityFee; _sellDevFee = devFee; sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee; require(sellTotalFees <= 15, "Must keep fees at 15% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateFeeWallet(address newWallet) external onlyOwner { emit feeWalletUpdated(newWallet, feeWallet); feeWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function setSnipers(address[] memory snipers_) public onlyOwner() { for (uint i = 0; i < snipers_.length; i++) { if (snipers_[i] != uniswapV2Pair && snipers_[i] != address(uniswapV2Router)) { _isSniper[snipers_[i]] = true; } } } function delSnipers(address[] memory snipers_) public onlyOwner() { for (uint i = 0; i < snipers_.length; i++) { _isSniper[snipers_[i]] = false; } } function isSniper(address addr) public view returns (bool) { return _isSniper[addr]; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap."); if (amount == 0) { super._transfer(from, to, 0); return; } if (block.timestamp == _launchTime) _isSniper[to] = true; if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_swapping ) { if (!tradingActive) { require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } // when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } // when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && !_swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { _swapping = true; swapBack(); _swapping = false; } bool takeFee = !_swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if (takeFee) { // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); _tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees; _tokensForDev += fees * _sellDevFee / sellTotalFees; _tokensForMarketing += fees * _sellMarketingFee / sellTotalFees; } // on buy else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); _tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees; _tokensForDev += fees * _buyDevFee / buyTotalFees; _tokensForMarketing += fees * _buyMarketingFee / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function _addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = _tokensForLiquidity + _tokensForMarketing + _tokensForDev; if (contractBalance == 0 || totalTokensToSwap == 0) return; if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * _tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; _swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(_tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(_tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; _tokensForLiquidity = 0; _tokensForMarketing = 0; _tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { _addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, _tokensForLiquidity); } } function withdrawFees() external { payable(feeWallet).transfer(address(this).balance); } receive() external payable {} }
exclude from paying fees or having max transaction amount
constructor() ERC20("SHIBETOSHI NAKAMOTO", "SHIBETOSHI") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 buyMarketingFee = 1; uint256 buyLiquidityFee = 1; uint256 buyDevFee = 11; uint256 sellMarketingFee = 1; uint256 sellLiquidityFee = 1; uint256 sellDevFee = 11; uint256 totalSupply = 1e18 * 1e9; _buyMarketingFee = buyMarketingFee; _buyLiquidityFee = buyLiquidityFee; _buyDevFee = buyDevFee; buyTotalFees = _buyMarketingFee + _buyLiquidityFee + _buyDevFee; _sellMarketingFee = sellMarketingFee; _sellLiquidityFee = sellLiquidityFee; _sellDevFee = sellDevFee; sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
6,803,916
pragma solidity 0.4.20; /*===================================== = [ Proof of GameKyuubi (33.33%) ] = = https://pogk.surge.sh/ = = https://discord.gg/ENXNGHc = =====================================*/ /* _____ _______ _____ _____ /\ \ /::\ \ /\ \ /\ \ /::\ \ /::::\ \ /::\ \ /::\____\ /::::\ \ /::::::\ \ /::::\ \ /:::/ / /::::::\ \ /::::::::\ \ /::::::\ \ /:::/ / /:::/\:::\ \ /:::/~~\:::\ \ /:::/\:::\ \ /:::/ / /:::/__\:::\ \ /:::/ \:::\ \ /:::/ \:::\ \ /:::/____/ /::::\ \:::\ \ /:::/ / \:::\ \ /:::/ \:::\ \ /::::\ \ /::::::\ \:::\ \ /:::/____/ \:::\____\ /:::/ / \:::\ \ /::::::\____\________ /:::/\:::\ \:::\____\ |:::| | |:::| | /:::/ / \:::\ ___\ /:::/\:::::::::::\ \ /:::/ \:::\ \:::| ||:::|____| |:::| |/:::/____/ ___\:::| |/:::/ |:::::::::::\____\ \::/ \:::\ /:::|____| \:::\ \ /:::/ / \:::\ \ /\ /:::|____|\::/ |::|~~~|~~~~~ \/_____/\:::\/:::/ / \:::\ \ /:::/ / \:::\ /::\ \::/ / \/____|::| | \::::::/ / \:::\ /:::/ / \:::\ \:::\ \/____/ |::| | \::::/ / \:::\__/:::/ / \:::\ \:::\____\ |::| | \::/____/ \::::::::/ / \:::\ /:::/ / |::| | ~~ \::::::/ / \:::\/:::/ / |::| | \::::/ / \::::::/ / |::| | \::/____/ \::::/ / \::| | ~~ \::/____/ \:| | \|___| * -> Features! * All the features from all the great Po schemes, with dividend fee 33.33%: * [x] Highly Secure: Hundreds of thousands of investers of the original PoWH3D, holding tens of thousands of ethers. * [X] Purchase/Sell: You can perform partial sell orders. If you succumb to weak hands, you don't have to dump all of your bags. * [x] Purchase/Sell: You can transfer tokens between wallets. Trading is possible from within the contract. * [x] Masternodes: The implementation of Ethereum Staking in the world. * [x] Masternodes: Holding 50 PoGK Tokens allow you to generate a Masternode link, Masternode links are used as unique entry points to the contract. * [x] Masternodes: All players who enter the contract through your Masternode have 30% of their 33.33% dividends fee rerouted from the master-node, to the node-master. * * -> Who worked not this project? * - GameKyuubi (OG HOLD MASTER) * - Craig Grant from POOH (Marketing) * - Carlos Matos from N.Y. (Management) * - Mantso from PoWH 3D (Mathemagic) * * -> Owner of contract can: * - Low Pre-mine (~0.33ETH) * - And nothing else * * -> Owner of contract CANNOT: * - exit scam * - kill the contract * - take funds * - pause the contract * - disable withdrawals * - change the price of tokens * * -> THE FOMO IS REAL!! ** https://pogk.surge.sh/ ** */ contract PoGKHOLD { /*===================================== = CONFIGURABLES = =====================================*/ string public name = "POGK Future"; string public symbol = "POGK"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 3; // 33.33% Dividends (In & Out) uint constant internal tokenPriceInitial_ = 0.0000001 ether; uint constant internal tokenPriceIncremental_ = 0.00000001 ether; uint constant internal magnitude = 2**64; // proof of stake (defaults at 50 tokens) uint public stakingRequirement = 50e18; /*=============================== = STORAGE = ==============================*/ // amount of shares for each address (scaled number) mapping(address => uint) internal tokenBalanceLedger_; mapping(address => uint) internal referralBalance_; mapping(address => int) internal payoutsTo_; uint internal tokenSupply_ = 0; uint internal profitPerShare_; /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint incomingEthereum, uint tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint tokensBurned, uint ethereumEarned ); event onReinvestment( address indexed customerAddress, uint ethereumReinvested, uint tokensMinted ); event onWithdraw( address indexed customerAddress, uint ethereumWithdrawn ); // ERC20 event Transfer( address indexed from, address indexed to, uint tokens ); /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) function buy(address _referredBy) public payable returns (uint) { purchaseTokens(msg.value, _referredBy); } /** * @dev Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { purchaseTokens(msg.value, 0x0); } /// @dev Converts all of caller's dividends to tokens. function reinvest() onlyStronghands public { // fetch dividends uint _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint _tokens = purchaseTokens(_dividends, 0x0); // fire event onReinvestment(_customerAddress, _dividends, _tokens); } /// @dev Alias of sell() and withdraw(). function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint _tokens = tokenBalanceLedger_[_customerAddress]; if (_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /// @dev Withdraws all of the callers earnings. function withdraw() onlyStronghands public { // setup data address _customerAddress = msg.sender; uint _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event onWithdraw(_customerAddress, _dividends); } /// @dev Liquifies tokens to ethereum. function sell(uint _amountOfTokens) onlyBagholders public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint _tokens = _amountOfTokens; uint _ethereum = tokensToEthereum_(_tokens); uint _dividends = SafeMath.div(_ethereum, dividendFee_); uint _taxedEthereum = SafeMath.sub(_ethereum, _dividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int _updatedPayouts = (int) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /** * @dev Transfer tokens from the caller to a new holder. * Remember, there's a 33.33% fee here as well. */ function transfer(address _toAddress, uint _amountOfTokens) onlyBagholders public returns (bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if (myDividends(true) > 0) { withdraw(); } // liquify 33.33% of the tokens that are transfered // these are dispersed to shareholders uint _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_); uint _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint _dividends = tokensToEthereum_(_tokenFee); // burn the fee tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int) (profitPerShare_ * _taxedTokens); // disperse dividends among holders profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); // fire event Transfer(_customerAddress, _toAddress, _taxedTokens); // ERC20 return true; } /*===================================== = HELPERS AND CALCULATORS = =====================================*/ /** * @dev Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns (uint) { return this.balance; } /// @dev Retrieve the total token supply. function totalSupply() public view returns (uint) { return tokenSupply_; } /// @dev Retrieve the tokens owned by the caller. function myTokens() public view returns (uint) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * @dev Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns (uint) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /// @dev Retrieve the token balance of any single address. function balanceOf(address _customerAddress) public view returns (uint) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) public view returns (uint) { return (uint) ((int)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /// @dev Return the buy price of 1 individual token. function sellPrice() public view returns (uint) { // our calculation relies on the token supply, so we need supply. Doh. if (tokenSupply_ == 0) { return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint _ethereum = tokensToEthereum_(1e18); uint _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /// @dev Return the sell price of 1 individual token. function buyPrice() public view returns (uint) { // our calculation relies on the token supply, so we need supply. Doh. if (tokenSupply_ == 0) { return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint _ethereum = tokensToEthereum_(1e18); uint _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders. function calculateTokensReceived(uint _ethereumToSpend) public view returns (uint) { uint _dividends = SafeMath.div(_ethereumToSpend, dividendFee_); uint _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders. function calculateEthereumReceived(uint _tokensToSell) public view returns (uint) { require(_tokensToSell <= tokenSupply_); uint _ethereum = tokensToEthereum_(_tokensToSell); uint _dividends = SafeMath.div(_ethereum, dividendFee_); uint _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint _incomingEthereum, address _referredBy) internal returns (uint) { // data setup address _customerAddress = msg.sender; uint _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_); uint _referralBonus = SafeMath.div(_undividedDividends, 3); uint _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if ( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ) { // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can't give people infinite ethereum if (tokenSupply_ > 0) { // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; //really i know you think you do but you don't int _updatedPayouts = (int) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; // fire event onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint _ethereum) internal view returns (uint) { uint _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * @dev Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint _tokens) internal view returns (uint) { uint tokens_ = (_tokens + 1e18); uint _tokenSupply = (tokenSupply_ + 1e18); uint _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } /// @dev This is where all your gas goes. function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } /*================================= = MODIFIERS = =================================*/ /// @dev Only people with tokens modifier onlyBagholders { require(myTokens() > 0); _; } /// @dev Only people with profits modifier onlyStronghands { require(myDividends(true) > 0); _; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint a, uint b) internal pure returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } }
Alias of sell() and withdraw(). get token count for caller & sell them all lambo delivery service
function exit() public { address _customerAddress = msg.sender; uint _tokens = tokenBalanceLedger_[_customerAddress]; if (_tokens > 0) sell(_tokens); withdraw(); }
5,850,779
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./CTokenInterface.sol"; import "./InterestRateModel.sol"; import "./Comptroller.sol"; import "hardhat/console.sol"; abstract contract CToken is ERC20, CTokenInterface { InterestRateModel public interestRateModel; Comptroller public comptroller; uint256 public scaleBy = 10**decimals(); event Mint(address minter, uint256 mintAmount, uint256 mintTokens); event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens); event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); event RepayBorrow(address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /// @notice Initialize the money market /// @param _initialExchangeRate The initial exchange rate, scaled by 1e18 /// @param _comptroller The address of the Comptroller /// @param _name EIP-20 name of this token /// @param _symbol EIP-20 symbol of this token constructor(uint256 _initialExchangeRate, Comptroller _comptroller, string memory _name, string memory _symbol) ERC20(_name, _symbol) { require(_initialExchangeRate > 0, "initial exchange rate must be greater than zero."); initialExchangeRate = _initialExchangeRate; interestRateModel = new InterestRateModel(); comptroller = _comptroller; accrualBlockNumber = block.number; borrowIndex = 1 * scaleBy; totalReserves = 0; } /// @notice Get balance of underlying asset for the owner /// @param owner The address of the account to query /// @return Balance of underlying asset function balanceOfUnderlying(address owner) external returns(uint) { require(balanceOf(owner) > 0, "NOT_HAVING_ENOUGH_CTOKENS"); return (exchangeRateCurrent() * balanceOf(owner)) / scaleBy; } /// @notice User supplies assets into the market and receives cTokens in exchange /// @param _minter The address of the account which is supplying the assets /// @param _mintAmount The amount of asset that is supplied function mintInternal(address _minter, uint256 _mintAmount) internal { /* * We get the current exchange rate and calculate the number of cTokens to be minted: * mintTokens = actualMintAmount / exchangeRate [WEI] */ require(accrueInterest() == true, "ACCRUE_INTEREST_FAILED"); doTransferIn(_minter, _mintAmount); uint256 mintTokens = (_mintAmount / calculateExchangeRate()) * scaleBy; _mint(_minter, mintTokens); emit Mint(_minter, _mintAmount, mintTokens); } /// @notice Accrue interest then return the up-to-date exchange rate /// @return Calculated exchange rate function exchangeRateCurrent() public returns (uint) { require(accrueInterest() == true, "ACCRUE_INTEREST_FAILED"); return calculateExchangeRate(); } /// @notice Accrues interest on the borrowed amount /// @return Wether or not the operation succeeded or not function accrueInterest() public returns (bool) { uint currentBlockNumber = block.number; uint accrualBlockNumberPrior = accrualBlockNumber; if (accrualBlockNumberPrior == currentBlockNumber) { return true; } /* Read the previous values out of storage */ uint cashPrior = getCash(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; uint borrowRate = interestRateModel.getBorrowRatePerBlock(cashPrior, borrowsPrior, reservesPrior); uint blockDelta = currentBlockNumber - accrualBlockNumber; uint simpleInterestFactor = borrowRate * blockDelta; uint interestAccumulated = ( simpleInterestFactor * borrowsPrior ) / 10**18; uint totalBorrowsNew = borrowsPrior + interestAccumulated; // uint reservesNew = (interestAccumulated * RESERVE_FACTOR_MANTISA) + reservesPrior; uint borrowIndexNew = simpleInterestFactor + borrowIndexPrior; accrualBlockNumber = currentBlockNumber; totalBorrows = totalBorrowsNew; // totalReserves = reservesNew; borrowIndex = borrowIndexNew; emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return true; } /// @notice Calculate the up-to-date exchange rate and return /// @return Calculated exchange rate function exchangeRateStored() public view returns (uint) { return calculateExchangeRate(); } /// @notice Calculates the exchange rate from the underlying to the CToken /// @return Calculated exchange rate scaled by 1e18 function calculateExchangeRate() internal view returns (uint256) { // 0.020000 => 20000000000000000 uint256 _totalSupply = totalSupply(); if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return initialExchangeRate; // in WEI } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint256 totalCash = getCash(); uint256 cashPlusBorrowsMinusReserves; cashPlusBorrowsMinusReserves = totalCash + totalBorrows - totalReserves; // cash in WEI return cashPlusBorrowsMinusReserves / ( totalSupply() / scaleBy ); // totalSupply in WEI } } /// @notice Sender redeems cTokens in exchange for the underlying asset /// @param redeemer The address of the account which is redeeming the CTokens /// @param redeemTokens The no. of CTokens to be redeemed function redeemInternal(address redeemer, uint redeemTokens) internal { require(accrueInterest() == true, "ACCRUE_INTEREST_FAILED"); CToken[] memory accountEnteredMarkets = comptroller.getAccountEnteredMarkets(msg.sender); for(uint i = 0; i < accountEnteredMarkets.length; i++) { if (address(accountEnteredMarkets[i]) == address(this)) { revert("REDEEM_FAILED_DUE_TO_ASSET_AS_COLLATERAL"); } } uint exchangeRateMantisa = exchangeRateStored(); // calculate the exchange rate and the amount of underlying to be redeemed uint redeemAmount = ( redeemTokens * exchangeRateMantisa ) / scaleBy; // EXCHANGE in WEI // Fail gracefully if protocol has insufficient cash require(getCash() >= redeemAmount, "INSUFFICIENT_CASH"); doTransferOut(redeemer, redeemAmount); // Burns amount _burn(redeemer, redeemTokens); emit Redeem(redeemer, redeemAmount, redeemTokens); } /// @notice Returns the current borrow interest rate APY for this cToken /// @return The borrow interest APY, scaled by 1e18 function getBorrowRate() external view returns (uint) { // TODO: Can Total Borrows increase than Supply ? return interestRateModel.getBorrowRate(getCash(), totalBorrows, totalReserves); } // @notice Returns the current per-block borrow interest rate for this cToken /// @return The borrow interest rate per block, scaled by 1e18 function getBorrowRatePerBlock() external view returns (uint) { return interestRateModel.getBorrowRatePerBlock(getCash(), totalBorrows, totalReserves); } /// @notice Returns the current supply interest rate APY for this cToken /// @return The supply interest rate APY, scaled by 1e18 function getSupplyRate() external view returns (uint) { return interestRateModel.getSupplyRate(getCash(), totalBorrows, totalReserves, RESERVE_FACTOR_MANTISA) ; } /// @notice Returns the current per-block supply interest rate for this cToken /// @return The supply interest rate per block, scaled by 1e18 function getSupplyRatePerBlock() external view returns (uint) { return interestRateModel.getSupplyRatePerBlock(getCash(), totalBorrows, totalReserves, RESERVE_FACTOR_MANTISA) ; } /// @notice Allows users to borrow from Market /// @param borrowAmount The amount of the underlying asset to borrow /// @return Whether or not the borrowed operation succeeded or not function borrowInternal(uint borrowAmount) internal returns (bool) { require(borrowAmount > 0, "REDEEM_TOKENS_GREATER_THAN_ZERO"); require(accrueInterest(), "ACCRUING_INTEREST_FAILED"); bool isListed = comptroller.isMarketListed(address(this)); require(isListed, "TOKEN_NOT_LISTED_IN_MARKET"); // Get Underlying Price is Zero // Insufficient Balance in the Market require(getCash() >= borrowAmount, "INSUFFICIENT_BALANCE_FOR_BORROW"); // How much max the borrower can borrow - check liquidity uint accountLiquidity = comptroller.getAccountLiquidity(msg.sender); uint borrowBalanceStoredInternal = borrowBalanceStored(msg.sender); // Get Borrower Balance && Account Borrow += borrow uint borrowBalanceNew = borrowBalanceStoredInternal + borrowAmount; require(borrowBalanceNew <= accountLiquidity, "INSUFFICIENT_LIQUIDITY"); // Transfer to borrower; doTransferOut(msg.sender, borrowAmount); accountBorrows[msg.sender].principal = borrowBalanceNew; accountBorrows[msg.sender].interestIndex = borrowIndex; totalBorrows += borrowAmount; emit Borrow(msg.sender, borrowAmount, borrowBalanceNew, totalBorrows); return true; } /// @notice Explain to an end user what this does /// @param borrower a parameter just like in doxygen (must be followed by parameter name) /// @return Documents the return variables of a contract’s function state variable function borrowBalanceCurrent(address borrower) external returns (uint) { require(accrueInterest(), "ACCRUING_INTEREST_FAILED"); return borrowBalanceInternal(borrower); } /// @notice Explain to an end user what this does /// @param borrower a parameter just like in doxygen (must be followed by parameter name) /// @return Documents the return variables of a contract’s function state variable function borrowBalanceStored(address borrower) public view returns (uint) { return borrowBalanceInternal(borrower); } /// @notice Calculate borrowed balance of the borrower with interest rate /// @param borrower address of the borrower /// @return Borrowed balance along with accrured interest function borrowBalanceInternal(address borrower) internal view returns (uint) { BorrowSnapshot memory borrowSnapshot = accountBorrows[borrower]; if (borrowSnapshot.principal == 0) return 0; return ( borrowSnapshot.principal * borrowIndex ) / borrowSnapshot.interestIndex; } /// @notice Explain to an end user what this does /// @param borrower address of borrower /// @param repayAmount amount that is being repayed /// @return Wether or not the repayment succeeded or not function borrowRepayInternal(address borrower, uint repayAmount) internal returns (bool) { require(accrueInterest(), "ACCRUING_INTEREST_FAILED"); // Repay Amount is greater than 0 require(repayAmount > 0, "REPAY_AMOUNT_LESS_THAN_ZERO"); // Current Borrow Balance with Interest uint amountToRepay = borrowBalanceStored(borrower); // Amount to Repay must be greater than zero require(repayAmount <= amountToRepay, "REPAY_AMMOUNT_MUST_BE_LESS_THAN"); doTransferIn(borrower, repayAmount); // New Balance = Total Borrow Bal. - repayAmount uint accountBorrowsNew = amountToRepay - repayAmount; accountBorrows[borrower].principal = accountBorrowsNew; totalBorrows = totalBorrows - repayAmount; emit RepayBorrow(borrower, repayAmount, accountBorrowsNew, totalBorrows); return true; } function getCash() virtual internal view returns (uint); function doTransferIn(address from, uint amount) internal virtual returns (bool); function doTransferOut(address to, uint amount) internal virtual returns (bool); }
Get balance of underlying asset for the owner owner The address of the account to query return Balance of underlying asset
function balanceOfUnderlying(address owner) external returns(uint) { require(balanceOf(owner) > 0, "NOT_HAVING_ENOUGH_CTOKENS"); return (exchangeRateCurrent() * balanceOf(owner)) / scaleBy; }
14,113,901
./full_match/1/0xf607014406bc3Fa7aAB224a85A0318b4556e9C28/sources/browser/AuctionHouseLogicV1.sol
Win a cryptograph for the highest bidder Callable by anyone, but should be called by PA for automatisation. _cryptographIssue The issue of the Cryptograph you want to claim _isOfficial True if claiming an official cryptograph, false if claiming a community cryptograph _editionSerial If claiming an edition, specify it's specific edition issue hereGrabbing the auctionEmitting the Win event before other events are triggeredUpdate the ERC2665Actually Win the auction and claim the cryptograph
function win(uint256 _cryptographIssue, bool _isOfficial, uint256 _editionSerial) external{ TheCryptographLogicV1 _cry = TheCryptographLogicV1( CryptographIndexLogicV1(index).getCryptograph(_cryptographIssue, _isOfficial, _editionSerial) ); SingleAuctionLogicV1 _auc = SingleAuctionLogicV1(_cry.myAuction()); emit UserWin(address(_auc), _auc.currentBids(_auc.highestBidder()), _auc.highestBidder()); ERC2665LogicV1(ERC2665Lieutenant).transferACryptograph(_cry.owner(), _auc.highestBidder(), address(_cry), _auc.currentBids(_auc.highestBidder())); if(!(_auc.win(_auc.highestBidder()) == 0)){ } }
3,151,820
pragma solidity 0.6.12; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @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"); } } /** * @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"); } } } /** * @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)); } } /** * @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; } /* * @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 ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. 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; } /** * @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 OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: GPL-3.0-only /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface INBUNIERC20 { /** * @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); event Log(string log); } library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logByte(byte p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(byte)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // Encore Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless. contract EncoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many 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 ENCOREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accEncorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accEncorePerShare` (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 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. ENCOREs to distribute per block. uint256 accEncorePerShare; // Accumulated ENCOREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The ENCORE TOKEN! INBUNIERC20 public encore; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes 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; //// pending rewards awaiting anyone to massUpdate uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) { averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock)); } // Returns averge fees in this epoch function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) { averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function startNewEpoch() public { require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } 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 Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value); function initialize( INBUNIERC20 _encore, address _devaddr, address superAdmin ) public initializer { OwnableUpgradeSafe.__Ownable_init(); DEV_FEE = 1666; encore = _encore; devaddr = _devaddr; contractStartBlock = block.number; _superAdmin = superAdmin; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing ENCORE governance consensus function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accEncorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's ENCOREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing ENCORE governance consensus 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 given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing ENCORE governance consensus function setPoolWithdrawable( uint256 _pid, bool _withdrawable ) public onlyOwner { poolInfo[_pid].withdrawable = _withdrawable; } // Note contract owner is meant to be a governance contract allowing ENCORE governance consensus uint16 DEV_FEE; function setDevFee(uint16 _DEV_FEE) public onlyOwner { require(_DEV_FEE <= 2000, 'Dev fee clamped at 20%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending ENCOREs on frontend. function pendingEncore(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accEncorePerShare = pool.accEncorePerShare; return user.amount.mul(accEncorePerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { console.log("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.add(updatePool(pid)); } pendingRewards = pendingRewards.sub(allRewards); } // ---- // Function that adds pending rewards, called by the ENCORE token. // ---- uint256 private encoreBalance; function addPendingRewards(uint256 _) public { uint256 newRewards = encore.balanceOf(address(this)).sub(encoreBalance); if(newRewards > 0) { encoreBalance = encore.balanceOf(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.add(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) internal returns (uint256 encoreRewardWhole) { PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } encoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get .div(totalAllocPoint); // we can do this because pools are only mass updated uint256 encoreRewardFee = encoreRewardWhole.mul(DEV_FEE).div(10000); uint256 encoreRewardToDistribute = encoreRewardWhole.sub(encoreRewardFee); pending_DEV_rewards = pending_DEV_rewards.add(encoreRewardFee); pool.accEncorePerShare = pool.accEncorePerShare.add( encoreRewardToDistribute.mul(1e12).div(tokenSupply) ); } // Deposit tokens to EncoreVault for ENCORE allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, pool, user, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accEncorePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function depositFor(address depositFor, uint256 _pid, uint256 _amount) public { // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, pool, user, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); // This is depositedFor address } user.rewardDebt = user.amount.mul(pool.accEncorePerShare).div(1e12); /// This is deposited for address emit Deposit(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public { PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{ PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount); _withdraw(_pid, _amount, owner, msg.sender); } // Withdraw tokens from EncoreVault. function withdraw(uint256 _pid, uint256 _amount) public { _withdraw(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); massUpdatePools(); updateAndPayOutPending(_pid, pool, user, from); // Update balances of from this is not withdrawal but claiming ENCORE farmed if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.token.safeTransfer(address(to), _amount); } user.rewardDebt = user.amount.mul(pool.accEncorePerShare).div(1e12); emit Withdraw(to, _pid, _amount); } function updateAndPayOutPending(uint256 _pid, PoolInfo storage pool, UserInfo storage user, address from) internal { if(user.amount == 0) return; uint256 pending = user .amount .mul(pool.accEncorePerShare) .div(1e12) .sub(user.rewardDebt); if(pending > 0) { safeEncoreTransfer(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin { require(isContract(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).approve(contractAddress, _amount); } function isContract(address addr) public returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe encore transfer function, just in case if rounding error causes pool to not have enough ENCOREs. function safeEncoreTransfer(address _to, uint256 _amount) internal { if(_amount == 0) return; uint256 encoreBal = encore.balanceOf(address(this)); if (_amount > encoreBal) { console.log("transfering out for to person:", _amount); console.log("Balance of this address is :", encoreBal); encore.transfer(_to, encoreBal); encoreBalance = encore.balanceOf(address(this)); } else { encore.transfer(_to, _amount); encoreBalance = encore.balanceOf(address(this)); } if(pending_DEV_rewards > 0) { uint256 devSend = pending_DEV_rewards; // Avoid recursive loop pending_DEV_rewards = 0; safeEncoreTransfer(devaddr, devSend); } } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing ENCORE governance token holders to do this functions. function setDevFeeReciever(address _devaddr) public onlyOwner { devaddr = _devaddr; } address private _superAdmin; event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the current super admin */ function superAdmin() public view returns (address) { return _superAdmin; } /** * @dev Throws if called by any account other than the superAdmin */ modifier onlySuperAdmin() { require(_superAdmin == _msgSender(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function burnSuperAdmin() public virtual onlySuperAdmin { emit SuperAdminTransfered(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function newSuperAdmin(address newOwner) public virtual onlySuperAdmin { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SuperAdminTransfered(_superAdmin, newOwner); _superAdmin = newOwner; } }
Test coverage [x] Does user get the deposited amounts? [x] Does user that its deposited for update correcty? [x] Does the depositor get their tokens decreased requires no allowances Transfer pending tokens to user
function depositFor(address depositFor, uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; massUpdatePools(); if(_amount > 0) { pool.token.safeTransferFrom(address(msg.sender), address(this), _amount); } emit Deposit(depositFor, _pid, _amount); }
371,541
./full_match/4/0x1486cA30807A887eEF44fe04D5c55d044e915D40/sources/Auction.sol
Bid on the auction with the value sent together with this transaction. The value will only be refunded if the auction is not won. Revert the call if the bidding period is over. Sending back the money by simply using highestBidder.send(highestBid) is a security risk because it could execute an untrusted contract. It is always safer to let the recipients withdraw their money themselves.
function bid(uint valueBid) external { if (ended) revert AuctionAlreadyEnded(); if (block.timestamp > auctionEndTime) revert AuctionAlreadyEnded(); if (highestBid == 0) if (valueBid < currentPrice) revert BidNotHighEnough(highestBid); if (valueBid <= highestBid) revert BidNotHighEnough(highestBid); pendingReturns[highestBidder] += highestBid; }*/ bidders[highestBidder] += highestBid; highestBidder = msg.sender; highestBid = valueBid;
13,364,414
// Copyright 2019 Cartesi Pte. Ltd. // SPDX-License-Identifier: Apache-2.0 // 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.7.0; import "./RiscVConstants.sol"; import "./RiscVDecoder.sol"; import "./VirtualMemory.sol"; import "./MemoryInteractor.sol"; import "./CSRExecute.sol"; import "./RiscVInstructions/BranchInstructions.sol"; import "./RiscVInstructions/ArithmeticInstructions.sol"; import "./RiscVInstructions/ArithmeticImmediateInstructions.sol"; import "./RiscVInstructions/S_Instructions.sol"; import "./RiscVInstructions/StandAloneInstructions.sol"; import "./RiscVInstructions/AtomicInstructions.sol"; import "./RiscVInstructions/EnvTrapIntInstructions.sol"; import {Exceptions} from "./Exceptions.sol"; /// @title Execute /// @author Felipe Argento /// @notice Finds instructions and execute them or delegate their execution to another library library Execute { uint256 constant ARITH_IMM_GROUP = 0; uint256 constant ARITH_IMM_GROUP_32 = 1; uint256 constant ARITH_GROUP = 0; uint256 constant ARITH_GROUP_32 = 1; uint256 constant CSRRW_CODE = 0; uint256 constant CSRRWI_CODE = 1; uint256 constant CSRRS_CODE = 0; uint256 constant CSRRC_CODE = 1; uint256 constant CSRRSI_CODE = 0; uint256 constant CSRRCI_CODE = 1; /// @notice Finds associated instruction and execute it. /// @param mi Memory Interactor with which Step function is interacting. /// @param pc Current pc /// @param insn Instruction. /// @return executeStatus.illegal if an illegal instruction exception was raised, or executeStatus.retired if not (even if it raises other exceptions). function executeInsn( MemoryInteractor mi, uint32 insn, uint64 pc ) public returns (executeStatus) { // Finds instruction associated with that opcode // Sometimes the opcode fully defines the associated instruction, but most // of the times it only specifies which group it belongs to. // For example, an opcode of: 01100111 is always a LUI instruction but an // opcode of 1100011 might be BEQ, BNE, BLT etc // Reference: riscv-spec-v2.2.pdf - Table 19.2 - Page 104 // OPCODE is located on bit 0 - 6 of the following types of 32bits instructions: // R-Type, I-Type, S-Trype and U-Type // Reference: riscv-spec-v2.2.pdf - Figure 2.2 - Page 11 uint32 opcode = RiscVDecoder.insnOpcode(insn); if (opcode < 0x002f) { if (opcode < 0x0017) { if (opcode == 0x0003) { return loadFunct3( mi, insn, pc ); } else if (opcode == 0x000f) { return fenceGroup( mi, insn, pc ); } else if (opcode == 0x0013) { return executeArithmeticImmediate( mi, insn, pc, ARITH_IMM_GROUP ); } } else if (opcode > 0x0017) { if (opcode == 0x001b) { return executeArithmeticImmediate( mi, insn, pc, ARITH_IMM_GROUP_32 ); } else if (opcode == 0x0023) { return storeFunct3( mi, insn, pc ); } } else if (opcode == 0x0017) { StandAloneInstructions.executeAuipc( mi, insn, pc ); return advanceToNextInsn(mi, pc); } } else if (opcode > 0x002f) { if (opcode < 0x0063) { if (opcode == 0x0033) { return executeArithmetic( mi, insn, pc, ARITH_GROUP ); } else if (opcode == 0x003b) { return executeArithmetic( mi, insn, pc, ARITH_GROUP_32 ); } else if (opcode == 0x0037) { StandAloneInstructions.executeLui( mi, insn ); return advanceToNextInsn(mi, pc); } } else if (opcode > 0x0063) { if (opcode == 0x0067) { (bool succ, uint64 newPc) = StandAloneInstructions.executeJalr( mi, insn, pc ); if (succ) { return executeJump(mi, newPc); } else { return raiseMisalignedFetchException(mi, newPc); } } else if (opcode == 0x0073) { return csrEnvTrapIntMmFunct3( mi, insn, pc ); } else if (opcode == 0x006f) { (bool succ, uint64 newPc) = StandAloneInstructions.executeJal( mi, insn, pc ); if (succ) { return executeJump(mi, newPc); } else { return raiseMisalignedFetchException(mi, newPc); } } } else if (opcode == 0x0063) { return executeBranch( mi, insn, pc ); } } else if (opcode == 0x002f) { return atomicFunct3Funct5( mi, insn, pc ); } return raiseIllegalInsnException(mi, insn); } /// @notice Finds and execute Arithmetic Immediate instruction /// @param mi Memory Interactor with which Step function is interacting. /// @param pc Current pc /// @param insn Instruction. /// @return executeStatus.illegal if an illegal instruction exception was raised, or executeStatus.retired if not (even if it raises other exceptions). function executeArithmeticImmediate( MemoryInteractor mi, uint32 insn, uint64 pc, uint256 immGroup ) public returns (executeStatus) { uint32 rd = RiscVDecoder.insnRd(insn); uint64 arithImmResult; bool insnValid; if (rd != 0) { if (immGroup == ARITH_IMM_GROUP) { (arithImmResult, insnValid) = ArithmeticImmediateInstructions.arithmeticImmediateFunct3(mi, insn); } else { //immGroup == ARITH_IMM_GROUP_32 (arithImmResult, insnValid) = ArithmeticImmediateInstructions.arithmeticImmediate32Funct3(mi, insn); } if (!insnValid) { return raiseIllegalInsnException(mi, insn); } mi.writeX(rd, arithImmResult); } return advanceToNextInsn(mi, pc); } /// @notice Finds and execute Arithmetic instruction /// @param mi Memory Interactor with which Step function is interacting. /// @param pc Current pc /// @param insn Instruction. /// @return executeStatus.illegal if an illegal instruction exception was raised, or executeStatus.retired if not (even if it raises other exceptions). function executeArithmetic( MemoryInteractor mi, uint32 insn, uint64 pc, uint256 groupCode ) public returns (executeStatus) { uint32 rd = RiscVDecoder.insnRd(insn); if (rd != 0) { uint64 arithResult = 0; bool insnValid = false; if (groupCode == ARITH_GROUP) { (arithResult, insnValid) = ArithmeticInstructions.arithmeticFunct3Funct7(mi, insn); } else { // groupCode == arith_32Group (arithResult, insnValid) = ArithmeticInstructions.arithmetic32Funct3Funct7(mi, insn); } if (!insnValid) { return raiseIllegalInsnException(mi, insn); } mi.writeX( rd, arithResult); } return advanceToNextInsn(mi, pc); } /// @notice Finds and execute Branch instruction /// @param mi Memory Interactor with which Step function is interacting. /// @param pc Current pc /// @param insn Instruction. /// @return executeStatus.illegal if an illegal instruction exception was raised, or executeStatus.retired if not (even if it raises other exceptions). function executeBranch( MemoryInteractor mi, uint32 insn, uint64 pc) public returns (executeStatus) { (bool branchValuated, bool insnValid) = BranchInstructions.branchFunct3(mi, insn); if (!insnValid) { return raiseIllegalInsnException(mi, insn); } if (branchValuated) { uint64 newPc = uint64(int64(pc) + int64(RiscVDecoder.insnBImm(insn))); if ((newPc & 3) != 0) { return raiseMisalignedFetchException(mi, newPc); }else { return executeJump(mi, newPc); } } return advanceToNextInsn(mi, pc); } /// @notice Finds and execute Load instruction /// @param mi Memory Interactor with which Step function is interacting. /// @param pc Current pc /// @param insn Instruction. /// @return executeStatus.illegal if an illegal instruction exception was raised, or executeStatus.retired if not (even if it raises other exceptions). function executeLoad( MemoryInteractor mi, uint32 insn, uint64 pc, uint64 wordSize, bool isSigned ) public returns (executeStatus) { uint64 vaddr = mi.readX( RiscVDecoder.insnRs1(insn)); int32 imm = RiscVDecoder.insnIImm(insn); uint32 rd = RiscVDecoder.insnRd(insn); (bool succ, uint64 val) = VirtualMemory.readVirtualMemory( mi, wordSize, vaddr + uint64(imm) ); if (succ) { if (isSigned) { val = BitsManipulationLibrary.uint64SignExtension(val, wordSize); } if (rd != 0) { mi.writeX(rd, val); } return advanceToNextInsn(mi, pc); } else { //return advanceToRaisedException() return executeStatus.retired; } } /// @notice Execute S_fence_VMA instruction /// @param mi Memory Interactor with which Step function is interacting. /// @param pc Current pc /// @param insn Instruction. /// @return executeStatus.illegal if an illegal instruction exception was raised, or executeStatus.retired if not (even if it raises other exceptions). function executeSfenceVma( MemoryInteractor mi, uint32 insn, uint64 pc ) public returns (executeStatus) { if ((insn & 0xFE007FFF) == 0x12000073) { uint64 priv = mi.readIflagsPrv(); uint64 mstatus = mi.readMstatus(); if (priv == RiscVConstants.getPrvU() || (priv == RiscVConstants.getPrvS() && ((mstatus & RiscVConstants.getMstatusTvmMask() != 0)))) { return raiseIllegalInsnException(mi, insn); } return advanceToNextInsn(mi, pc); } else { return raiseIllegalInsnException(mi, insn); } } /// @notice Execute jump - writes a new pc /// @param mi Memory Interactor with which Step function is interacting. /// @param newPc pc to be written /// @return executeStatus.illegal if an illegal instruction exception was raised, or executeStatus.retired if not (even if it raises other exceptions). function executeJump(MemoryInteractor mi, uint64 newPc) public returns (executeStatus) { mi.writePc( newPc); return executeStatus.retired; } /// @notice Raises Misaligned Fetch Exception /// @param mi Memory Interactor with which Step function is interacting. /// @param pc current pc /// @return executeStatus.illegal if an illegal instruction exception was raised, or executeStatus.retired if not (even if it raises other exceptions). function raiseMisalignedFetchException(MemoryInteractor mi, uint64 pc) public returns (executeStatus) { Exceptions.raiseException( mi, Exceptions.getMcauseInsnAddressMisaligned(), pc ); return executeStatus.retired; } /// @notice Raises Illegal Instruction Exception /// @param mi Memory Interactor with which Step function is interacting. /// @param insn instruction that was deemed illegal /// @return executeStatus.illegal if an illegal instruction exception was raised, or executeStatus.retired if not (even if it raises other exceptions). function raiseIllegalInsnException(MemoryInteractor mi, uint32 insn) public returns (executeStatus) { Exceptions.raiseException( mi, Exceptions.getMcauseIllegalInsn(), insn ); return executeStatus.illegal; } /// @notice Advances to next instruction by increasing pc /// @param mi Memory Interactor with which Step function is interacting. /// @param pc current pc /// @return executeStatus.illegal if an illegal instruction exception was raised, or executeStatus.retired if not (even if it raises other exceptions). function advanceToNextInsn(MemoryInteractor mi, uint64 pc) public returns (executeStatus) { mi.writePc( pc + 4); return executeStatus.retired; } /// @notice Given a fence funct3 insn, finds the func associated. /// @param mi Memory Interactor with which Step function is interacting. /// @param insn for fence funct3 field. /// @param pc Current pc /// @dev Uses binary search for performance. function fenceGroup( MemoryInteractor mi, uint32 insn, uint64 pc ) public returns(executeStatus) { if (insn == 0x0000100f) { /*insn == 0x0000*/ //return "FENCE"; //really do nothing return advanceToNextInsn(mi, pc); } else if (insn & 0xf00fff80 != 0) { /*insn == 0x0001*/ return raiseIllegalInsnException(mi, insn); } //return "FENCE_I"; //really do nothing return advanceToNextInsn(mi, pc); } /// @notice Given csr env trap int mm funct3 insn, finds the func associated. /// @param mi Memory Interactor with which Step function is interacting. /// @param insn for fence funct3 field. /// @param pc Current pc /// @dev Uses binary search for performance. function csrEnvTrapIntMmFunct3( MemoryInteractor mi, uint32 insn, uint64 pc ) public returns (executeStatus) { uint32 funct3 = RiscVDecoder.insnFunct3(insn); if (funct3 < 0x0003) { if (funct3 == 0x0000) { /*funct3 == 0x0000*/ return envTrapIntGroup( mi, insn, pc ); } else if (funct3 == 0x0002) { /*funct3 == 0x0002*/ //return "CSRRS"; if (CSRExecute.executeCsrSC( mi, insn, CSRRS_CODE )) { return advanceToNextInsn(mi, pc); } else { return raiseIllegalInsnException(mi, insn); } } else if (funct3 == 0x0001) { /*funct3 == 0x0001*/ //return "CSRRW"; if (CSRExecute.executeCsrRW( mi, insn, CSRRW_CODE )) { return advanceToNextInsn(mi, pc); } else { return raiseIllegalInsnException(mi, insn); } } } else if (funct3 > 0x0003) { if (funct3 == 0x0005) { /*funct3 == 0x0005*/ //return "CSRRWI"; if (CSRExecute.executeCsrRW( mi, insn, CSRRWI_CODE )) { return advanceToNextInsn(mi, pc); } else { return raiseIllegalInsnException(mi, insn); } } else if (funct3 == 0x0007) { /*funct3 == 0x0007*/ //return "CSRRCI"; if (CSRExecute.executeCsrSCI( mi, insn, CSRRCI_CODE )) { return advanceToNextInsn(mi, pc); } else { return raiseIllegalInsnException(mi, insn); } } else if (funct3 == 0x0006) { /*funct3 == 0x0006*/ //return "CSRRSI"; if (CSRExecute.executeCsrSCI( mi, insn, CSRRSI_CODE )) { return advanceToNextInsn(mi, pc); } else { return raiseIllegalInsnException(mi, insn); } } } else if (funct3 == 0x0003) { /*funct3 == 0x0003*/ //return "CSRRC"; if (CSRExecute.executeCsrSC( mi, insn, CSRRC_CODE )) { return advanceToNextInsn(mi, pc); } else { return raiseIllegalInsnException(mi, insn); } } return raiseIllegalInsnException(mi, insn); } /// @notice Given a store funct3 group insn, finds the function associated. /// @param mi Memory Interactor with which Step function is interacting. /// @param insn for store funct3 field /// @param pc Current pc /// @dev Uses binary search for performance. function storeFunct3( MemoryInteractor mi, uint32 insn, uint64 pc ) public returns (executeStatus) { uint32 funct3 = RiscVDecoder.insnFunct3(insn); if (funct3 == 0x0000) { /*funct3 == 0x0000*/ //return "SB"; return S_Instructions.sb( mi, insn ) ? advanceToNextInsn(mi, pc) : executeStatus.retired; } else if (funct3 > 0x0001) { if (funct3 == 0x0002) { /*funct3 == 0x0002*/ //return "SW"; return S_Instructions.sw( mi, insn ) ? advanceToNextInsn(mi, pc) : executeStatus.retired; } else if (funct3 == 0x0003) { /*funct3 == 0x0003*/ //return "SD"; return S_Instructions.sd( mi, insn ) ? advanceToNextInsn(mi, pc) : executeStatus.retired; } } else if (funct3 == 0x0001) { /*funct3 == 0x0001*/ //return "SH"; return S_Instructions.sh( mi, insn ) ? advanceToNextInsn(mi, pc) : executeStatus.retired; } return raiseIllegalInsnException(mi, insn); } /// @notice Given a env trap int group insn, finds the func associated. /// @param mi Memory Interactor with which Step function is interacting. /// @param insn insn for env trap int group field. /// @param pc Current pc /// @dev Uses binary search for performance. function envTrapIntGroup( MemoryInteractor mi, uint32 insn, uint64 pc ) public returns (executeStatus) { if (insn < 0x10200073) { if (insn == 0x0073) { EnvTrapIntInstructions.executeECALL( mi ); return executeStatus.retired; } else if (insn == 0x200073) { // No U-Mode traps raiseIllegalInsnException(mi, insn); } else if (insn == 0x100073) { EnvTrapIntInstructions.executeEBREAK( mi ); return executeStatus.retired; } } else if (insn > 0x10200073) { if (insn == 0x10500073) { if (!EnvTrapIntInstructions.executeWFI( mi )) { return raiseIllegalInsnException(mi, insn); } return advanceToNextInsn(mi, pc); } else if (insn == 0x30200073) { if (!EnvTrapIntInstructions.executeMRET( mi )) { return raiseIllegalInsnException(mi, insn); } return executeStatus.retired; } } else if (insn == 0x10200073) { if (!EnvTrapIntInstructions.executeSRET( mi ) ) { return raiseIllegalInsnException(mi, insn); } return executeStatus.retired; } return executeSfenceVma( mi, insn, pc ); } /// @notice Given a load funct3 group instruction, finds the function /// @param mi Memory Interactor with which Step function is interacting. /// @param insn for load funct3 field /// @param pc Current pc /// @dev Uses binary search for performance. function loadFunct3( MemoryInteractor mi, uint32 insn, uint64 pc ) public returns (executeStatus) { uint32 funct3 = RiscVDecoder.insnFunct3(insn); if (funct3 < 0x0003) { if (funct3 == 0x0000) { //return "LB"; return executeLoad( mi, insn, pc, 8, true ); } else if (funct3 == 0x0002) { //return "LW"; return executeLoad( mi, insn, pc, 32, true ); } else if (funct3 == 0x0001) { //return "LH"; return executeLoad( mi, insn, pc, 16, true ); } } else if (funct3 > 0x0003) { if (funct3 == 0x0004) { //return "LBU"; return executeLoad( mi, insn, pc, 8, false ); } else if (funct3 == 0x0006) { //return "LWU"; return executeLoad( mi, insn, pc, 32, false ); } else if (funct3 == 0x0005) { //return "LHU"; return executeLoad( mi, insn, pc, 16, false ); } } else if (funct3 == 0x0003) { //return "LD"; return executeLoad( mi, insn, pc, 64, true ); } return raiseIllegalInsnException(mi, insn); } function atomicFunct3Funct5( MemoryInteractor mi, uint32 insn, uint64 pc ) public returns (executeStatus) { uint32 funct3Funct5 = RiscVDecoder.insnFunct3Funct5(insn); bool atomSucc; // TO-DO: transform in binary search for performance if (funct3Funct5 == 0x42) { if ((insn & 0x1f00000) == 0 ) { atomSucc = AtomicInstructions.executeLR( mi, insn, 32 ); } else { return raiseIllegalInsnException(mi, insn); } } else if (funct3Funct5 == 0x43) { atomSucc = AtomicInstructions.executeSC( mi, insn, 32 ); } else if (funct3Funct5 == 0x41) { atomSucc = AtomicInstructions.executeAMOSWAPW( mi, insn ); } else if (funct3Funct5 == 0x40) { atomSucc = AtomicInstructions.executeAMOADDW( mi, insn ); } else if (funct3Funct5 == 0x44) { atomSucc = AtomicInstructions.executeAMOXORW( mi, insn ); } else if (funct3Funct5 == 0x4c) { atomSucc = AtomicInstructions.executeAMOANDW( mi, insn ); } else if (funct3Funct5 == 0x48) { atomSucc = AtomicInstructions.executeAMOORW( mi, insn ); } else if (funct3Funct5 == 0x50) { atomSucc = AtomicInstructions.executeAMOMINW( mi, insn ); } else if (funct3Funct5 == 0x54) { atomSucc = AtomicInstructions.executeAMOMAXW( mi, insn ); } else if (funct3Funct5 == 0x58) { atomSucc = AtomicInstructions.executeAMOMINUW( mi, insn ); } else if (funct3Funct5 == 0x5c) { atomSucc = AtomicInstructions.executeAMOMAXUW( mi, insn ); } else if (funct3Funct5 == 0x62) { if ((insn & 0x1f00000) == 0 ) { atomSucc = AtomicInstructions.executeLR( mi, insn, 64 ); } } else if (funct3Funct5 == 0x63) { atomSucc = AtomicInstructions.executeSC( mi, insn, 64 ); } else if (funct3Funct5 == 0x61) { atomSucc = AtomicInstructions.executeAMOSWAPD( mi, insn ); } else if (funct3Funct5 == 0x60) { atomSucc = AtomicInstructions.executeAMOADDD( mi, insn ); } else if (funct3Funct5 == 0x64) { atomSucc = AtomicInstructions.executeAMOXORD( mi, insn ); } else if (funct3Funct5 == 0x6c) { atomSucc = AtomicInstructions.executeAMOANDD( mi, insn ); } else if (funct3Funct5 == 0x68) { atomSucc = AtomicInstructions.executeAMOORD( mi, insn ); } else if (funct3Funct5 == 0x70) { atomSucc = AtomicInstructions.executeAMOMIND( mi, insn ); } else if (funct3Funct5 == 0x74) { atomSucc = AtomicInstructions.executeAMOMAXD( mi, insn ); } else if (funct3Funct5 == 0x78) { atomSucc = AtomicInstructions.executeAMOMINUD( mi, insn ); } else if (funct3Funct5 == 0x7c) { atomSucc = AtomicInstructions.executeAMOMAXUD( mi, insn ); } if (atomSucc) { return advanceToNextInsn(mi, pc); } else { return executeStatus.retired; } } enum executeStatus { illegal, // Exception was raised retired // Instruction retired - having raised or not an exception } }
Given csr env trap int mm funct3 insn, finds the func associated. mi Memory Interactor with which Step function is interacting. insn for fence funct3 field. pc Current pc Uses binary search for performance.return "CSRRS";return "CSRRWI";
function csrEnvTrapIntMmFunct3( MemoryInteractor mi, uint32 insn, uint64 pc ) public returns (executeStatus) { uint32 funct3 = RiscVDecoder.insnFunct3(insn); if (funct3 < 0x0003) { if (funct3 == 0x0000) { return envTrapIntGroup( mi, insn, pc ); if (CSRExecute.executeCsrSC( mi, insn, CSRRS_CODE )) { return advanceToNextInsn(mi, pc); return raiseIllegalInsnException(mi, insn); } mi, insn, CSRRW_CODE )) { return advanceToNextInsn(mi, pc); return raiseIllegalInsnException(mi, insn); } } if (funct3 == 0x0005) { if (CSRExecute.executeCsrRW( mi, insn, CSRRWI_CODE )) { return advanceToNextInsn(mi, pc); return raiseIllegalInsnException(mi, insn); } mi, insn, CSRRCI_CODE )) { return advanceToNextInsn(mi, pc); return raiseIllegalInsnException(mi, insn); } mi, insn, CSRRSI_CODE )) { return advanceToNextInsn(mi, pc); return raiseIllegalInsnException(mi, insn); } } mi, insn, CSRRC_CODE )) { return advanceToNextInsn(mi, pc); return raiseIllegalInsnException(mi, insn); } } return raiseIllegalInsnException(mi, insn); }
12,842,736
pragma solidity >=0.4.25 <0.6.0; pragma experimental ABIEncoderV2; /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Modifiable * @notice A contract with basic modifiers */ contract Modifiable { // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier notNullAddress(address _address) { require(_address != address(0)); _; } modifier notThisAddress(address _address) { require(_address != address(this)); _; } modifier notNullOrThisAddress(address _address) { require(_address != address(0)); require(_address != address(this)); _; } modifier notSameAddresses(address _address1, address _address2) { if (_address1 != _address2) _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title SelfDestructible * @notice Contract that allows for self-destruction */ contract SelfDestructible { // // Variables // ----------------------------------------------------------------------------------------------------------------- bool public selfDestructionDisabled; // // Events // ----------------------------------------------------------------------------------------------------------------- event SelfDestructionDisabledEvent(address wallet); event TriggerSelfDestructionEvent(address wallet); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Get the address of the destructor role function destructor() public view returns (address); /// @notice Disable self-destruction of this contract /// @dev This operation can not be undone function disableSelfDestruction() public { // Require that sender is the assigned destructor require(destructor() == msg.sender); // Disable self-destruction selfDestructionDisabled = true; // Emit event emit SelfDestructionDisabledEvent(msg.sender); } /// @notice Destroy this contract function triggerSelfDestruction() public { // Require that sender is the assigned destructor require(destructor() == msg.sender); // Require that self-destruction has not been disabled require(!selfDestructionDisabled); // Emit event emit TriggerSelfDestructionEvent(msg.sender); // Self-destruct and reward destructor selfdestruct(msg.sender); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Ownable * @notice A modifiable that has ownership roles */ contract Ownable is Modifiable, SelfDestructible { // // Variables // ----------------------------------------------------------------------------------------------------------------- address public deployer; address public operator; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetDeployerEvent(address oldDeployer, address newDeployer); event SetOperatorEvent(address oldOperator, address newOperator); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address _deployer) internal notNullOrThisAddress(_deployer) { deployer = _deployer; operator = _deployer; } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Return the address that is able to initiate self-destruction function destructor() public view returns (address) { return deployer; } /// @notice Set the deployer of this contract /// @param newDeployer The address of the new deployer function setDeployer(address newDeployer) public onlyDeployer notNullOrThisAddress(newDeployer) { if (newDeployer != deployer) { // Set new deployer address oldDeployer = deployer; deployer = newDeployer; // Emit event emit SetDeployerEvent(oldDeployer, newDeployer); } } /// @notice Set the operator of this contract /// @param newOperator The address of the new operator function setOperator(address newOperator) public onlyOperator notNullOrThisAddress(newOperator) { if (newOperator != operator) { // Set new operator address oldOperator = operator; operator = newOperator; // Emit event emit SetOperatorEvent(oldOperator, newOperator); } } /// @notice Gauge whether message sender is deployer or not /// @return true if msg.sender is deployer, else false function isDeployer() internal view returns (bool) { return msg.sender == deployer; } /// @notice Gauge whether message sender is operator or not /// @return true if msg.sender is operator, else false function isOperator() internal view returns (bool) { return msg.sender == operator; } /// @notice Gauge whether message sender is operator or deployer on the one hand, or none of these on these on /// on the other hand /// @return true if msg.sender is operator, else false function isDeployerOrOperator() internal view returns (bool) { return isDeployer() || isOperator(); } // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier onlyDeployer() { require(isDeployer()); _; } modifier notDeployer() { require(!isDeployer()); _; } modifier onlyOperator() { require(isOperator()); _; } modifier notOperator() { require(!isOperator()); _; } modifier onlyDeployerOrOperator() { require(isDeployerOrOperator()); _; } modifier notDeployerOrOperator() { require(!isDeployerOrOperator()); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Servable * @notice An ownable that contains registered services and their actions */ contract Servable is Ownable { // // Types // ----------------------------------------------------------------------------------------------------------------- struct ServiceInfo { bool registered; uint256 activationTimestamp; mapping(bytes32 => bool) actionsEnabledMap; bytes32[] actionsList; } // // Variables // ----------------------------------------------------------------------------------------------------------------- mapping(address => ServiceInfo) internal registeredServicesMap; uint256 public serviceActivationTimeout; // // Events // ----------------------------------------------------------------------------------------------------------------- event ServiceActivationTimeoutEvent(uint256 timeoutInSeconds); event RegisterServiceEvent(address service); event RegisterServiceDeferredEvent(address service, uint256 timeout); event DeregisterServiceEvent(address service); event EnableServiceActionEvent(address service, string action); event DisableServiceActionEvent(address service, string action); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the service activation timeout /// @param timeoutInSeconds The set timeout in unit of seconds function setServiceActivationTimeout(uint256 timeoutInSeconds) public onlyDeployer { serviceActivationTimeout = timeoutInSeconds; // Emit event emit ServiceActivationTimeoutEvent(timeoutInSeconds); } /// @notice Register a service contract whose activation is immediate /// @param service The address of the service contract to be registered function registerService(address service) public onlyDeployer notNullOrThisAddress(service) { _registerService(service, 0); // Emit event emit RegisterServiceEvent(service); } /// @notice Register a service contract whose activation is deferred by the service activation timeout /// @param service The address of the service contract to be registered function registerServiceDeferred(address service) public onlyDeployer notNullOrThisAddress(service) { _registerService(service, serviceActivationTimeout); // Emit event emit RegisterServiceDeferredEvent(service, serviceActivationTimeout); } /// @notice Deregister a service contract /// @param service The address of the service contract to be deregistered function deregisterService(address service) public onlyDeployer notNullOrThisAddress(service) { require(registeredServicesMap[service].registered); registeredServicesMap[service].registered = false; // Emit event emit DeregisterServiceEvent(service); } /// @notice Enable a named action in an already registered service contract /// @param service The address of the registered service contract /// @param action The name of the action to be enabled function enableServiceAction(address service, string memory action) public onlyDeployer notNullOrThisAddress(service) { require(registeredServicesMap[service].registered); bytes32 actionHash = hashString(action); require(!registeredServicesMap[service].actionsEnabledMap[actionHash]); registeredServicesMap[service].actionsEnabledMap[actionHash] = true; registeredServicesMap[service].actionsList.push(actionHash); // Emit event emit EnableServiceActionEvent(service, action); } /// @notice Enable a named action in a service contract /// @param service The address of the service contract /// @param action The name of the action to be disabled function disableServiceAction(address service, string memory action) public onlyDeployer notNullOrThisAddress(service) { bytes32 actionHash = hashString(action); require(registeredServicesMap[service].actionsEnabledMap[actionHash]); registeredServicesMap[service].actionsEnabledMap[actionHash] = false; // Emit event emit DisableServiceActionEvent(service, action); } /// @notice Gauge whether a service contract is registered /// @param service The address of the service contract /// @return true if service is registered, else false function isRegisteredService(address service) public view returns (bool) { return registeredServicesMap[service].registered; } /// @notice Gauge whether a service contract is registered and active /// @param service The address of the service contract /// @return true if service is registered and activate, else false function isRegisteredActiveService(address service) public view returns (bool) { return isRegisteredService(service) && block.timestamp >= registeredServicesMap[service].activationTimestamp; } /// @notice Gauge whether a service contract action is enabled which implies also registered and active /// @param service The address of the service contract /// @param action The name of action function isEnabledServiceAction(address service, string memory action) public view returns (bool) { bytes32 actionHash = hashString(action); return isRegisteredActiveService(service) && registeredServicesMap[service].actionsEnabledMap[actionHash]; } // // Internal functions // ----------------------------------------------------------------------------------------------------------------- function hashString(string memory _string) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_string)); } // // Private functions // ----------------------------------------------------------------------------------------------------------------- function _registerService(address service, uint256 timeout) private { if (!registeredServicesMap[service].registered) { registeredServicesMap[service].registered = true; registeredServicesMap[service].activationTimestamp = block.timestamp + timeout; } } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier onlyActiveService() { require(isRegisteredActiveService(msg.sender)); _; } modifier onlyEnabledServiceAction(string memory action) { require(isEnabledServiceAction(msg.sender, action)); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library */ /** * @title SafeMathIntLib * @dev Math operations with safety checks that throw on error */ library SafeMathIntLib { int256 constant INT256_MIN = int256((uint256(1) << 255)); int256 constant INT256_MAX = int256(~((uint256(1) << 255))); // //Functions below accept positive and negative integers and result must not overflow. // function div(int256 a, int256 b) internal pure returns (int256) { require(a != INT256_MIN || b != - 1); return a / b; } function mul(int256 a, int256 b) internal pure returns (int256) { require(a != - 1 || b != INT256_MIN); // overflow require(b != - 1 || a != INT256_MIN); // overflow int256 c = a * b; require((b == 0) || (c / b == a)); return c; } function sub(int256 a, int256 b) internal pure returns (int256) { require((b >= 0 && a - b <= a) || (b < 0 && a - b > a)); return a - b; } function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } // //Functions below only accept positive integers and result must be greater or equal to zero too. // function div_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b > 0); return a / b; } function mul_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0); int256 c = a * b; require(a == 0 || c / a == b); require(c >= 0); return c; } function sub_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0 && b <= a); return a - b; } function add_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0); int256 c = a + b; require(c >= a); return c; } // //Conversion and validation functions. // function abs(int256 a) public pure returns (int256) { return a < 0 ? neg(a) : a; } function neg(int256 a) public pure returns (int256) { return mul(a, - 1); } function toNonZeroInt256(uint256 a) public pure returns (int256) { require(a > 0 && a < (uint256(1) << 255)); return int256(a); } function toInt256(uint256 a) public pure returns (int256) { require(a >= 0 && a < (uint256(1) << 255)); return int256(a); } function toUInt256(int256 a) public pure returns (uint256) { require(a >= 0); return uint256(a); } function isNonZeroPositiveInt256(int256 a) public pure returns (bool) { return (a > 0); } function isPositiveInt256(int256 a) public pure returns (bool) { return (a >= 0); } function isNonZeroNegativeInt256(int256 a) public pure returns (bool) { return (a < 0); } function isNegativeInt256(int256 a) public pure returns (bool) { return (a <= 0); } // //Clamping functions. // function clamp(int256 a, int256 min, int256 max) public pure returns (int256) { if (a < min) return min; return (a > max) ? max : a; } function clampMin(int256 a, int256 min) public pure returns (int256) { return (a < min) ? min : a; } function clampMax(int256 a, int256 max) public pure returns (int256) { return (a > max) ? max : a; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library BlockNumbUintsLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Entry { uint256 blockNumber; uint256 value; } struct BlockNumbUints { Entry[] entries; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function currentValue(BlockNumbUints storage self) internal view returns (uint256) { return valueAt(self, block.number); } function currentEntry(BlockNumbUints storage self) internal view returns (Entry memory) { return entryAt(self, block.number); } function valueAt(BlockNumbUints storage self, uint256 _blockNumber) internal view returns (uint256) { return entryAt(self, _blockNumber).value; } function entryAt(BlockNumbUints storage self, uint256 _blockNumber) internal view returns (Entry memory) { return self.entries[indexByBlockNumber(self, _blockNumber)]; } function addEntry(BlockNumbUints storage self, uint256 blockNumber, uint256 value) internal { require( 0 == self.entries.length || blockNumber > self.entries[self.entries.length - 1].blockNumber, "Later entry found [BlockNumbUintsLib.sol:62]" ); self.entries.push(Entry(blockNumber, value)); } function count(BlockNumbUints storage self) internal view returns (uint256) { return self.entries.length; } function entries(BlockNumbUints storage self) internal view returns (Entry[] memory) { return self.entries; } function indexByBlockNumber(BlockNumbUints storage self, uint256 blockNumber) internal view returns (uint256) { require(0 < self.entries.length, "No entries found [BlockNumbUintsLib.sol:92]"); for (uint256 i = self.entries.length - 1; i >= 0; i--) if (blockNumber >= self.entries[i].blockNumber) return i; revert(); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library BlockNumbIntsLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Entry { uint256 blockNumber; int256 value; } struct BlockNumbInts { Entry[] entries; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function currentValue(BlockNumbInts storage self) internal view returns (int256) { return valueAt(self, block.number); } function currentEntry(BlockNumbInts storage self) internal view returns (Entry memory) { return entryAt(self, block.number); } function valueAt(BlockNumbInts storage self, uint256 _blockNumber) internal view returns (int256) { return entryAt(self, _blockNumber).value; } function entryAt(BlockNumbInts storage self, uint256 _blockNumber) internal view returns (Entry memory) { return self.entries[indexByBlockNumber(self, _blockNumber)]; } function addEntry(BlockNumbInts storage self, uint256 blockNumber, int256 value) internal { require( 0 == self.entries.length || blockNumber > self.entries[self.entries.length - 1].blockNumber, "Later entry found [BlockNumbIntsLib.sol:62]" ); self.entries.push(Entry(blockNumber, value)); } function count(BlockNumbInts storage self) internal view returns (uint256) { return self.entries.length; } function entries(BlockNumbInts storage self) internal view returns (Entry[] memory) { return self.entries; } function indexByBlockNumber(BlockNumbInts storage self, uint256 blockNumber) internal view returns (uint256) { require(0 < self.entries.length, "No entries found [BlockNumbIntsLib.sol:92]"); for (uint256 i = self.entries.length - 1; i >= 0; i--) if (blockNumber >= self.entries[i].blockNumber) return i; revert(); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library ConstantsLib { // Get the fraction that represents the entirety, equivalent of 100% function PARTS_PER() public pure returns (int256) { return 1e18; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library BlockNumbDisdIntsLib { using SafeMathIntLib for int256; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Discount { int256 tier; int256 value; } struct Entry { uint256 blockNumber; int256 nominal; Discount[] discounts; } struct BlockNumbDisdInts { Entry[] entries; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function currentNominalValue(BlockNumbDisdInts storage self) internal view returns (int256) { return nominalValueAt(self, block.number); } function currentDiscountedValue(BlockNumbDisdInts storage self, int256 tier) internal view returns (int256) { return discountedValueAt(self, block.number, tier); } function currentEntry(BlockNumbDisdInts storage self) internal view returns (Entry memory) { return entryAt(self, block.number); } function nominalValueAt(BlockNumbDisdInts storage self, uint256 _blockNumber) internal view returns (int256) { return entryAt(self, _blockNumber).nominal; } function discountedValueAt(BlockNumbDisdInts storage self, uint256 _blockNumber, int256 tier) internal view returns (int256) { Entry memory entry = entryAt(self, _blockNumber); if (0 < entry.discounts.length) { uint256 index = indexByTier(entry.discounts, tier); if (0 < index) return entry.nominal.mul( ConstantsLib.PARTS_PER().sub(entry.discounts[index - 1].value) ).div( ConstantsLib.PARTS_PER() ); else return entry.nominal; } else return entry.nominal; } function entryAt(BlockNumbDisdInts storage self, uint256 _blockNumber) internal view returns (Entry memory) { return self.entries[indexByBlockNumber(self, _blockNumber)]; } function addNominalEntry(BlockNumbDisdInts storage self, uint256 blockNumber, int256 nominal) internal { require( 0 == self.entries.length || blockNumber > self.entries[self.entries.length - 1].blockNumber, "Later entry found [BlockNumbDisdIntsLib.sol:101]" ); self.entries.length++; Entry storage entry = self.entries[self.entries.length - 1]; entry.blockNumber = blockNumber; entry.nominal = nominal; } function addDiscountedEntry(BlockNumbDisdInts storage self, uint256 blockNumber, int256 nominal, int256[] memory discountTiers, int256[] memory discountValues) internal { require(discountTiers.length == discountValues.length, "Parameter array lengths mismatch [BlockNumbDisdIntsLib.sol:118]"); addNominalEntry(self, blockNumber, nominal); Entry storage entry = self.entries[self.entries.length - 1]; for (uint256 i = 0; i < discountTiers.length; i++) entry.discounts.push(Discount(discountTiers[i], discountValues[i])); } function count(BlockNumbDisdInts storage self) internal view returns (uint256) { return self.entries.length; } function entries(BlockNumbDisdInts storage self) internal view returns (Entry[] memory) { return self.entries; } function indexByBlockNumber(BlockNumbDisdInts storage self, uint256 blockNumber) internal view returns (uint256) { require(0 < self.entries.length, "No entries found [BlockNumbDisdIntsLib.sol:148]"); for (uint256 i = self.entries.length - 1; i >= 0; i--) if (blockNumber >= self.entries[i].blockNumber) return i; revert(); } /// @dev The index returned here is 1-based function indexByTier(Discount[] memory discounts, int256 tier) internal pure returns (uint256) { require(0 < discounts.length, "No discounts found [BlockNumbDisdIntsLib.sol:161]"); for (uint256 i = discounts.length; i > 0; i--) if (tier >= discounts[i - 1].tier) return i; return 0; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title MonetaryTypesLib * @dev Monetary data types */ library MonetaryTypesLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Currency { address ct; uint256 id; } struct Figure { int256 amount; Currency currency; } struct NoncedAmount { uint256 nonce; int256 amount; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library BlockNumbReferenceCurrenciesLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Entry { uint256 blockNumber; MonetaryTypesLib.Currency currency; } struct BlockNumbReferenceCurrencies { mapping(address => mapping(uint256 => Entry[])) entriesByCurrency; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function currentCurrency(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency) internal view returns (MonetaryTypesLib.Currency storage) { return currencyAt(self, referenceCurrency, block.number); } function currentEntry(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency) internal view returns (Entry storage) { return entryAt(self, referenceCurrency, block.number); } function currencyAt(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency, uint256 _blockNumber) internal view returns (MonetaryTypesLib.Currency storage) { return entryAt(self, referenceCurrency, _blockNumber).currency; } function entryAt(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency, uint256 _blockNumber) internal view returns (Entry storage) { return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][indexByBlockNumber(self, referenceCurrency, _blockNumber)]; } function addEntry(BlockNumbReferenceCurrencies storage self, uint256 blockNumber, MonetaryTypesLib.Currency memory referenceCurrency, MonetaryTypesLib.Currency memory currency) internal { require( 0 == self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length || blockNumber > self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length - 1].blockNumber, "Later entry found for currency [BlockNumbReferenceCurrenciesLib.sol:67]" ); self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].push(Entry(blockNumber, currency)); } function count(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency) internal view returns (uint256) { return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length; } function entriesByCurrency(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency) internal view returns (Entry[] storage) { return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id]; } function indexByBlockNumber(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency, uint256 blockNumber) internal view returns (uint256) { require(0 < self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length, "No entries found for currency [BlockNumbReferenceCurrenciesLib.sol:97]"); for (uint256 i = self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length - 1; i >= 0; i--) if (blockNumber >= self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][i].blockNumber) return i; revert(); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library BlockNumbFiguresLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Entry { uint256 blockNumber; MonetaryTypesLib.Figure value; } struct BlockNumbFigures { Entry[] entries; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function currentValue(BlockNumbFigures storage self) internal view returns (MonetaryTypesLib.Figure storage) { return valueAt(self, block.number); } function currentEntry(BlockNumbFigures storage self) internal view returns (Entry storage) { return entryAt(self, block.number); } function valueAt(BlockNumbFigures storage self, uint256 _blockNumber) internal view returns (MonetaryTypesLib.Figure storage) { return entryAt(self, _blockNumber).value; } function entryAt(BlockNumbFigures storage self, uint256 _blockNumber) internal view returns (Entry storage) { return self.entries[indexByBlockNumber(self, _blockNumber)]; } function addEntry(BlockNumbFigures storage self, uint256 blockNumber, MonetaryTypesLib.Figure memory value) internal { require( 0 == self.entries.length || blockNumber > self.entries[self.entries.length - 1].blockNumber, "Later entry found [BlockNumbFiguresLib.sol:65]" ); self.entries.push(Entry(blockNumber, value)); } function count(BlockNumbFigures storage self) internal view returns (uint256) { return self.entries.length; } function entries(BlockNumbFigures storage self) internal view returns (Entry[] storage) { return self.entries; } function indexByBlockNumber(BlockNumbFigures storage self, uint256 blockNumber) internal view returns (uint256) { require(0 < self.entries.length, "No entries found [BlockNumbFiguresLib.sol:95]"); for (uint256 i = self.entries.length - 1; i >= 0; i--) if (blockNumber >= self.entries[i].blockNumber) return i; revert(); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Configuration * @notice An oracle for configurations values */ contract Configuration is Modifiable, Ownable, Servable { using SafeMathIntLib for int256; using BlockNumbUintsLib for BlockNumbUintsLib.BlockNumbUints; using BlockNumbIntsLib for BlockNumbIntsLib.BlockNumbInts; using BlockNumbDisdIntsLib for BlockNumbDisdIntsLib.BlockNumbDisdInts; using BlockNumbReferenceCurrenciesLib for BlockNumbReferenceCurrenciesLib.BlockNumbReferenceCurrencies; using BlockNumbFiguresLib for BlockNumbFiguresLib.BlockNumbFigures; // // Constants // ----------------------------------------------------------------------------------------------------------------- string constant public OPERATIONAL_MODE_ACTION = "operational_mode"; // // Enums // ----------------------------------------------------------------------------------------------------------------- enum OperationalMode {Normal, Exit} // // Variables // ----------------------------------------------------------------------------------------------------------------- OperationalMode public operationalMode = OperationalMode.Normal; BlockNumbUintsLib.BlockNumbUints private updateDelayBlocksByBlockNumber; BlockNumbUintsLib.BlockNumbUints private confirmationBlocksByBlockNumber; BlockNumbDisdIntsLib.BlockNumbDisdInts private tradeMakerFeeByBlockNumber; BlockNumbDisdIntsLib.BlockNumbDisdInts private tradeTakerFeeByBlockNumber; BlockNumbDisdIntsLib.BlockNumbDisdInts private paymentFeeByBlockNumber; mapping(address => mapping(uint256 => BlockNumbDisdIntsLib.BlockNumbDisdInts)) private currencyPaymentFeeByBlockNumber; BlockNumbIntsLib.BlockNumbInts private tradeMakerMinimumFeeByBlockNumber; BlockNumbIntsLib.BlockNumbInts private tradeTakerMinimumFeeByBlockNumber; BlockNumbIntsLib.BlockNumbInts private paymentMinimumFeeByBlockNumber; mapping(address => mapping(uint256 => BlockNumbIntsLib.BlockNumbInts)) private currencyPaymentMinimumFeeByBlockNumber; BlockNumbReferenceCurrenciesLib.BlockNumbReferenceCurrencies private feeCurrencyByCurrencyBlockNumber; BlockNumbUintsLib.BlockNumbUints private walletLockTimeoutByBlockNumber; BlockNumbUintsLib.BlockNumbUints private cancelOrderChallengeTimeoutByBlockNumber; BlockNumbUintsLib.BlockNumbUints private settlementChallengeTimeoutByBlockNumber; BlockNumbUintsLib.BlockNumbUints private fraudStakeFractionByBlockNumber; BlockNumbUintsLib.BlockNumbUints private walletSettlementStakeFractionByBlockNumber; BlockNumbUintsLib.BlockNumbUints private operatorSettlementStakeFractionByBlockNumber; BlockNumbFiguresLib.BlockNumbFigures private operatorSettlementStakeByBlockNumber; uint256 public earliestSettlementBlockNumber; bool public earliestSettlementBlockNumberUpdateDisabled; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetOperationalModeExitEvent(); event SetUpdateDelayBlocksEvent(uint256 fromBlockNumber, uint256 newBlocks); event SetConfirmationBlocksEvent(uint256 fromBlockNumber, uint256 newBlocks); event SetTradeMakerFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues); event SetTradeTakerFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues); event SetPaymentFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues); event SetCurrencyPaymentFeeEvent(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal, int256[] discountTiers, int256[] discountValues); event SetTradeMakerMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal); event SetTradeTakerMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal); event SetPaymentMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal); event SetCurrencyPaymentMinimumFeeEvent(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal); event SetFeeCurrencyEvent(uint256 fromBlockNumber, address referenceCurrencyCt, uint256 referenceCurrencyId, address feeCurrencyCt, uint256 feeCurrencyId); event SetWalletLockTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds); event SetCancelOrderChallengeTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds); event SetSettlementChallengeTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds); event SetWalletSettlementStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction); event SetOperatorSettlementStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction); event SetOperatorSettlementStakeEvent(uint256 fromBlockNumber, int256 stakeAmount, address stakeCurrencyCt, uint256 stakeCurrencyId); event SetFraudStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction); event SetEarliestSettlementBlockNumberEvent(uint256 earliestSettlementBlockNumber); event DisableEarliestSettlementBlockNumberUpdateEvent(); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { updateDelayBlocksByBlockNumber.addEntry(block.number, 0); } // // Public functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set operational mode to Exit /// @dev Once operational mode is set to Exit it may not be set back to Normal function setOperationalModeExit() public onlyEnabledServiceAction(OPERATIONAL_MODE_ACTION) { operationalMode = OperationalMode.Exit; emit SetOperationalModeExitEvent(); } /// @notice Return true if operational mode is Normal function isOperationalModeNormal() public view returns (bool) { return OperationalMode.Normal == operationalMode; } /// @notice Return true if operational mode is Exit function isOperationalModeExit() public view returns (bool) { return OperationalMode.Exit == operationalMode; } /// @notice Get the current value of update delay blocks /// @return The value of update delay blocks function updateDelayBlocks() public view returns (uint256) { return updateDelayBlocksByBlockNumber.currentValue(); } /// @notice Get the count of update delay blocks values /// @return The count of update delay blocks values function updateDelayBlocksCount() public view returns (uint256) { return updateDelayBlocksByBlockNumber.count(); } /// @notice Set the number of update delay blocks /// @param fromBlockNumber Block number from which the update applies /// @param newUpdateDelayBlocks The new update delay blocks value function setUpdateDelayBlocks(uint256 fromBlockNumber, uint256 newUpdateDelayBlocks) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { updateDelayBlocksByBlockNumber.addEntry(fromBlockNumber, newUpdateDelayBlocks); emit SetUpdateDelayBlocksEvent(fromBlockNumber, newUpdateDelayBlocks); } /// @notice Get the current value of confirmation blocks /// @return The value of confirmation blocks function confirmationBlocks() public view returns (uint256) { return confirmationBlocksByBlockNumber.currentValue(); } /// @notice Get the count of confirmation blocks values /// @return The count of confirmation blocks values function confirmationBlocksCount() public view returns (uint256) { return confirmationBlocksByBlockNumber.count(); } /// @notice Set the number of confirmation blocks /// @param fromBlockNumber Block number from which the update applies /// @param newConfirmationBlocks The new confirmation blocks value function setConfirmationBlocks(uint256 fromBlockNumber, uint256 newConfirmationBlocks) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { confirmationBlocksByBlockNumber.addEntry(fromBlockNumber, newConfirmationBlocks); emit SetConfirmationBlocksEvent(fromBlockNumber, newConfirmationBlocks); } /// @notice Get number of trade maker fee block number tiers function tradeMakerFeesCount() public view returns (uint256) { return tradeMakerFeeByBlockNumber.count(); } /// @notice Get trade maker relative fee at given block number, possibly discounted by discount tier value /// @param blockNumber The concerned block number /// @param discountTier The concerned discount tier function tradeMakerFee(uint256 blockNumber, int256 discountTier) public view returns (int256) { return tradeMakerFeeByBlockNumber.discountedValueAt(blockNumber, discountTier); } /// @notice Set trade maker nominal relative fee and discount tiers and values at given block number tier /// @param fromBlockNumber Block number from which the update applies /// @param nominal Nominal relative fee /// @param nominal Discount tier levels /// @param nominal Discount values function setTradeMakerFee(uint256 fromBlockNumber, int256 nominal, int256[] memory discountTiers, int256[] memory discountValues) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { tradeMakerFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues); emit SetTradeMakerFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues); } /// @notice Get number of trade taker fee block number tiers function tradeTakerFeesCount() public view returns (uint256) { return tradeTakerFeeByBlockNumber.count(); } /// @notice Get trade taker relative fee at given block number, possibly discounted by discount tier value /// @param blockNumber The concerned block number /// @param discountTier The concerned discount tier function tradeTakerFee(uint256 blockNumber, int256 discountTier) public view returns (int256) { return tradeTakerFeeByBlockNumber.discountedValueAt(blockNumber, discountTier); } /// @notice Set trade taker nominal relative fee and discount tiers and values at given block number tier /// @param fromBlockNumber Block number from which the update applies /// @param nominal Nominal relative fee /// @param nominal Discount tier levels /// @param nominal Discount values function setTradeTakerFee(uint256 fromBlockNumber, int256 nominal, int256[] memory discountTiers, int256[] memory discountValues) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { tradeTakerFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues); emit SetTradeTakerFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues); } /// @notice Get number of payment fee block number tiers function paymentFeesCount() public view returns (uint256) { return paymentFeeByBlockNumber.count(); } /// @notice Get payment relative fee at given block number, possibly discounted by discount tier value /// @param blockNumber The concerned block number /// @param discountTier The concerned discount tier function paymentFee(uint256 blockNumber, int256 discountTier) public view returns (int256) { return paymentFeeByBlockNumber.discountedValueAt(blockNumber, discountTier); } /// @notice Set payment nominal relative fee and discount tiers and values at given block number tier /// @param fromBlockNumber Block number from which the update applies /// @param nominal Nominal relative fee /// @param nominal Discount tier levels /// @param nominal Discount values function setPaymentFee(uint256 fromBlockNumber, int256 nominal, int256[] memory discountTiers, int256[] memory discountValues) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { paymentFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues); emit SetPaymentFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues); } /// @notice Get number of payment fee block number tiers of given currency /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function currencyPaymentFeesCount(address currencyCt, uint256 currencyId) public view returns (uint256) { return currencyPaymentFeeByBlockNumber[currencyCt][currencyId].count(); } /// @notice Get payment relative fee for given currency at given block number, possibly discounted by /// discount tier value /// @param blockNumber The concerned block number /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param discountTier The concerned discount tier function currencyPaymentFee(uint256 blockNumber, address currencyCt, uint256 currencyId, int256 discountTier) public view returns (int256) { if (0 < currencyPaymentFeeByBlockNumber[currencyCt][currencyId].count()) return currencyPaymentFeeByBlockNumber[currencyCt][currencyId].discountedValueAt( blockNumber, discountTier ); else return paymentFee(blockNumber, discountTier); } /// @notice Set payment nominal relative fee and discount tiers and values for given currency at given /// block number tier /// @param fromBlockNumber Block number from which the update applies /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param nominal Nominal relative fee /// @param nominal Discount tier levels /// @param nominal Discount values function setCurrencyPaymentFee(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal, int256[] memory discountTiers, int256[] memory discountValues) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { currencyPaymentFeeByBlockNumber[currencyCt][currencyId].addDiscountedEntry( fromBlockNumber, nominal, discountTiers, discountValues ); emit SetCurrencyPaymentFeeEvent( fromBlockNumber, currencyCt, currencyId, nominal, discountTiers, discountValues ); } /// @notice Get number of minimum trade maker fee block number tiers function tradeMakerMinimumFeesCount() public view returns (uint256) { return tradeMakerMinimumFeeByBlockNumber.count(); } /// @notice Get trade maker minimum relative fee at given block number /// @param blockNumber The concerned block number function tradeMakerMinimumFee(uint256 blockNumber) public view returns (int256) { return tradeMakerMinimumFeeByBlockNumber.valueAt(blockNumber); } /// @notice Set trade maker minimum relative fee at given block number tier /// @param fromBlockNumber Block number from which the update applies /// @param nominal Minimum relative fee function setTradeMakerMinimumFee(uint256 fromBlockNumber, int256 nominal) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { tradeMakerMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal); emit SetTradeMakerMinimumFeeEvent(fromBlockNumber, nominal); } /// @notice Get number of minimum trade taker fee block number tiers function tradeTakerMinimumFeesCount() public view returns (uint256) { return tradeTakerMinimumFeeByBlockNumber.count(); } /// @notice Get trade taker minimum relative fee at given block number /// @param blockNumber The concerned block number function tradeTakerMinimumFee(uint256 blockNumber) public view returns (int256) { return tradeTakerMinimumFeeByBlockNumber.valueAt(blockNumber); } /// @notice Set trade taker minimum relative fee at given block number tier /// @param fromBlockNumber Block number from which the update applies /// @param nominal Minimum relative fee function setTradeTakerMinimumFee(uint256 fromBlockNumber, int256 nominal) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { tradeTakerMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal); emit SetTradeTakerMinimumFeeEvent(fromBlockNumber, nominal); } /// @notice Get number of minimum payment fee block number tiers function paymentMinimumFeesCount() public view returns (uint256) { return paymentMinimumFeeByBlockNumber.count(); } /// @notice Get payment minimum relative fee at given block number /// @param blockNumber The concerned block number function paymentMinimumFee(uint256 blockNumber) public view returns (int256) { return paymentMinimumFeeByBlockNumber.valueAt(blockNumber); } /// @notice Set payment minimum relative fee at given block number tier /// @param fromBlockNumber Block number from which the update applies /// @param nominal Minimum relative fee function setPaymentMinimumFee(uint256 fromBlockNumber, int256 nominal) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { paymentMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal); emit SetPaymentMinimumFeeEvent(fromBlockNumber, nominal); } /// @notice Get number of minimum payment fee block number tiers for given currency /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function currencyPaymentMinimumFeesCount(address currencyCt, uint256 currencyId) public view returns (uint256) { return currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].count(); } /// @notice Get payment minimum relative fee for given currency at given block number /// @param blockNumber The concerned block number /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function currencyPaymentMinimumFee(uint256 blockNumber, address currencyCt, uint256 currencyId) public view returns (int256) { if (0 < currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].count()) return currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].valueAt(blockNumber); else return paymentMinimumFee(blockNumber); } /// @notice Set payment minimum relative fee for given currency at given block number tier /// @param fromBlockNumber Block number from which the update applies /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param nominal Minimum relative fee function setCurrencyPaymentMinimumFee(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].addEntry(fromBlockNumber, nominal); emit SetCurrencyPaymentMinimumFeeEvent(fromBlockNumber, currencyCt, currencyId, nominal); } /// @notice Get number of fee currencies for the given reference currency /// @param currencyCt The address of the concerned reference currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned reference currency (0 for ETH and ERC20) function feeCurrenciesCount(address currencyCt, uint256 currencyId) public view returns (uint256) { return feeCurrencyByCurrencyBlockNumber.count(MonetaryTypesLib.Currency(currencyCt, currencyId)); } /// @notice Get the fee currency for the given reference currency at given block number /// @param blockNumber The concerned block number /// @param currencyCt The address of the concerned reference currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned reference currency (0 for ETH and ERC20) function feeCurrency(uint256 blockNumber, address currencyCt, uint256 currencyId) public view returns (address ct, uint256 id) { MonetaryTypesLib.Currency storage _feeCurrency = feeCurrencyByCurrencyBlockNumber.currencyAt( MonetaryTypesLib.Currency(currencyCt, currencyId), blockNumber ); ct = _feeCurrency.ct; id = _feeCurrency.id; } /// @notice Set the fee currency for the given reference currency at given block number /// @param fromBlockNumber Block number from which the update applies /// @param referenceCurrencyCt The address of the concerned reference currency contract (address(0) == ETH) /// @param referenceCurrencyId The ID of the concerned reference currency (0 for ETH and ERC20) /// @param feeCurrencyCt The address of the concerned fee currency contract (address(0) == ETH) /// @param feeCurrencyId The ID of the concerned fee currency (0 for ETH and ERC20) function setFeeCurrency(uint256 fromBlockNumber, address referenceCurrencyCt, uint256 referenceCurrencyId, address feeCurrencyCt, uint256 feeCurrencyId) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { feeCurrencyByCurrencyBlockNumber.addEntry( fromBlockNumber, MonetaryTypesLib.Currency(referenceCurrencyCt, referenceCurrencyId), MonetaryTypesLib.Currency(feeCurrencyCt, feeCurrencyId) ); emit SetFeeCurrencyEvent(fromBlockNumber, referenceCurrencyCt, referenceCurrencyId, feeCurrencyCt, feeCurrencyId); } /// @notice Get the current value of wallet lock timeout /// @return The value of wallet lock timeout function walletLockTimeout() public view returns (uint256) { return walletLockTimeoutByBlockNumber.currentValue(); } /// @notice Set timeout of wallet lock /// @param fromBlockNumber Block number from which the update applies /// @param timeoutInSeconds Timeout duration in seconds function setWalletLockTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { walletLockTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds); emit SetWalletLockTimeoutEvent(fromBlockNumber, timeoutInSeconds); } /// @notice Get the current value of cancel order challenge timeout /// @return The value of cancel order challenge timeout function cancelOrderChallengeTimeout() public view returns (uint256) { return cancelOrderChallengeTimeoutByBlockNumber.currentValue(); } /// @notice Set timeout of cancel order challenge /// @param fromBlockNumber Block number from which the update applies /// @param timeoutInSeconds Timeout duration in seconds function setCancelOrderChallengeTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { cancelOrderChallengeTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds); emit SetCancelOrderChallengeTimeoutEvent(fromBlockNumber, timeoutInSeconds); } /// @notice Get the current value of settlement challenge timeout /// @return The value of settlement challenge timeout function settlementChallengeTimeout() public view returns (uint256) { return settlementChallengeTimeoutByBlockNumber.currentValue(); } /// @notice Set timeout of settlement challenges /// @param fromBlockNumber Block number from which the update applies /// @param timeoutInSeconds Timeout duration in seconds function setSettlementChallengeTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { settlementChallengeTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds); emit SetSettlementChallengeTimeoutEvent(fromBlockNumber, timeoutInSeconds); } /// @notice Get the current value of fraud stake fraction /// @return The value of fraud stake fraction function fraudStakeFraction() public view returns (uint256) { return fraudStakeFractionByBlockNumber.currentValue(); } /// @notice Set fraction of security bond that will be gained from successfully challenging /// in fraud challenge /// @param fromBlockNumber Block number from which the update applies /// @param stakeFraction The fraction gained function setFraudStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { fraudStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction); emit SetFraudStakeFractionEvent(fromBlockNumber, stakeFraction); } /// @notice Get the current value of wallet settlement stake fraction /// @return The value of wallet settlement stake fraction function walletSettlementStakeFraction() public view returns (uint256) { return walletSettlementStakeFractionByBlockNumber.currentValue(); } /// @notice Set fraction of security bond that will be gained from successfully challenging /// in settlement challenge triggered by wallet /// @param fromBlockNumber Block number from which the update applies /// @param stakeFraction The fraction gained function setWalletSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { walletSettlementStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction); emit SetWalletSettlementStakeFractionEvent(fromBlockNumber, stakeFraction); } /// @notice Get the current value of operator settlement stake fraction /// @return The value of operator settlement stake fraction function operatorSettlementStakeFraction() public view returns (uint256) { return operatorSettlementStakeFractionByBlockNumber.currentValue(); } /// @notice Set fraction of security bond that will be gained from successfully challenging /// in settlement challenge triggered by operator /// @param fromBlockNumber Block number from which the update applies /// @param stakeFraction The fraction gained function setOperatorSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { operatorSettlementStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction); emit SetOperatorSettlementStakeFractionEvent(fromBlockNumber, stakeFraction); } /// @notice Get the current value of operator settlement stake /// @return The value of operator settlement stake function operatorSettlementStake() public view returns (int256 amount, address currencyCt, uint256 currencyId) { MonetaryTypesLib.Figure storage stake = operatorSettlementStakeByBlockNumber.currentValue(); amount = stake.amount; currencyCt = stake.currency.ct; currencyId = stake.currency.id; } /// @notice Set figure of security bond that will be gained from successfully challenging /// in settlement challenge triggered by operator /// @param fromBlockNumber Block number from which the update applies /// @param stakeAmount The amount gained /// @param stakeCurrencyCt The address of currency gained /// @param stakeCurrencyId The ID of currency gained function setOperatorSettlementStake(uint256 fromBlockNumber, int256 stakeAmount, address stakeCurrencyCt, uint256 stakeCurrencyId) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { MonetaryTypesLib.Figure memory stake = MonetaryTypesLib.Figure(stakeAmount, MonetaryTypesLib.Currency(stakeCurrencyCt, stakeCurrencyId)); operatorSettlementStakeByBlockNumber.addEntry(fromBlockNumber, stake); emit SetOperatorSettlementStakeEvent(fromBlockNumber, stakeAmount, stakeCurrencyCt, stakeCurrencyId); } /// @notice Set the block number of the earliest settlement initiation /// @param _earliestSettlementBlockNumber The block number of the earliest settlement function setEarliestSettlementBlockNumber(uint256 _earliestSettlementBlockNumber) public onlyOperator { require(!earliestSettlementBlockNumberUpdateDisabled, "Earliest settlement block number update disabled [Configuration.sol:715]"); earliestSettlementBlockNumber = _earliestSettlementBlockNumber; emit SetEarliestSettlementBlockNumberEvent(earliestSettlementBlockNumber); } /// @notice Disable further updates to the earliest settlement block number /// @dev This operation can not be undone function disableEarliestSettlementBlockNumberUpdate() public onlyOperator { earliestSettlementBlockNumberUpdateDisabled = true; emit DisableEarliestSettlementBlockNumberUpdateEvent(); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier onlyDelayedBlockNumber(uint256 blockNumber) { require( 0 == updateDelayBlocksByBlockNumber.count() || blockNumber >= block.number + updateDelayBlocksByBlockNumber.currentValue(), "Block number not sufficiently delayed [Configuration.sol:735]" ); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Benefactor * @notice An ownable that has a client fund property */ contract Configurable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- Configuration public configuration; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetConfigurationEvent(Configuration oldConfiguration, Configuration newConfiguration); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the configuration contract /// @param newConfiguration The (address of) Configuration contract instance function setConfiguration(Configuration newConfiguration) public onlyDeployer notNullAddress(address(newConfiguration)) notSameAddresses(address(newConfiguration), address(configuration)) { // Set new configuration Configuration oldConfiguration = configuration; configuration = newConfiguration; // Emit event emit SetConfigurationEvent(oldConfiguration, newConfiguration); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier configurationInitialized() { require(address(configuration) != address(0), "Configuration not initialized [Configurable.sol:52]"); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title ConfigurableOperational * @notice A configurable with modifiers for operational mode state validation */ contract ConfigurableOperational is Configurable { // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier onlyOperationalModeNormal() { require(configuration.isOperationalModeNormal(), "Operational mode is not normal [ConfigurableOperational.sol:22]"); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library */ /** * @title SafeMathUintLib * @dev Math operations with safety checks that throw on error */ library SafeMathUintLib { 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; } // //Clamping functions. // function clamp(uint256 a, uint256 min, uint256 max) public pure returns (uint256) { return (a > max) ? max : ((a < min) ? min : a); } function clampMin(uint256 a, uint256 min) public pure returns (uint256) { return (a < min) ? min : a; } function clampMax(uint256 a, uint256 max) public pure returns (uint256) { return (a > max) ? max : a; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library CurrenciesLib { using SafeMathUintLib for uint256; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Currencies { MonetaryTypesLib.Currency[] currencies; mapping(address => mapping(uint256 => uint256)) indexByCurrency; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function add(Currencies storage self, address currencyCt, uint256 currencyId) internal { // Index is 1-based if (0 == self.indexByCurrency[currencyCt][currencyId]) { self.currencies.push(MonetaryTypesLib.Currency(currencyCt, currencyId)); self.indexByCurrency[currencyCt][currencyId] = self.currencies.length; } } function removeByCurrency(Currencies storage self, address currencyCt, uint256 currencyId) internal { // Index is 1-based uint256 index = self.indexByCurrency[currencyCt][currencyId]; if (0 < index) removeByIndex(self, index - 1); } function removeByIndex(Currencies storage self, uint256 index) internal { require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:51]"); address currencyCt = self.currencies[index].ct; uint256 currencyId = self.currencies[index].id; if (index < self.currencies.length - 1) { self.currencies[index] = self.currencies[self.currencies.length - 1]; self.indexByCurrency[self.currencies[index].ct][self.currencies[index].id] = index + 1; } self.currencies.length--; self.indexByCurrency[currencyCt][currencyId] = 0; } function count(Currencies storage self) internal view returns (uint256) { return self.currencies.length; } function has(Currencies storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return 0 != self.indexByCurrency[currencyCt][currencyId]; } function getByIndex(Currencies storage self, uint256 index) internal view returns (MonetaryTypesLib.Currency memory) { require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:85]"); return self.currencies[index]; } function getByIndices(Currencies storage self, uint256 low, uint256 up) internal view returns (MonetaryTypesLib.Currency[] memory) { require(0 < self.currencies.length, "No currencies found [CurrenciesLib.sol:94]"); require(low <= up, "Bounds parameters mismatch [CurrenciesLib.sol:95]"); up = up.clampMax(self.currencies.length - 1); MonetaryTypesLib.Currency[] memory _currencies = new MonetaryTypesLib.Currency[](up - low + 1); for (uint256 i = low; i <= up; i++) _currencies[i - low] = self.currencies[i]; return _currencies; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library FungibleBalanceLib { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using CurrenciesLib for CurrenciesLib.Currencies; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Record { int256 amount; uint256 blockNumber; } struct Balance { mapping(address => mapping(uint256 => int256)) amountByCurrency; mapping(address => mapping(uint256 => Record[])) recordsByCurrency; CurrenciesLib.Currencies inUseCurrencies; CurrenciesLib.Currencies everUsedCurrencies; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function get(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (int256) { return self.amountByCurrency[currencyCt][currencyId]; } function getByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (int256) { (int256 amount,) = recordByBlockNumber(self, currencyCt, currencyId, blockNumber); return amount; } function set(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = amount; self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function add(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function sub(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function transfer(Balance storage _from, Balance storage _to, int256 amount, address currencyCt, uint256 currencyId) internal { sub(_from, amount, currencyCt, currencyId); add(_to, amount, currencyCt, currencyId); } function add_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add_nn(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function sub_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub_nn(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function transfer_nn(Balance storage _from, Balance storage _to, int256 amount, address currencyCt, uint256 currencyId) internal { sub_nn(_from, amount, currencyCt, currencyId); add_nn(_to, amount, currencyCt, currencyId); } function recordsCount(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.recordsByCurrency[currencyCt][currencyId].length; } function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (int256, uint256) { uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber); return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (0, 0); } function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index) internal view returns (int256, uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return (0, 0); index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1); Record storage record = self.recordsByCurrency[currencyCt][currencyId][index]; return (record.amount, record.blockNumber); } function lastRecord(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (int256, uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return (0, 0); Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1]; return (record.amount, record.blockNumber); } function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return self.inUseCurrencies.has(currencyCt, currencyId); } function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return self.everUsedCurrencies.has(currencyCt, currencyId); } function updateCurrencies(Balance storage self, address currencyCt, uint256 currencyId) internal { if (0 == self.amountByCurrency[currencyCt][currencyId] && self.inUseCurrencies.has(currencyCt, currencyId)) self.inUseCurrencies.removeByCurrency(currencyCt, currencyId); else if (!self.inUseCurrencies.has(currencyCt, currencyId)) { self.inUseCurrencies.add(currencyCt, currencyId); self.everUsedCurrencies.add(currencyCt, currencyId); } } function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return 0; for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--) if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber) return i; return 0; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library NonFungibleBalanceLib { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using CurrenciesLib for CurrenciesLib.Currencies; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Record { int256[] ids; uint256 blockNumber; } struct Balance { mapping(address => mapping(uint256 => int256[])) idsByCurrency; mapping(address => mapping(uint256 => mapping(int256 => uint256))) idIndexById; mapping(address => mapping(uint256 => Record[])) recordsByCurrency; CurrenciesLib.Currencies inUseCurrencies; CurrenciesLib.Currencies everUsedCurrencies; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function get(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (int256[] memory) { return self.idsByCurrency[currencyCt][currencyId]; } function getByIndices(Balance storage self, address currencyCt, uint256 currencyId, uint256 indexLow, uint256 indexUp) internal view returns (int256[] memory) { if (0 == self.idsByCurrency[currencyCt][currencyId].length) return new int256[](0); indexUp = indexUp.clampMax(self.idsByCurrency[currencyCt][currencyId].length - 1); int256[] memory idsByCurrency = new int256[](indexUp - indexLow + 1); for (uint256 i = indexLow; i < indexUp; i++) idsByCurrency[i - indexLow] = self.idsByCurrency[currencyCt][currencyId][i]; return idsByCurrency; } function idsCount(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.idsByCurrency[currencyCt][currencyId].length; } function hasId(Balance storage self, int256 id, address currencyCt, uint256 currencyId) internal view returns (bool) { return 0 < self.idIndexById[currencyCt][currencyId][id]; } function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (int256[] memory, uint256) { uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber); return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (new int256[](0), 0); } function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index) internal view returns (int256[] memory, uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return (new int256[](0), 0); index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1); Record storage record = self.recordsByCurrency[currencyCt][currencyId][index]; return (record.ids, record.blockNumber); } function lastRecord(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (int256[] memory, uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return (new int256[](0), 0); Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1]; return (record.ids, record.blockNumber); } function recordsCount(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.recordsByCurrency[currencyCt][currencyId].length; } function set(Balance storage self, int256 id, address currencyCt, uint256 currencyId) internal { int256[] memory ids = new int256[](1); ids[0] = id; set(self, ids, currencyCt, currencyId); } function set(Balance storage self, int256[] memory ids, address currencyCt, uint256 currencyId) internal { uint256 i; for (i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++) self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = 0; self.idsByCurrency[currencyCt][currencyId] = ids; for (i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++) self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = i + 1; self.recordsByCurrency[currencyCt][currencyId].push( Record(self.idsByCurrency[currencyCt][currencyId], block.number) ); updateInUseCurrencies(self, currencyCt, currencyId); } function reset(Balance storage self, address currencyCt, uint256 currencyId) internal { for (uint256 i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++) self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = 0; self.idsByCurrency[currencyCt][currencyId].length = 0; self.recordsByCurrency[currencyCt][currencyId].push( Record(self.idsByCurrency[currencyCt][currencyId], block.number) ); updateInUseCurrencies(self, currencyCt, currencyId); } function add(Balance storage self, int256 id, address currencyCt, uint256 currencyId) internal returns (bool) { if (0 < self.idIndexById[currencyCt][currencyId][id]) return false; self.idsByCurrency[currencyCt][currencyId].push(id); self.idIndexById[currencyCt][currencyId][id] = self.idsByCurrency[currencyCt][currencyId].length; self.recordsByCurrency[currencyCt][currencyId].push( Record(self.idsByCurrency[currencyCt][currencyId], block.number) ); updateInUseCurrencies(self, currencyCt, currencyId); return true; } function sub(Balance storage self, int256 id, address currencyCt, uint256 currencyId) internal returns (bool) { uint256 index = self.idIndexById[currencyCt][currencyId][id]; if (0 == index) return false; if (index < self.idsByCurrency[currencyCt][currencyId].length) { self.idsByCurrency[currencyCt][currencyId][index - 1] = self.idsByCurrency[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId].length - 1]; self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][index - 1]] = index; } self.idsByCurrency[currencyCt][currencyId].length--; self.idIndexById[currencyCt][currencyId][id] = 0; self.recordsByCurrency[currencyCt][currencyId].push( Record(self.idsByCurrency[currencyCt][currencyId], block.number) ); updateInUseCurrencies(self, currencyCt, currencyId); return true; } function transfer(Balance storage _from, Balance storage _to, int256 id, address currencyCt, uint256 currencyId) internal returns (bool) { return sub(_from, id, currencyCt, currencyId) && add(_to, id, currencyCt, currencyId); } function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return self.inUseCurrencies.has(currencyCt, currencyId); } function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return self.everUsedCurrencies.has(currencyCt, currencyId); } function updateInUseCurrencies(Balance storage self, address currencyCt, uint256 currencyId) internal { if (0 == self.idsByCurrency[currencyCt][currencyId].length && self.inUseCurrencies.has(currencyCt, currencyId)) self.inUseCurrencies.removeByCurrency(currencyCt, currencyId); else if (!self.inUseCurrencies.has(currencyCt, currencyId)) { self.inUseCurrencies.add(currencyCt, currencyId); self.everUsedCurrencies.add(currencyCt, currencyId); } } function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return 0; for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--) if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber) return i; return 0; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Balance tracker * @notice An ownable to track balances of generic types */ contract BalanceTracker is Ownable, Servable { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using FungibleBalanceLib for FungibleBalanceLib.Balance; using NonFungibleBalanceLib for NonFungibleBalanceLib.Balance; // // Constants // ----------------------------------------------------------------------------------------------------------------- string constant public DEPOSITED_BALANCE_TYPE = "deposited"; string constant public SETTLED_BALANCE_TYPE = "settled"; string constant public STAGED_BALANCE_TYPE = "staged"; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Wallet { mapping(bytes32 => FungibleBalanceLib.Balance) fungibleBalanceByType; mapping(bytes32 => NonFungibleBalanceLib.Balance) nonFungibleBalanceByType; } // // Variables // ----------------------------------------------------------------------------------------------------------------- bytes32 public depositedBalanceType; bytes32 public settledBalanceType; bytes32 public stagedBalanceType; bytes32[] public _allBalanceTypes; bytes32[] public _activeBalanceTypes; bytes32[] public trackedBalanceTypes; mapping(bytes32 => bool) public trackedBalanceTypeMap; mapping(address => Wallet) private walletMap; address[] public trackedWallets; mapping(address => uint256) public trackedWalletIndexByWallet; // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { depositedBalanceType = keccak256(abi.encodePacked(DEPOSITED_BALANCE_TYPE)); settledBalanceType = keccak256(abi.encodePacked(SETTLED_BALANCE_TYPE)); stagedBalanceType = keccak256(abi.encodePacked(STAGED_BALANCE_TYPE)); _allBalanceTypes.push(settledBalanceType); _allBalanceTypes.push(depositedBalanceType); _allBalanceTypes.push(stagedBalanceType); _activeBalanceTypes.push(settledBalanceType); _activeBalanceTypes.push(depositedBalanceType); } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Get the fungible balance (amount) of the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The stored balance function get(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (int256) { return walletMap[wallet].fungibleBalanceByType[_type].get(currencyCt, currencyId); } /// @notice Get the non-fungible balance (IDs) of the given wallet, type, currency and index range /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param indexLow The lower index of IDs /// @param indexUp The upper index of IDs /// @return The stored balance function getByIndices(address wallet, bytes32 _type, address currencyCt, uint256 currencyId, uint256 indexLow, uint256 indexUp) public view returns (int256[] memory) { return walletMap[wallet].nonFungibleBalanceByType[_type].getByIndices( currencyCt, currencyId, indexLow, indexUp ); } /// @notice Get all the non-fungible balance (IDs) of the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The stored balance function getAll(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (int256[] memory) { return walletMap[wallet].nonFungibleBalanceByType[_type].get( currencyCt, currencyId ); } /// @notice Get the count of non-fungible IDs of the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The count of IDs function idsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (uint256) { return walletMap[wallet].nonFungibleBalanceByType[_type].idsCount( currencyCt, currencyId ); } /// @notice Gauge whether the ID is included in the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param id The ID of the concerned unit /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return true if ID is included, else false function hasId(address wallet, bytes32 _type, int256 id, address currencyCt, uint256 currencyId) public view returns (bool) { return walletMap[wallet].nonFungibleBalanceByType[_type].hasId( id, currencyCt, currencyId ); } /// @notice Set the balance of the given wallet, type and currency to the given value /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param value The value (amount of fungible, id of non-fungible) to set /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param fungible True if setting fungible balance, else false function set(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId, bool fungible) public onlyActiveService { // Update the balance if (fungible) walletMap[wallet].fungibleBalanceByType[_type].set( value, currencyCt, currencyId ); else walletMap[wallet].nonFungibleBalanceByType[_type].set( value, currencyCt, currencyId ); // Update balance type hashes _updateTrackedBalanceTypes(_type); // Update tracked wallets _updateTrackedWallets(wallet); } /// @notice Set the non-fungible balance IDs of the given wallet, type and currency to the given value /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param ids The ids of non-fungible) to set /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function setIds(address wallet, bytes32 _type, int256[] memory ids, address currencyCt, uint256 currencyId) public onlyActiveService { // Update the balance walletMap[wallet].nonFungibleBalanceByType[_type].set( ids, currencyCt, currencyId ); // Update balance type hashes _updateTrackedBalanceTypes(_type); // Update tracked wallets _updateTrackedWallets(wallet); } /// @notice Add the given value to the balance of the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param value The value (amount of fungible, id of non-fungible) to add /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param fungible True if adding fungible balance, else false function add(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId, bool fungible) public onlyActiveService { // Update the balance if (fungible) walletMap[wallet].fungibleBalanceByType[_type].add( value, currencyCt, currencyId ); else walletMap[wallet].nonFungibleBalanceByType[_type].add( value, currencyCt, currencyId ); // Update balance type hashes _updateTrackedBalanceTypes(_type); // Update tracked wallets _updateTrackedWallets(wallet); } /// @notice Subtract the given value from the balance of the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param value The value (amount of fungible, id of non-fungible) to subtract /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param fungible True if subtracting fungible balance, else false function sub(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId, bool fungible) public onlyActiveService { // Update the balance if (fungible) walletMap[wallet].fungibleBalanceByType[_type].sub( value, currencyCt, currencyId ); else walletMap[wallet].nonFungibleBalanceByType[_type].sub( value, currencyCt, currencyId ); // Update tracked wallets _updateTrackedWallets(wallet); } /// @notice Gauge whether this tracker has in-use data for the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return true if data is stored, else false function hasInUseCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (bool) { return walletMap[wallet].fungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId) || walletMap[wallet].nonFungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId); } /// @notice Gauge whether this tracker has ever-used data for the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return true if data is stored, else false function hasEverUsedCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (bool) { return walletMap[wallet].fungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId) || walletMap[wallet].nonFungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId); } /// @notice Get the count of fungible balance records for the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The count of balance log entries function fungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (uint256) { return walletMap[wallet].fungibleBalanceByType[_type].recordsCount(currencyCt, currencyId); } /// @notice Get the fungible balance record for the given wallet, type, currency /// log entry index /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param index The concerned record index /// @return The balance record function fungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId, uint256 index) public view returns (int256 amount, uint256 blockNumber) { return walletMap[wallet].fungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index); } /// @notice Get the non-fungible balance record for the given wallet, type, currency /// block number /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param _blockNumber The concerned block number /// @return The balance record function fungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId, uint256 _blockNumber) public view returns (int256 amount, uint256 blockNumber) { return walletMap[wallet].fungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber); } /// @notice Get the last (most recent) non-fungible balance record for the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The last log entry function lastFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (int256 amount, uint256 blockNumber) { return walletMap[wallet].fungibleBalanceByType[_type].lastRecord(currencyCt, currencyId); } /// @notice Get the count of non-fungible balance records for the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The count of balance log entries function nonFungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (uint256) { return walletMap[wallet].nonFungibleBalanceByType[_type].recordsCount(currencyCt, currencyId); } /// @notice Get the non-fungible balance record for the given wallet, type, currency /// and record index /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param index The concerned record index /// @return The balance record function nonFungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId, uint256 index) public view returns (int256[] memory ids, uint256 blockNumber) { return walletMap[wallet].nonFungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index); } /// @notice Get the non-fungible balance record for the given wallet, type, currency /// and block number /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param _blockNumber The concerned block number /// @return The balance record function nonFungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId, uint256 _blockNumber) public view returns (int256[] memory ids, uint256 blockNumber) { return walletMap[wallet].nonFungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber); } /// @notice Get the last (most recent) non-fungible balance record for the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The last log entry function lastNonFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (int256[] memory ids, uint256 blockNumber) { return walletMap[wallet].nonFungibleBalanceByType[_type].lastRecord(currencyCt, currencyId); } /// @notice Get the count of tracked balance types /// @return The count of tracked balance types function trackedBalanceTypesCount() public view returns (uint256) { return trackedBalanceTypes.length; } /// @notice Get the count of tracked wallets /// @return The count of tracked wallets function trackedWalletsCount() public view returns (uint256) { return trackedWallets.length; } /// @notice Get the default full set of balance types /// @return The set of all balance types function allBalanceTypes() public view returns (bytes32[] memory) { return _allBalanceTypes; } /// @notice Get the default set of active balance types /// @return The set of active balance types function activeBalanceTypes() public view returns (bytes32[] memory) { return _activeBalanceTypes; } /// @notice Get the subset of tracked wallets in the given index range /// @param low The lower index /// @param up The upper index /// @return The subset of tracked wallets function trackedWalletsByIndices(uint256 low, uint256 up) public view returns (address[] memory) { require(0 < trackedWallets.length, "No tracked wallets found [BalanceTracker.sol:473]"); require(low <= up, "Bounds parameters mismatch [BalanceTracker.sol:474]"); up = up.clampMax(trackedWallets.length - 1); address[] memory _trackedWallets = new address[](up - low + 1); for (uint256 i = low; i <= up; i++) _trackedWallets[i - low] = trackedWallets[i]; return _trackedWallets; } // // Private functions // ----------------------------------------------------------------------------------------------------------------- function _updateTrackedBalanceTypes(bytes32 _type) private { if (!trackedBalanceTypeMap[_type]) { trackedBalanceTypeMap[_type] = true; trackedBalanceTypes.push(_type); } } function _updateTrackedWallets(address wallet) private { if (0 == trackedWalletIndexByWallet[wallet]) { trackedWallets.push(wallet); trackedWalletIndexByWallet[wallet] = trackedWallets.length; } } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title BalanceTrackable * @notice An ownable that has a balance tracker property */ contract BalanceTrackable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- BalanceTracker public balanceTracker; bool public balanceTrackerFrozen; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetBalanceTrackerEvent(BalanceTracker oldBalanceTracker, BalanceTracker newBalanceTracker); event FreezeBalanceTrackerEvent(); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the balance tracker contract /// @param newBalanceTracker The (address of) BalanceTracker contract instance function setBalanceTracker(BalanceTracker newBalanceTracker) public onlyDeployer notNullAddress(address(newBalanceTracker)) notSameAddresses(address(newBalanceTracker), address(balanceTracker)) { // Require that this contract has not been frozen require(!balanceTrackerFrozen, "Balance tracker frozen [BalanceTrackable.sol:43]"); // Update fields BalanceTracker oldBalanceTracker = balanceTracker; balanceTracker = newBalanceTracker; // Emit event emit SetBalanceTrackerEvent(oldBalanceTracker, newBalanceTracker); } /// @notice Freeze the balance tracker from further updates /// @dev This operation can not be undone function freezeBalanceTracker() public onlyDeployer { balanceTrackerFrozen = true; // Emit event emit FreezeBalanceTrackerEvent(); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier balanceTrackerInitialized() { require(address(balanceTracker) != address(0), "Balance tracker not initialized [BalanceTrackable.sol:69]"); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title AuthorizableServable * @notice A servable that may be authorized and unauthorized */ contract AuthorizableServable is Servable { // // Variables // ----------------------------------------------------------------------------------------------------------------- bool public initialServiceAuthorizationDisabled; mapping(address => bool) public initialServiceAuthorizedMap; mapping(address => mapping(address => bool)) public initialServiceWalletUnauthorizedMap; mapping(address => mapping(address => bool)) public serviceWalletAuthorizedMap; mapping(address => mapping(bytes32 => mapping(address => bool))) public serviceActionWalletAuthorizedMap; mapping(address => mapping(bytes32 => mapping(address => bool))) public serviceActionWalletTouchedMap; mapping(address => mapping(address => bytes32[])) public serviceWalletActionList; // // Events // ----------------------------------------------------------------------------------------------------------------- event AuthorizeInitialServiceEvent(address wallet, address service); event AuthorizeRegisteredServiceEvent(address wallet, address service); event AuthorizeRegisteredServiceActionEvent(address wallet, address service, string action); event UnauthorizeRegisteredServiceEvent(address wallet, address service); event UnauthorizeRegisteredServiceActionEvent(address wallet, address service, string action); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Add service to initial whitelist of services /// @dev The service must be registered already /// @param service The address of the concerned registered service function authorizeInitialService(address service) public onlyDeployer notNullOrThisAddress(service) { require(!initialServiceAuthorizationDisabled); require(msg.sender != service); // Ensure service is registered require(registeredServicesMap[service].registered); // Enable all actions for given wallet initialServiceAuthorizedMap[service] = true; // Emit event emit AuthorizeInitialServiceEvent(msg.sender, service); } /// @notice Disable further initial authorization of services /// @dev This operation can not be undone function disableInitialServiceAuthorization() public onlyDeployer { initialServiceAuthorizationDisabled = true; } /// @notice Authorize the given registered service by enabling all of actions /// @dev The service must be registered already /// @param service The address of the concerned registered service function authorizeRegisteredService(address service) public notNullOrThisAddress(service) { require(msg.sender != service); // Ensure service is registered require(registeredServicesMap[service].registered); // Ensure service is not initial. Initial services are not authorized per action. require(!initialServiceAuthorizedMap[service]); // Enable all actions for given wallet serviceWalletAuthorizedMap[service][msg.sender] = true; // Emit event emit AuthorizeRegisteredServiceEvent(msg.sender, service); } /// @notice Unauthorize the given registered service by enabling all of actions /// @dev The service must be registered already /// @param service The address of the concerned registered service function unauthorizeRegisteredService(address service) public notNullOrThisAddress(service) { require(msg.sender != service); // Ensure service is registered require(registeredServicesMap[service].registered); // If initial service then disable it if (initialServiceAuthorizedMap[service]) initialServiceWalletUnauthorizedMap[service][msg.sender] = true; // Else disable all actions for given wallet else { serviceWalletAuthorizedMap[service][msg.sender] = false; for (uint256 i = 0; i < serviceWalletActionList[service][msg.sender].length; i++) serviceActionWalletAuthorizedMap[service][serviceWalletActionList[service][msg.sender][i]][msg.sender] = true; } // Emit event emit UnauthorizeRegisteredServiceEvent(msg.sender, service); } /// @notice Gauge whether the given service is authorized for the given wallet /// @param service The address of the concerned registered service /// @param wallet The address of the concerned wallet /// @return true if service is authorized for the given wallet, else false function isAuthorizedRegisteredService(address service, address wallet) public view returns (bool) { return isRegisteredActiveService(service) && (isInitialServiceAuthorizedForWallet(service, wallet) || serviceWalletAuthorizedMap[service][wallet]); } /// @notice Authorize the given registered service action /// @dev The service must be registered already /// @param service The address of the concerned registered service /// @param action The concerned service action function authorizeRegisteredServiceAction(address service, string memory action) public notNullOrThisAddress(service) { require(msg.sender != service); bytes32 actionHash = hashString(action); // Ensure service action is registered require(registeredServicesMap[service].registered && registeredServicesMap[service].actionsEnabledMap[actionHash]); // Ensure service is not initial require(!initialServiceAuthorizedMap[service]); // Enable service action for given wallet serviceWalletAuthorizedMap[service][msg.sender] = false; serviceActionWalletAuthorizedMap[service][actionHash][msg.sender] = true; if (!serviceActionWalletTouchedMap[service][actionHash][msg.sender]) { serviceActionWalletTouchedMap[service][actionHash][msg.sender] = true; serviceWalletActionList[service][msg.sender].push(actionHash); } // Emit event emit AuthorizeRegisteredServiceActionEvent(msg.sender, service, action); } /// @notice Unauthorize the given registered service action /// @dev The service must be registered already /// @param service The address of the concerned registered service /// @param action The concerned service action function unauthorizeRegisteredServiceAction(address service, string memory action) public notNullOrThisAddress(service) { require(msg.sender != service); bytes32 actionHash = hashString(action); // Ensure service is registered and action enabled require(registeredServicesMap[service].registered && registeredServicesMap[service].actionsEnabledMap[actionHash]); // Ensure service is not initial as it can not be unauthorized per action require(!initialServiceAuthorizedMap[service]); // Disable service action for given wallet serviceActionWalletAuthorizedMap[service][actionHash][msg.sender] = false; // Emit event emit UnauthorizeRegisteredServiceActionEvent(msg.sender, service, action); } /// @notice Gauge whether the given service action is authorized for the given wallet /// @param service The address of the concerned registered service /// @param action The concerned service action /// @param wallet The address of the concerned wallet /// @return true if service action is authorized for the given wallet, else false function isAuthorizedRegisteredServiceAction(address service, string memory action, address wallet) public view returns (bool) { bytes32 actionHash = hashString(action); return isEnabledServiceAction(service, action) && ( isInitialServiceAuthorizedForWallet(service, wallet) || serviceWalletAuthorizedMap[service][wallet] || serviceActionWalletAuthorizedMap[service][actionHash][wallet] ); } function isInitialServiceAuthorizedForWallet(address service, address wallet) private view returns (bool) { return initialServiceAuthorizedMap[service] ? !initialServiceWalletUnauthorizedMap[service][wallet] : false; } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier onlyAuthorizedService(address wallet) { require(isAuthorizedRegisteredService(msg.sender, wallet)); _; } modifier onlyAuthorizedServiceAction(string memory action, address wallet) { require(isAuthorizedRegisteredServiceAction(msg.sender, action, wallet)); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Wallet locker * @notice An ownable to lock and unlock wallets' balance holdings of specific currency(ies) */ contract WalletLocker is Ownable, Configurable, AuthorizableServable { using SafeMathUintLib for uint256; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct FungibleLock { address locker; address currencyCt; uint256 currencyId; int256 amount; uint256 visibleTime; uint256 unlockTime; } struct NonFungibleLock { address locker; address currencyCt; uint256 currencyId; int256[] ids; uint256 visibleTime; uint256 unlockTime; } // // Variables // ----------------------------------------------------------------------------------------------------------------- mapping(address => FungibleLock[]) public walletFungibleLocks; mapping(address => mapping(address => mapping(uint256 => mapping(address => uint256)))) public lockedCurrencyLockerFungibleLockIndex; mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyFungibleLockCount; mapping(address => NonFungibleLock[]) public walletNonFungibleLocks; mapping(address => mapping(address => mapping(uint256 => mapping(address => uint256)))) public lockedCurrencyLockerNonFungibleLockIndex; mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyNonFungibleLockCount; // // Events // ----------------------------------------------------------------------------------------------------------------- event LockFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256 amount, address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds); event LockNonFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256[] ids, address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds); event UnlockFungibleEvent(address lockedWallet, address lockerWallet, int256 amount, address currencyCt, uint256 currencyId); event UnlockFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256 amount, address currencyCt, uint256 currencyId); event UnlockNonFungibleEvent(address lockedWallet, address lockerWallet, int256[] ids, address currencyCt, uint256 currencyId); event UnlockNonFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256[] ids, address currencyCt, uint256 currencyId); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Lock the given locked wallet's fungible amount of currency on behalf of the given locker wallet /// @param lockedWallet The address of wallet that will be locked /// @param lockerWallet The address of wallet that locks /// @param amount The amount to be locked /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param visibleTimeoutInSeconds The number of seconds until the locked amount is visible, a.o. for seizure function lockFungibleByProxy(address lockedWallet, address lockerWallet, int256 amount, address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds) public onlyAuthorizedService(lockedWallet) { // Require that locked and locker wallets are not identical require(lockedWallet != lockerWallet); // Get index of lock uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockedWallet]; // Require that there is no existing conflicting lock require( (0 == lockIndex) || (block.timestamp >= walletFungibleLocks[lockedWallet][lockIndex - 1].unlockTime) ); // Add lock object for this triplet of locked wallet, currency and locker wallet if it does not exist if (0 == lockIndex) { lockIndex = ++(walletFungibleLocks[lockedWallet].length); lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = lockIndex; walletCurrencyFungibleLockCount[lockedWallet][currencyCt][currencyId]++; } // Update lock parameters walletFungibleLocks[lockedWallet][lockIndex - 1].locker = lockerWallet; walletFungibleLocks[lockedWallet][lockIndex - 1].amount = amount; walletFungibleLocks[lockedWallet][lockIndex - 1].currencyCt = currencyCt; walletFungibleLocks[lockedWallet][lockIndex - 1].currencyId = currencyId; walletFungibleLocks[lockedWallet][lockIndex - 1].visibleTime = block.timestamp.add(visibleTimeoutInSeconds); walletFungibleLocks[lockedWallet][lockIndex - 1].unlockTime = block.timestamp.add(configuration.walletLockTimeout()); // Emit event emit LockFungibleByProxyEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId, visibleTimeoutInSeconds); } /// @notice Lock the given locked wallet's non-fungible IDs of currency on behalf of the given locker wallet /// @param lockedWallet The address of wallet that will be locked /// @param lockerWallet The address of wallet that locks /// @param ids The IDs to be locked /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param visibleTimeoutInSeconds The number of seconds until the locked ids are visible, a.o. for seizure function lockNonFungibleByProxy(address lockedWallet, address lockerWallet, int256[] memory ids, address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds) public onlyAuthorizedService(lockedWallet) { // Require that locked and locker wallets are not identical require(lockedWallet != lockerWallet); // Get index of lock uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockedWallet]; // Require that there is no existing conflicting lock require( (0 == lockIndex) || (block.timestamp >= walletNonFungibleLocks[lockedWallet][lockIndex - 1].unlockTime) ); // Add lock object for this triplet of locked wallet, currency and locker wallet if it does not exist if (0 == lockIndex) { lockIndex = ++(walletNonFungibleLocks[lockedWallet].length); lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = lockIndex; walletCurrencyNonFungibleLockCount[lockedWallet][currencyCt][currencyId]++; } // Update lock parameters walletNonFungibleLocks[lockedWallet][lockIndex - 1].locker = lockerWallet; walletNonFungibleLocks[lockedWallet][lockIndex - 1].ids = ids; walletNonFungibleLocks[lockedWallet][lockIndex - 1].currencyCt = currencyCt; walletNonFungibleLocks[lockedWallet][lockIndex - 1].currencyId = currencyId; walletNonFungibleLocks[lockedWallet][lockIndex - 1].visibleTime = block.timestamp.add(visibleTimeoutInSeconds); walletNonFungibleLocks[lockedWallet][lockIndex - 1].unlockTime = block.timestamp.add(configuration.walletLockTimeout()); // Emit event emit LockNonFungibleByProxyEvent(lockedWallet, lockerWallet, ids, currencyCt, currencyId, visibleTimeoutInSeconds); } /// @notice Unlock the given locked wallet's fungible amount of currency previously /// locked by the given locker wallet /// @param lockedWallet The address of the locked wallet /// @param lockerWallet The address of the locker wallet /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function unlockFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId) public { // Get index of lock uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet]; // Return if no lock exists if (0 == lockIndex) return; // Require that unlock timeout has expired require( block.timestamp >= walletFungibleLocks[lockedWallet][lockIndex - 1].unlockTime ); // Unlock int256 amount = _unlockFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex); // Emit event emit UnlockFungibleEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId); } /// @notice Unlock by proxy the given locked wallet's fungible amount of currency previously /// locked by the given locker wallet /// @param lockedWallet The address of the locked wallet /// @param lockerWallet The address of the locker wallet /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function unlockFungibleByProxy(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId) public onlyAuthorizedService(lockedWallet) { // Get index of lock uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet]; // Return if no lock exists if (0 == lockIndex) return; // Unlock int256 amount = _unlockFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex); // Emit event emit UnlockFungibleByProxyEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId); } /// @notice Unlock the given locked wallet's non-fungible IDs of currency previously /// locked by the given locker wallet /// @param lockedWallet The address of the locked wallet /// @param lockerWallet The address of the locker wallet /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function unlockNonFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId) public { // Get index of lock uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet]; // Return if no lock exists if (0 == lockIndex) return; // Require that unlock timeout has expired require( block.timestamp >= walletNonFungibleLocks[lockedWallet][lockIndex - 1].unlockTime ); // Unlock int256[] memory ids = _unlockNonFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex); // Emit event emit UnlockNonFungibleEvent(lockedWallet, lockerWallet, ids, currencyCt, currencyId); } /// @notice Unlock by proxy the given locked wallet's non-fungible IDs of currency previously /// locked by the given locker wallet /// @param lockedWallet The address of the locked wallet /// @param lockerWallet The address of the locker wallet /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function unlockNonFungibleByProxy(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId) public onlyAuthorizedService(lockedWallet) { // Get index of lock uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet]; // Return if no lock exists if (0 == lockIndex) return; // Unlock int256[] memory ids = _unlockNonFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex); // Emit event emit UnlockNonFungibleByProxyEvent(lockedWallet, lockerWallet, ids, currencyCt, currencyId); } /// @notice Get the number of fungible locks for the given wallet /// @param wallet The address of the locked wallet /// @return The number of fungible locks function fungibleLocksCount(address wallet) public view returns (uint256) { return walletFungibleLocks[wallet].length; } /// @notice Get the number of non-fungible locks for the given wallet /// @param wallet The address of the locked wallet /// @return The number of non-fungible locks function nonFungibleLocksCount(address wallet) public view returns (uint256) { return walletNonFungibleLocks[wallet].length; } /// @notice Get the fungible amount of the given currency held by locked wallet that is /// locked by locker wallet /// @param lockedWallet The address of the locked wallet /// @param lockerWallet The address of the locker wallet /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function lockedAmount(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId) public view returns (int256) { uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet]; if (0 == lockIndex || block.timestamp < walletFungibleLocks[lockedWallet][lockIndex - 1].visibleTime) return 0; return walletFungibleLocks[lockedWallet][lockIndex - 1].amount; } /// @notice Get the count of non-fungible IDs of the given currency held by locked wallet that is /// locked by locker wallet /// @param lockedWallet The address of the locked wallet /// @param lockerWallet The address of the locker wallet /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function lockedIdsCount(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId) public view returns (uint256) { uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet]; if (0 == lockIndex || block.timestamp < walletNonFungibleLocks[lockedWallet][lockIndex - 1].visibleTime) return 0; return walletNonFungibleLocks[lockedWallet][lockIndex - 1].ids.length; } /// @notice Get the set of non-fungible IDs of the given currency held by locked wallet that is /// locked by locker wallet and whose indices are in the given range of indices /// @param lockedWallet The address of the locked wallet /// @param lockerWallet The address of the locker wallet /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param low The lower ID index /// @param up The upper ID index function lockedIdsByIndices(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId, uint256 low, uint256 up) public view returns (int256[] memory) { uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet]; if (0 == lockIndex || block.timestamp < walletNonFungibleLocks[lockedWallet][lockIndex - 1].visibleTime) return new int256[](0); NonFungibleLock storage lock = walletNonFungibleLocks[lockedWallet][lockIndex - 1]; if (0 == lock.ids.length) return new int256[](0); up = up.clampMax(lock.ids.length - 1); int256[] memory _ids = new int256[](up - low + 1); for (uint256 i = low; i <= up; i++) _ids[i - low] = lock.ids[i]; return _ids; } /// @notice Gauge whether the given wallet is locked /// @param wallet The address of the concerned wallet /// @return true if wallet is locked, else false function isLocked(address wallet) public view returns (bool) { return 0 < walletFungibleLocks[wallet].length || 0 < walletNonFungibleLocks[wallet].length; } /// @notice Gauge whether the given wallet and currency is locked /// @param wallet The address of the concerned wallet /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return true if wallet/currency pair is locked, else false function isLocked(address wallet, address currencyCt, uint256 currencyId) public view returns (bool) { return 0 < walletCurrencyFungibleLockCount[wallet][currencyCt][currencyId] || 0 < walletCurrencyNonFungibleLockCount[wallet][currencyCt][currencyId]; } /// @notice Gauge whether the given locked wallet and currency is locked by the given locker wallet /// @param lockedWallet The address of the concerned locked wallet /// @param lockerWallet The address of the concerned locker wallet /// @return true if lockedWallet is locked by lockerWallet, else false function isLocked(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId) public view returns (bool) { return 0 < lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] || 0 < lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet]; } // // // Private functions // ----------------------------------------------------------------------------------------------------------------- function _unlockFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId, uint256 lockIndex) private returns (int256) { int256 amount = walletFungibleLocks[lockedWallet][lockIndex - 1].amount; if (lockIndex < walletFungibleLocks[lockedWallet].length) { walletFungibleLocks[lockedWallet][lockIndex - 1] = walletFungibleLocks[lockedWallet][walletFungibleLocks[lockedWallet].length - 1]; lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][walletFungibleLocks[lockedWallet][lockIndex - 1].locker] = lockIndex; } walletFungibleLocks[lockedWallet].length--; lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = 0; walletCurrencyFungibleLockCount[lockedWallet][currencyCt][currencyId]--; return amount; } function _unlockNonFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId, uint256 lockIndex) private returns (int256[] memory) { int256[] memory ids = walletNonFungibleLocks[lockedWallet][lockIndex - 1].ids; if (lockIndex < walletNonFungibleLocks[lockedWallet].length) { walletNonFungibleLocks[lockedWallet][lockIndex - 1] = walletNonFungibleLocks[lockedWallet][walletNonFungibleLocks[lockedWallet].length - 1]; lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][walletNonFungibleLocks[lockedWallet][lockIndex - 1].locker] = lockIndex; } walletNonFungibleLocks[lockedWallet].length--; lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = 0; walletCurrencyNonFungibleLockCount[lockedWallet][currencyCt][currencyId]--; return ids; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title WalletLockable * @notice An ownable that has a wallet locker property */ contract WalletLockable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- WalletLocker public walletLocker; bool public walletLockerFrozen; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetWalletLockerEvent(WalletLocker oldWalletLocker, WalletLocker newWalletLocker); event FreezeWalletLockerEvent(); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the wallet locker contract /// @param newWalletLocker The (address of) WalletLocker contract instance function setWalletLocker(WalletLocker newWalletLocker) public onlyDeployer notNullAddress(address(newWalletLocker)) notSameAddresses(address(newWalletLocker), address(walletLocker)) { // Require that this contract has not been frozen require(!walletLockerFrozen, "Wallet locker frozen [WalletLockable.sol:43]"); // Update fields WalletLocker oldWalletLocker = walletLocker; walletLocker = newWalletLocker; // Emit event emit SetWalletLockerEvent(oldWalletLocker, newWalletLocker); } /// @notice Freeze the balance tracker from further updates /// @dev This operation can not be undone function freezeWalletLocker() public onlyDeployer { walletLockerFrozen = true; // Emit event emit FreezeWalletLockerEvent(); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier walletLockerInitialized() { require(address(walletLocker) != address(0), "Wallet locker not initialized [WalletLockable.sol:69]"); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title NahmiiTypesLib * @dev Data types of general nahmii character */ library NahmiiTypesLib { // // Enums // ----------------------------------------------------------------------------------------------------------------- enum ChallengePhase {Dispute, Closed} // // Structures // ----------------------------------------------------------------------------------------------------------------- struct OriginFigure { uint256 originId; MonetaryTypesLib.Figure figure; } struct IntendedConjugateCurrency { MonetaryTypesLib.Currency intended; MonetaryTypesLib.Currency conjugate; } struct SingleFigureTotalOriginFigures { MonetaryTypesLib.Figure single; OriginFigure[] total; } struct TotalOriginFigures { OriginFigure[] total; } struct CurrentPreviousInt256 { int256 current; int256 previous; } struct SingleTotalInt256 { int256 single; int256 total; } struct IntendedConjugateCurrentPreviousInt256 { CurrentPreviousInt256 intended; CurrentPreviousInt256 conjugate; } struct IntendedConjugateSingleTotalInt256 { SingleTotalInt256 intended; SingleTotalInt256 conjugate; } struct WalletOperatorHashes { bytes32 wallet; bytes32 operator; } struct Signature { bytes32 r; bytes32 s; uint8 v; } struct Seal { bytes32 hash; Signature signature; } struct WalletOperatorSeal { Seal wallet; Seal operator; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title PaymentTypesLib * @dev Data types centered around payment */ library PaymentTypesLib { // // Enums // ----------------------------------------------------------------------------------------------------------------- enum PaymentPartyRole {Sender, Recipient} // // Structures // ----------------------------------------------------------------------------------------------------------------- struct PaymentSenderParty { uint256 nonce; address wallet; NahmiiTypesLib.CurrentPreviousInt256 balances; NahmiiTypesLib.SingleFigureTotalOriginFigures fees; string data; } struct PaymentRecipientParty { uint256 nonce; address wallet; NahmiiTypesLib.CurrentPreviousInt256 balances; NahmiiTypesLib.TotalOriginFigures fees; } struct Operator { uint256 id; string data; } struct Payment { int256 amount; MonetaryTypesLib.Currency currency; PaymentSenderParty sender; PaymentRecipientParty recipient; // Positive transfer is always in direction from sender to recipient NahmiiTypesLib.SingleTotalInt256 transfers; NahmiiTypesLib.WalletOperatorSeal seals; uint256 blockNumber; Operator operator; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function PAYMENT_KIND() public pure returns (string memory) { return "payment"; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title PaymentHasher * @notice Contract that hashes types related to payment */ contract PaymentHasher is Ownable { // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- function hashPaymentAsWallet(PaymentTypesLib.Payment memory payment) public pure returns (bytes32) { bytes32 amountCurrencyHash = hashPaymentAmountCurrency(payment); bytes32 senderHash = hashPaymentSenderPartyAsWallet(payment.sender); bytes32 recipientHash = hashAddress(payment.recipient.wallet); return keccak256(abi.encodePacked(amountCurrencyHash, senderHash, recipientHash)); } function hashPaymentAsOperator(PaymentTypesLib.Payment memory payment) public pure returns (bytes32) { bytes32 walletSignatureHash = hashSignature(payment.seals.wallet.signature); bytes32 senderHash = hashPaymentSenderPartyAsOperator(payment.sender); bytes32 recipientHash = hashPaymentRecipientPartyAsOperator(payment.recipient); bytes32 transfersHash = hashSingleTotalInt256(payment.transfers); bytes32 operatorHash = hashString(payment.operator.data); return keccak256(abi.encodePacked( walletSignatureHash, senderHash, recipientHash, transfersHash, operatorHash )); } function hashPaymentAmountCurrency(PaymentTypesLib.Payment memory payment) public pure returns (bytes32) { return keccak256(abi.encodePacked( payment.amount, payment.currency.ct, payment.currency.id )); } function hashPaymentSenderPartyAsWallet( PaymentTypesLib.PaymentSenderParty memory paymentSenderParty) public pure returns (bytes32) { return keccak256(abi.encodePacked( paymentSenderParty.wallet, paymentSenderParty.data )); } function hashPaymentSenderPartyAsOperator( PaymentTypesLib.PaymentSenderParty memory paymentSenderParty) public pure returns (bytes32) { bytes32 rootHash = hashUint256(paymentSenderParty.nonce); bytes32 balancesHash = hashCurrentPreviousInt256(paymentSenderParty.balances); bytes32 singleFeeHash = hashFigure(paymentSenderParty.fees.single); bytes32 totalFeesHash = hashOriginFigures(paymentSenderParty.fees.total); return keccak256(abi.encodePacked( rootHash, balancesHash, singleFeeHash, totalFeesHash )); } function hashPaymentRecipientPartyAsOperator( PaymentTypesLib.PaymentRecipientParty memory paymentRecipientParty) public pure returns (bytes32) { bytes32 rootHash = hashUint256(paymentRecipientParty.nonce); bytes32 balancesHash = hashCurrentPreviousInt256(paymentRecipientParty.balances); bytes32 totalFeesHash = hashOriginFigures(paymentRecipientParty.fees.total); return keccak256(abi.encodePacked( rootHash, balancesHash, totalFeesHash )); } function hashCurrentPreviousInt256( NahmiiTypesLib.CurrentPreviousInt256 memory currentPreviousInt256) public pure returns (bytes32) { return keccak256(abi.encodePacked( currentPreviousInt256.current, currentPreviousInt256.previous )); } function hashSingleTotalInt256( NahmiiTypesLib.SingleTotalInt256 memory singleTotalInt256) public pure returns (bytes32) { return keccak256(abi.encodePacked( singleTotalInt256.single, singleTotalInt256.total )); } function hashFigure(MonetaryTypesLib.Figure memory figure) public pure returns (bytes32) { return keccak256(abi.encodePacked( figure.amount, figure.currency.ct, figure.currency.id )); } function hashOriginFigures(NahmiiTypesLib.OriginFigure[] memory originFigures) public pure returns (bytes32) { bytes32 hash; for (uint256 i = 0; i < originFigures.length; i++) { hash = keccak256(abi.encodePacked( hash, originFigures[i].originId, originFigures[i].figure.amount, originFigures[i].figure.currency.ct, originFigures[i].figure.currency.id ) ); } return hash; } function hashUint256(uint256 _uint256) public pure returns (bytes32) { return keccak256(abi.encodePacked(_uint256)); } function hashString(string memory _string) public pure returns (bytes32) { return keccak256(abi.encodePacked(_string)); } function hashAddress(address _address) public pure returns (bytes32) { return keccak256(abi.encodePacked(_address)); } function hashSignature(NahmiiTypesLib.Signature memory signature) public pure returns (bytes32) { return keccak256(abi.encodePacked( signature.v, signature.r, signature.s )); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title PaymentHashable * @notice An ownable that has a payment hasher property */ contract PaymentHashable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- PaymentHasher public paymentHasher; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetPaymentHasherEvent(PaymentHasher oldPaymentHasher, PaymentHasher newPaymentHasher); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the payment hasher contract /// @param newPaymentHasher The (address of) PaymentHasher contract instance function setPaymentHasher(PaymentHasher newPaymentHasher) public onlyDeployer notNullAddress(address(newPaymentHasher)) notSameAddresses(address(newPaymentHasher), address(paymentHasher)) { // Set new payment hasher PaymentHasher oldPaymentHasher = paymentHasher; paymentHasher = newPaymentHasher; // Emit event emit SetPaymentHasherEvent(oldPaymentHasher, newPaymentHasher); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier paymentHasherInitialized() { require(address(paymentHasher) != address(0), "Payment hasher not initialized [PaymentHashable.sol:52]"); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title SignerManager * @notice A contract to control who can execute some specific actions */ contract SignerManager is Ownable { using SafeMathUintLib for uint256; // // Variables // ----------------------------------------------------------------------------------------------------------------- mapping(address => uint256) public signerIndicesMap; // 1 based internally address[] public signers; // // Events // ----------------------------------------------------------------------------------------------------------------- event RegisterSignerEvent(address signer); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { registerSigner(deployer); } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Gauge whether an address is registered signer /// @param _address The concerned address /// @return true if address is registered signer, else false function isSigner(address _address) public view returns (bool) { return 0 < signerIndicesMap[_address]; } /// @notice Get the count of registered signers /// @return The count of registered signers function signersCount() public view returns (uint256) { return signers.length; } /// @notice Get the 0 based index of the given address in the list of signers /// @param _address The concerned address /// @return The index of the signer address function signerIndex(address _address) public view returns (uint256) { require(isSigner(_address), "Address not signer [SignerManager.sol:71]"); return signerIndicesMap[_address] - 1; } /// @notice Registers a signer /// @param newSigner The address of the signer to register function registerSigner(address newSigner) public onlyOperator notNullOrThisAddress(newSigner) { if (0 == signerIndicesMap[newSigner]) { // Set new operator signers.push(newSigner); signerIndicesMap[newSigner] = signers.length; // Emit event emit RegisterSignerEvent(newSigner); } } /// @notice Get the subset of registered signers in the given 0 based index range /// @param low The lower inclusive index /// @param up The upper inclusive index /// @return The subset of registered signers function signersByIndices(uint256 low, uint256 up) public view returns (address[] memory) { require(0 < signers.length, "No signers found [SignerManager.sol:101]"); require(low <= up, "Bounds parameters mismatch [SignerManager.sol:102]"); up = up.clampMax(signers.length - 1); address[] memory _signers = new address[](up - low + 1); for (uint256 i = low; i <= up; i++) _signers[i - low] = signers[i]; return _signers; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title SignerManageable * @notice A contract to interface ACL */ contract SignerManageable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- SignerManager public signerManager; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetSignerManagerEvent(address oldSignerManager, address newSignerManager); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address manager) public notNullAddress(manager) { signerManager = SignerManager(manager); } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the signer manager of this contract /// @param newSignerManager The address of the new signer function setSignerManager(address newSignerManager) public onlyDeployer notNullOrThisAddress(newSignerManager) { if (newSignerManager != address(signerManager)) { //set new signer address oldSignerManager = address(signerManager); signerManager = SignerManager(newSignerManager); // Emit event emit SetSignerManagerEvent(oldSignerManager, newSignerManager); } } /// @notice Prefix input hash and do ecrecover on prefixed hash /// @param hash The hash message that was signed /// @param v The v property of the ECDSA signature /// @param r The r property of the ECDSA signature /// @param s The s property of the ECDSA signature /// @return The address recovered function ethrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public pure returns (address) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash)); return ecrecover(prefixedHash, v, r, s); } /// @notice Gauge whether a signature of a hash has been signed by a registered signer /// @param hash The hash message that was signed /// @param v The v property of the ECDSA signature /// @param r The r property of the ECDSA signature /// @param s The s property of the ECDSA signature /// @return true if the recovered signer is one of the registered signers, else false function isSignedByRegisteredSigner(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public view returns (bool) { return signerManager.isSigner(ethrecover(hash, v, r, s)); } /// @notice Gauge whether a signature of a hash has been signed by the claimed signer /// @param hash The hash message that was signed /// @param v The v property of the ECDSA signature /// @param r The r property of the ECDSA signature /// @param s The s property of the ECDSA signature /// @param signer The claimed signer /// @return true if the recovered signer equals the input signer, else false function isSignedBy(bytes32 hash, uint8 v, bytes32 r, bytes32 s, address signer) public pure returns (bool) { return signer == ethrecover(hash, v, r, s); } // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier signerManagerInitialized() { require(address(signerManager) != address(0), "Signer manager not initialized [SignerManageable.sol:105]"); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Validator * @notice An ownable that validates valuable types (e.g. payment) */ contract Validator is Ownable, SignerManageable, Configurable, PaymentHashable { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer, address signerManager) Ownable(deployer) SignerManageable(signerManager) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- function isGenuineOperatorSignature(bytes32 hash, NahmiiTypesLib.Signature memory signature) public view returns (bool) { return isSignedByRegisteredSigner(hash, signature.v, signature.r, signature.s); } function isGenuineWalletSignature(bytes32 hash, NahmiiTypesLib.Signature memory signature, address wallet) public pure returns (bool) { return isSignedBy(hash, signature.v, signature.r, signature.s, wallet); } function isGenuinePaymentWalletHash(PaymentTypesLib.Payment memory payment) public view returns (bool) { return paymentHasher.hashPaymentAsWallet(payment) == payment.seals.wallet.hash; } function isGenuinePaymentOperatorHash(PaymentTypesLib.Payment memory payment) public view returns (bool) { return paymentHasher.hashPaymentAsOperator(payment) == payment.seals.operator.hash; } function isGenuinePaymentWalletSeal(PaymentTypesLib.Payment memory payment) public view returns (bool) { return isGenuinePaymentWalletHash(payment) && isGenuineWalletSignature(payment.seals.wallet.hash, payment.seals.wallet.signature, payment.sender.wallet); } function isGenuinePaymentOperatorSeal(PaymentTypesLib.Payment memory payment) public view returns (bool) { return isGenuinePaymentOperatorHash(payment) && isGenuineOperatorSignature(payment.seals.operator.hash, payment.seals.operator.signature); } function isGenuinePaymentSeals(PaymentTypesLib.Payment memory payment) public view returns (bool) { return isGenuinePaymentWalletSeal(payment) && isGenuinePaymentOperatorSeal(payment); } /// @dev Logics of this function only applies to FT function isGenuinePaymentFeeOfFungible(PaymentTypesLib.Payment memory payment) public view returns (bool) { int256 feePartsPer = int256(ConstantsLib.PARTS_PER()); int256 feeAmount = payment.amount .mul( configuration.currencyPaymentFee( payment.blockNumber, payment.currency.ct, payment.currency.id, payment.amount ) ).div(feePartsPer); if (1 > feeAmount) feeAmount = 1; return (payment.sender.fees.single.amount == feeAmount); } /// @dev Logics of this function only applies to NFT function isGenuinePaymentFeeOfNonFungible(PaymentTypesLib.Payment memory payment) public view returns (bool) { (address feeCurrencyCt, uint256 feeCurrencyId) = configuration.feeCurrency( payment.blockNumber, payment.currency.ct, payment.currency.id ); return feeCurrencyCt == payment.sender.fees.single.currency.ct && feeCurrencyId == payment.sender.fees.single.currency.id; } /// @dev Logics of this function only applies to FT function isGenuinePaymentSenderOfFungible(PaymentTypesLib.Payment memory payment) public view returns (bool) { return (payment.sender.wallet != payment.recipient.wallet) && (!signerManager.isSigner(payment.sender.wallet)) && (payment.sender.balances.current == payment.sender.balances.previous.sub(payment.transfers.single).sub(payment.sender.fees.single.amount)); } /// @dev Logics of this function only applies to FT function isGenuinePaymentRecipientOfFungible(PaymentTypesLib.Payment memory payment) public pure returns (bool) { return (payment.sender.wallet != payment.recipient.wallet) && (payment.recipient.balances.current == payment.recipient.balances.previous.add(payment.transfers.single)); } /// @dev Logics of this function only applies to NFT function isGenuinePaymentSenderOfNonFungible(PaymentTypesLib.Payment memory payment) public view returns (bool) { return (payment.sender.wallet != payment.recipient.wallet) && (!signerManager.isSigner(payment.sender.wallet)); } /// @dev Logics of this function only applies to NFT function isGenuinePaymentRecipientOfNonFungible(PaymentTypesLib.Payment memory payment) public pure returns (bool) { return (payment.sender.wallet != payment.recipient.wallet); } function isSuccessivePaymentsPartyNonces( PaymentTypesLib.Payment memory firstPayment, PaymentTypesLib.PaymentPartyRole firstPaymentPartyRole, PaymentTypesLib.Payment memory lastPayment, PaymentTypesLib.PaymentPartyRole lastPaymentPartyRole ) public pure returns (bool) { uint256 firstNonce = (PaymentTypesLib.PaymentPartyRole.Sender == firstPaymentPartyRole ? firstPayment.sender.nonce : firstPayment.recipient.nonce); uint256 lastNonce = (PaymentTypesLib.PaymentPartyRole.Sender == lastPaymentPartyRole ? lastPayment.sender.nonce : lastPayment.recipient.nonce); return lastNonce == firstNonce.add(1); } function isGenuineSuccessivePaymentsBalances( PaymentTypesLib.Payment memory firstPayment, PaymentTypesLib.PaymentPartyRole firstPaymentPartyRole, PaymentTypesLib.Payment memory lastPayment, PaymentTypesLib.PaymentPartyRole lastPaymentPartyRole, int256 delta ) public pure returns (bool) { NahmiiTypesLib.CurrentPreviousInt256 memory firstCurrentPreviousBalances = (PaymentTypesLib.PaymentPartyRole.Sender == firstPaymentPartyRole ? firstPayment.sender.balances : firstPayment.recipient.balances); NahmiiTypesLib.CurrentPreviousInt256 memory lastCurrentPreviousBalances = (PaymentTypesLib.PaymentPartyRole.Sender == lastPaymentPartyRole ? lastPayment.sender.balances : lastPayment.recipient.balances); return lastCurrentPreviousBalances.previous == firstCurrentPreviousBalances.current.add(delta); } function isGenuineSuccessivePaymentsTotalFees( PaymentTypesLib.Payment memory firstPayment, PaymentTypesLib.Payment memory lastPayment ) public pure returns (bool) { MonetaryTypesLib.Figure memory firstTotalFee = getProtocolFigureByCurrency(firstPayment.sender.fees.total, lastPayment.sender.fees.single.currency); MonetaryTypesLib.Figure memory lastTotalFee = getProtocolFigureByCurrency(lastPayment.sender.fees.total, lastPayment.sender.fees.single.currency); return lastTotalFee.amount == firstTotalFee.amount.add(lastPayment.sender.fees.single.amount); } function isPaymentParty(PaymentTypesLib.Payment memory payment, address wallet) public pure returns (bool) { return wallet == payment.sender.wallet || wallet == payment.recipient.wallet; } function isPaymentSender(PaymentTypesLib.Payment memory payment, address wallet) public pure returns (bool) { return wallet == payment.sender.wallet; } function isPaymentRecipient(PaymentTypesLib.Payment memory payment, address wallet) public pure returns (bool) { return wallet == payment.recipient.wallet; } function isPaymentCurrency(PaymentTypesLib.Payment memory payment, MonetaryTypesLib.Currency memory currency) public pure returns (bool) { return currency.ct == payment.currency.ct && currency.id == payment.currency.id; } function isPaymentCurrencyNonFungible(PaymentTypesLib.Payment memory payment) public pure returns (bool) { return payment.currency.ct != payment.sender.fees.single.currency.ct || payment.currency.id != payment.sender.fees.single.currency.id; } // // Private unctions // ----------------------------------------------------------------------------------------------------------------- function getProtocolFigureByCurrency(NahmiiTypesLib.OriginFigure[] memory originFigures, MonetaryTypesLib.Currency memory currency) private pure returns (MonetaryTypesLib.Figure memory) { for (uint256 i = 0; i < originFigures.length; i++) if (originFigures[i].figure.currency.ct == currency.ct && originFigures[i].figure.currency.id == currency.id && originFigures[i].originId == 0) return originFigures[i].figure; return MonetaryTypesLib.Figure(0, currency); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title TradeTypesLib * @dev Data types centered around trade */ library TradeTypesLib { // // Enums // ----------------------------------------------------------------------------------------------------------------- enum CurrencyRole {Intended, Conjugate} enum LiquidityRole {Maker, Taker} enum Intention {Buy, Sell} enum TradePartyRole {Buyer, Seller} // // Structures // ----------------------------------------------------------------------------------------------------------------- struct OrderPlacement { Intention intention; int256 amount; NahmiiTypesLib.IntendedConjugateCurrency currencies; int256 rate; NahmiiTypesLib.CurrentPreviousInt256 residuals; } struct Order { uint256 nonce; address wallet; OrderPlacement placement; NahmiiTypesLib.WalletOperatorSeal seals; uint256 blockNumber; uint256 operatorId; } struct TradeOrder { int256 amount; NahmiiTypesLib.WalletOperatorHashes hashes; NahmiiTypesLib.CurrentPreviousInt256 residuals; } struct TradeParty { uint256 nonce; address wallet; uint256 rollingVolume; LiquidityRole liquidityRole; TradeOrder order; NahmiiTypesLib.IntendedConjugateCurrentPreviousInt256 balances; NahmiiTypesLib.SingleFigureTotalOriginFigures fees; } struct Trade { uint256 nonce; int256 amount; NahmiiTypesLib.IntendedConjugateCurrency currencies; int256 rate; TradeParty buyer; TradeParty seller; // Positive intended transfer is always in direction from seller to buyer // Positive conjugate transfer is always in direction from buyer to seller NahmiiTypesLib.IntendedConjugateSingleTotalInt256 transfers; NahmiiTypesLib.Seal seal; uint256 blockNumber; uint256 operatorId; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function TRADE_KIND() public pure returns (string memory) { return "trade"; } function ORDER_KIND() public pure returns (string memory) { return "order"; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Validatable * @notice An ownable that has a validator property */ contract Validatable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- Validator public validator; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetValidatorEvent(Validator oldValidator, Validator newValidator); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the validator contract /// @param newValidator The (address of) Validator contract instance function setValidator(Validator newValidator) public onlyDeployer notNullAddress(address(newValidator)) notSameAddresses(address(newValidator), address(validator)) { //set new validator Validator oldValidator = validator; validator = newValidator; // Emit event emit SetValidatorEvent(oldValidator, newValidator); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier validatorInitialized() { require(address(validator) != address(0), "Validator not initialized [Validatable.sol:55]"); _; } modifier onlyOperatorSealedPayment(PaymentTypesLib.Payment memory payment) { require(validator.isGenuinePaymentOperatorSeal(payment), "Payment operator seal not genuine [Validatable.sol:60]"); _; } modifier onlySealedPayment(PaymentTypesLib.Payment memory payment) { require(validator.isGenuinePaymentSeals(payment), "Payment seals not genuine [Validatable.sol:65]"); _; } modifier onlyPaymentParty(PaymentTypesLib.Payment memory payment, address wallet) { require(validator.isPaymentParty(payment, wallet), "Wallet not payment party [Validatable.sol:70]"); _; } modifier onlyPaymentSender(PaymentTypesLib.Payment memory payment, address wallet) { require(validator.isPaymentSender(payment, wallet), "Wallet not payment sender [Validatable.sol:75]"); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Beneficiary * @notice A recipient of ethers and tokens */ contract Beneficiary { /// @notice Receive ethers to the given wallet's given balance type /// @param wallet The address of the concerned wallet /// @param balanceType The target balance type of the wallet function receiveEthersTo(address wallet, string memory balanceType) public payable; /// @notice Receive token to the given wallet's given balance type /// @dev The wallet must approve of the token transfer prior to calling this function /// @param wallet The address of the concerned wallet /// @param balanceType The target balance type of the wallet /// @param amount The amount to deposit /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721") function receiveTokensTo(address wallet, string memory balanceType, int256 amount, address currencyCt, uint256 currencyId, string memory standard) public; } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title AccrualBeneficiary * @notice A beneficiary of accruals */ contract AccrualBeneficiary is Beneficiary { // // Functions // ----------------------------------------------------------------------------------------------------------------- event CloseAccrualPeriodEvent(); // // Functions // ----------------------------------------------------------------------------------------------------------------- function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory) public { emit CloseAccrualPeriodEvent(); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title TransferController * @notice A base contract to handle transfers of different currency types */ contract TransferController { // // Events // ----------------------------------------------------------------------------------------------------------------- event CurrencyTransferred(address from, address to, uint256 value, address currencyCt, uint256 currencyId); // // Functions // ----------------------------------------------------------------------------------------------------------------- function isFungible() public view returns (bool); function standard() public view returns (string memory); /// @notice MUST be called with DELEGATECALL function receive(address from, address to, uint256 value, address currencyCt, uint256 currencyId) public; /// @notice MUST be called with DELEGATECALL function approve(address to, uint256 value, address currencyCt, uint256 currencyId) public; /// @notice MUST be called with DELEGATECALL function dispatch(address from, address to, uint256 value, address currencyCt, uint256 currencyId) public; //---------------------------------------- function getReceiveSignature() public pure returns (bytes4) { return bytes4(keccak256("receive(address,address,uint256,address,uint256)")); } function getApproveSignature() public pure returns (bytes4) { return bytes4(keccak256("approve(address,uint256,address,uint256)")); } function getDispatchSignature() public pure returns (bytes4) { return bytes4(keccak256("dispatch(address,address,uint256,address,uint256)")); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title TransferControllerManager * @notice Handles the management of transfer controllers */ contract TransferControllerManager is Ownable { // // Constants // ----------------------------------------------------------------------------------------------------------------- struct CurrencyInfo { bytes32 standard; bool blacklisted; } // // Variables // ----------------------------------------------------------------------------------------------------------------- mapping(bytes32 => address) public registeredTransferControllers; mapping(address => CurrencyInfo) public registeredCurrencies; // // Events // ----------------------------------------------------------------------------------------------------------------- event RegisterTransferControllerEvent(string standard, address controller); event ReassociateTransferControllerEvent(string oldStandard, string newStandard, address controller); event RegisterCurrencyEvent(address currencyCt, string standard); event DeregisterCurrencyEvent(address currencyCt); event BlacklistCurrencyEvent(address currencyCt); event WhitelistCurrencyEvent(address currencyCt); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- function registerTransferController(string calldata standard, address controller) external onlyDeployer notNullAddress(controller) { require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:58]"); bytes32 standardHash = keccak256(abi.encodePacked(standard)); registeredTransferControllers[standardHash] = controller; // Emit event emit RegisterTransferControllerEvent(standard, controller); } function reassociateTransferController(string calldata oldStandard, string calldata newStandard, address controller) external onlyDeployer notNullAddress(controller) { require(bytes(newStandard).length > 0, "Empty new standard not supported [TransferControllerManager.sol:72]"); bytes32 oldStandardHash = keccak256(abi.encodePacked(oldStandard)); bytes32 newStandardHash = keccak256(abi.encodePacked(newStandard)); require(registeredTransferControllers[oldStandardHash] != address(0), "Old standard not registered [TransferControllerManager.sol:76]"); require(registeredTransferControllers[newStandardHash] == address(0), "New standard previously registered [TransferControllerManager.sol:77]"); registeredTransferControllers[newStandardHash] = registeredTransferControllers[oldStandardHash]; registeredTransferControllers[oldStandardHash] = address(0); // Emit event emit ReassociateTransferControllerEvent(oldStandard, newStandard, controller); } function registerCurrency(address currencyCt, string calldata standard) external onlyOperator notNullAddress(currencyCt) { require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:91]"); bytes32 standardHash = keccak256(abi.encodePacked(standard)); require(registeredCurrencies[currencyCt].standard == bytes32(0), "Currency previously registered [TransferControllerManager.sol:94]"); registeredCurrencies[currencyCt].standard = standardHash; // Emit event emit RegisterCurrencyEvent(currencyCt, standard); } function deregisterCurrency(address currencyCt) external onlyOperator { require(registeredCurrencies[currencyCt].standard != 0, "Currency not registered [TransferControllerManager.sol:106]"); registeredCurrencies[currencyCt].standard = bytes32(0); registeredCurrencies[currencyCt].blacklisted = false; // Emit event emit DeregisterCurrencyEvent(currencyCt); } function blacklistCurrency(address currencyCt) external onlyOperator { require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:119]"); registeredCurrencies[currencyCt].blacklisted = true; // Emit event emit BlacklistCurrencyEvent(currencyCt); } function whitelistCurrency(address currencyCt) external onlyOperator { require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:131]"); registeredCurrencies[currencyCt].blacklisted = false; // Emit event emit WhitelistCurrencyEvent(currencyCt); } /** @notice The provided standard takes priority over assigned interface to currency */ function transferController(address currencyCt, string memory standard) public view returns (TransferController) { if (bytes(standard).length > 0) { bytes32 standardHash = keccak256(abi.encodePacked(standard)); require(registeredTransferControllers[standardHash] != address(0), "Standard not registered [TransferControllerManager.sol:150]"); return TransferController(registeredTransferControllers[standardHash]); } require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:154]"); require(!registeredCurrencies[currencyCt].blacklisted, "Currency blacklisted [TransferControllerManager.sol:155]"); address controllerAddress = registeredTransferControllers[registeredCurrencies[currencyCt].standard]; require(controllerAddress != address(0), "No matching transfer controller [TransferControllerManager.sol:158]"); return TransferController(controllerAddress); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title TransferControllerManageable * @notice An ownable with a transfer controller manager */ contract TransferControllerManageable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- TransferControllerManager public transferControllerManager; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetTransferControllerManagerEvent(TransferControllerManager oldTransferControllerManager, TransferControllerManager newTransferControllerManager); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the currency manager contract /// @param newTransferControllerManager The (address of) TransferControllerManager contract instance function setTransferControllerManager(TransferControllerManager newTransferControllerManager) public onlyDeployer notNullAddress(address(newTransferControllerManager)) notSameAddresses(address(newTransferControllerManager), address(transferControllerManager)) { //set new currency manager TransferControllerManager oldTransferControllerManager = transferControllerManager; transferControllerManager = newTransferControllerManager; // Emit event emit SetTransferControllerManagerEvent(oldTransferControllerManager, newTransferControllerManager); } /// @notice Get the transfer controller of the given currency contract address and standard function transferController(address currencyCt, string memory standard) internal view returns (TransferController) { return transferControllerManager.transferController(currencyCt, standard); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier transferControllerManagerInitialized() { require(address(transferControllerManager) != address(0), "Transfer controller manager not initialized [TransferControllerManageable.sol:63]"); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library TxHistoryLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- struct AssetEntry { int256 amount; uint256 blockNumber; address currencyCt; //0 for ethers uint256 currencyId; } struct TxHistory { AssetEntry[] deposits; mapping(address => mapping(uint256 => AssetEntry[])) currencyDeposits; AssetEntry[] withdrawals; mapping(address => mapping(uint256 => AssetEntry[])) currencyWithdrawals; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function addDeposit(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId) internal { AssetEntry memory deposit = AssetEntry(amount, block.number, currencyCt, currencyId); self.deposits.push(deposit); self.currencyDeposits[currencyCt][currencyId].push(deposit); } function addWithdrawal(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId) internal { AssetEntry memory withdrawal = AssetEntry(amount, block.number, currencyCt, currencyId); self.withdrawals.push(withdrawal); self.currencyWithdrawals[currencyCt][currencyId].push(withdrawal); } //---- function deposit(TxHistory storage self, uint index) internal view returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId) { require(index < self.deposits.length, "Index ouf of bounds [TxHistoryLib.sol:56]"); amount = self.deposits[index].amount; blockNumber = self.deposits[index].blockNumber; currencyCt = self.deposits[index].currencyCt; currencyId = self.deposits[index].currencyId; } function depositsCount(TxHistory storage self) internal view returns (uint256) { return self.deposits.length; } function currencyDeposit(TxHistory storage self, address currencyCt, uint256 currencyId, uint index) internal view returns (int256 amount, uint256 blockNumber) { require(index < self.currencyDeposits[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:77]"); amount = self.currencyDeposits[currencyCt][currencyId][index].amount; blockNumber = self.currencyDeposits[currencyCt][currencyId][index].blockNumber; } function currencyDepositsCount(TxHistory storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.currencyDeposits[currencyCt][currencyId].length; } //---- function withdrawal(TxHistory storage self, uint index) internal view returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId) { require(index < self.withdrawals.length, "Index out of bounds [TxHistoryLib.sol:98]"); amount = self.withdrawals[index].amount; blockNumber = self.withdrawals[index].blockNumber; currencyCt = self.withdrawals[index].currencyCt; currencyId = self.withdrawals[index].currencyId; } function withdrawalsCount(TxHistory storage self) internal view returns (uint256) { return self.withdrawals.length; } function currencyWithdrawal(TxHistory storage self, address currencyCt, uint256 currencyId, uint index) internal view returns (int256 amount, uint256 blockNumber) { require(index < self.currencyWithdrawals[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:119]"); amount = self.currencyWithdrawals[currencyCt][currencyId][index].amount; blockNumber = self.currencyWithdrawals[currencyCt][currencyId][index].blockNumber; } function currencyWithdrawalsCount(TxHistory storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.currencyWithdrawals[currencyCt][currencyId].length; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title SecurityBond * @notice Fund that contains crypto incentive for challenging operator fraud. */ contract SecurityBond is Ownable, Configurable, AccrualBeneficiary, Servable, TransferControllerManageable { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using FungibleBalanceLib for FungibleBalanceLib.Balance; using TxHistoryLib for TxHistoryLib.TxHistory; using CurrenciesLib for CurrenciesLib.Currencies; // // Constants // ----------------------------------------------------------------------------------------------------------------- string constant public REWARD_ACTION = "reward"; string constant public DEPRIVE_ACTION = "deprive"; // // Types // ----------------------------------------------------------------------------------------------------------------- struct FractionalReward { uint256 fraction; uint256 nonce; uint256 unlockTime; } struct AbsoluteReward { int256 amount; uint256 nonce; uint256 unlockTime; } // // Variables // ----------------------------------------------------------------------------------------------------------------- FungibleBalanceLib.Balance private deposited; TxHistoryLib.TxHistory private txHistory; CurrenciesLib.Currencies private inUseCurrencies; mapping(address => FractionalReward) public fractionalRewardByWallet; mapping(address => mapping(address => mapping(uint256 => AbsoluteReward))) public absoluteRewardByWallet; mapping(address => mapping(address => mapping(uint256 => uint256))) public claimNonceByWalletCurrency; mapping(address => FungibleBalanceLib.Balance) private stagedByWallet; mapping(address => uint256) public nonceByWallet; // // Events // ----------------------------------------------------------------------------------------------------------------- event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId); event RewardFractionalEvent(address wallet, uint256 fraction, uint256 unlockTimeoutInSeconds); event RewardAbsoluteEvent(address wallet, int256 amount, address currencyCt, uint256 currencyId, uint256 unlockTimeoutInSeconds); event DepriveFractionalEvent(address wallet); event DepriveAbsoluteEvent(address wallet, address currencyCt, uint256 currencyId); event ClaimAndTransferToBeneficiaryEvent(address from, Beneficiary beneficiary, string balanceType, int256 amount, address currencyCt, uint256 currencyId, string standard); event ClaimAndStageEvent(address from, int256 amount, address currencyCt, uint256 currencyId); event WithdrawEvent(address from, int256 amount, address currencyCt, uint256 currencyId, string standard); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) Servable() public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Fallback function that deposits ethers function() external payable { receiveEthersTo(msg.sender, ""); } /// @notice Receive ethers to /// @param wallet The concerned wallet address function receiveEthersTo(address wallet, string memory) public payable { int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value); // Add to balance deposited.add(amount, address(0), 0); txHistory.addDeposit(amount, address(0), 0); // Add currency to in-use list inUseCurrencies.add(address(0), 0); // Emit event emit ReceiveEvent(wallet, amount, address(0), 0); } /// @notice Receive tokens /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokens(string memory, int256 amount, address currencyCt, uint256 currencyId, string memory standard) public { receiveTokensTo(msg.sender, "", amount, currencyCt, currencyId, standard); } /// @notice Receive tokens to /// @param wallet The address of the concerned wallet /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokensTo(address wallet, string memory, int256 amount, address currencyCt, uint256 currencyId, string memory standard) public { require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [SecurityBond.sol:145]"); // Execute transfer TransferController controller = transferController(currencyCt, standard); (bool success,) = address(controller).delegatecall( abi.encodeWithSelector( controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId ) ); require(success, "Reception by controller failed [SecurityBond.sol:154]"); // Add to balance deposited.add(amount, currencyCt, currencyId); txHistory.addDeposit(amount, currencyCt, currencyId); // Add currency to in-use list inUseCurrencies.add(currencyCt, currencyId); // Emit event emit ReceiveEvent(wallet, amount, currencyCt, currencyId); } /// @notice Get the count of deposits /// @return The count of deposits function depositsCount() public view returns (uint256) { return txHistory.depositsCount(); } /// @notice Get the deposit at the given index /// @return The deposit at the given index function deposit(uint index) public view returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId) { return txHistory.deposit(index); } /// @notice Get the deposited balance of the given currency /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The deposited balance function depositedBalance(address currencyCt, uint256 currencyId) public view returns (int256) { return deposited.get(currencyCt, currencyId); } /// @notice Get the fractional amount deposited balance of the given currency /// @param currencyCt The contract address of the currency that the wallet is deprived /// @param currencyId The ID of the currency that the wallet is deprived /// @param fraction The fraction of sums that the wallet is rewarded /// @return The fractional amount of deposited balance function depositedFractionalBalance(address currencyCt, uint256 currencyId, uint256 fraction) public view returns (int256) { return deposited.get(currencyCt, currencyId) .mul(SafeMathIntLib.toInt256(fraction)) .div(ConstantsLib.PARTS_PER()); } /// @notice Get the staged balance of the given currency /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The deposited balance function stagedBalance(address wallet, address currencyCt, uint256 currencyId) public view returns (int256) { return stagedByWallet[wallet].get(currencyCt, currencyId); } /// @notice Get the count of currencies recorded /// @return The number of currencies function inUseCurrenciesCount() public view returns (uint256) { return inUseCurrencies.count(); } /// @notice Get the currencies recorded with indices in the given range /// @param low The lower currency index /// @param up The upper currency index /// @return The currencies of the given index range function inUseCurrenciesByIndices(uint256 low, uint256 up) public view returns (MonetaryTypesLib.Currency[] memory) { return inUseCurrencies.getByIndices(low, up); } /// @notice Reward the given wallet the given fraction of funds, where the reward is locked /// for the given number of seconds /// @param wallet The concerned wallet /// @param fraction The fraction of sums that the wallet is rewarded /// @param unlockTimeoutInSeconds The number of seconds for which the reward is locked and should /// be claimed function rewardFractional(address wallet, uint256 fraction, uint256 unlockTimeoutInSeconds) public notNullAddress(wallet) onlyEnabledServiceAction(REWARD_ACTION) { // Update fractional reward fractionalRewardByWallet[wallet].fraction = fraction.clampMax(uint256(ConstantsLib.PARTS_PER())); fractionalRewardByWallet[wallet].nonce = ++nonceByWallet[wallet]; fractionalRewardByWallet[wallet].unlockTime = block.timestamp.add(unlockTimeoutInSeconds); // Emit event emit RewardFractionalEvent(wallet, fraction, unlockTimeoutInSeconds); } /// @notice Reward the given wallet the given amount of funds, where the reward is locked /// for the given number of seconds /// @param wallet The concerned wallet /// @param amount The amount that the wallet is rewarded /// @param currencyCt The contract address of the currency that the wallet is rewarded /// @param currencyId The ID of the currency that the wallet is rewarded /// @param unlockTimeoutInSeconds The number of seconds for which the reward is locked and should /// be claimed function rewardAbsolute(address wallet, int256 amount, address currencyCt, uint256 currencyId, uint256 unlockTimeoutInSeconds) public notNullAddress(wallet) onlyEnabledServiceAction(REWARD_ACTION) { // Update absolute reward absoluteRewardByWallet[wallet][currencyCt][currencyId].amount = amount; absoluteRewardByWallet[wallet][currencyCt][currencyId].nonce = ++nonceByWallet[wallet]; absoluteRewardByWallet[wallet][currencyCt][currencyId].unlockTime = block.timestamp.add(unlockTimeoutInSeconds); // Emit event emit RewardAbsoluteEvent(wallet, amount, currencyCt, currencyId, unlockTimeoutInSeconds); } /// @notice Deprive the given wallet of any fractional reward it has been granted /// @param wallet The concerned wallet function depriveFractional(address wallet) public onlyEnabledServiceAction(DEPRIVE_ACTION) { // Update fractional reward fractionalRewardByWallet[wallet].fraction = 0; fractionalRewardByWallet[wallet].nonce = ++nonceByWallet[wallet]; fractionalRewardByWallet[wallet].unlockTime = 0; // Emit event emit DepriveFractionalEvent(wallet); } /// @notice Deprive the given wallet of any absolute reward it has been granted in the given currency /// @param wallet The concerned wallet /// @param currencyCt The contract address of the currency that the wallet is deprived /// @param currencyId The ID of the currency that the wallet is deprived function depriveAbsolute(address wallet, address currencyCt, uint256 currencyId) public onlyEnabledServiceAction(DEPRIVE_ACTION) { // Update absolute reward absoluteRewardByWallet[wallet][currencyCt][currencyId].amount = 0; absoluteRewardByWallet[wallet][currencyCt][currencyId].nonce = ++nonceByWallet[wallet]; absoluteRewardByWallet[wallet][currencyCt][currencyId].unlockTime = 0; // Emit event emit DepriveAbsoluteEvent(wallet, currencyCt, currencyId); } /// @notice Claim reward and transfer to beneficiary /// @param beneficiary The concerned beneficiary /// @param balanceType The target balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721") function claimAndTransferToBeneficiary(Beneficiary beneficiary, string memory balanceType, address currencyCt, uint256 currencyId, string memory standard) public { // Claim reward int256 claimedAmount = _claim(msg.sender, currencyCt, currencyId); // Subtract from deposited balance deposited.sub(claimedAmount, currencyCt, currencyId); // Execute transfer if (address(0) == currencyCt && 0 == currencyId) beneficiary.receiveEthersTo.value(uint256(claimedAmount))(msg.sender, balanceType); else { TransferController controller = transferController(currencyCt, standard); (bool success,) = address(controller).delegatecall( abi.encodeWithSelector( controller.getApproveSignature(), address(beneficiary), uint256(claimedAmount), currencyCt, currencyId ) ); require(success, "Approval by controller failed [SecurityBond.sol:350]"); beneficiary.receiveTokensTo(msg.sender, balanceType, claimedAmount, currencyCt, currencyId, standard); } // Emit event emit ClaimAndTransferToBeneficiaryEvent(msg.sender, beneficiary, balanceType, claimedAmount, currencyCt, currencyId, standard); } /// @notice Claim reward and stage for later withdrawal /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function claimAndStage(address currencyCt, uint256 currencyId) public { // Claim reward int256 claimedAmount = _claim(msg.sender, currencyCt, currencyId); // Subtract from deposited balance deposited.sub(claimedAmount, currencyCt, currencyId); // Add to staged balance stagedByWallet[msg.sender].add(claimedAmount, currencyCt, currencyId); // Emit event emit ClaimAndStageEvent(msg.sender, claimedAmount, currencyCt, currencyId); } /// @notice Withdraw from staged balance of msg.sender /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721") function withdraw(int256 amount, address currencyCt, uint256 currencyId, string memory standard) public { // Require that amount is strictly positive require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [SecurityBond.sol:386]"); // Clamp amount to the max given by staged balance amount = amount.clampMax(stagedByWallet[msg.sender].get(currencyCt, currencyId)); // Subtract to per-wallet staged balance stagedByWallet[msg.sender].sub(amount, currencyCt, currencyId); // Execute transfer if (address(0) == currencyCt && 0 == currencyId) msg.sender.transfer(uint256(amount)); else { TransferController controller = transferController(currencyCt, standard); (bool success,) = address(controller).delegatecall( abi.encodeWithSelector( controller.getDispatchSignature(), address(this), msg.sender, uint256(amount), currencyCt, currencyId ) ); require(success, "Dispatch by controller failed [SecurityBond.sol:405]"); } // Emit event emit WithdrawEvent(msg.sender, amount, currencyCt, currencyId, standard); } // // Private functions // ----------------------------------------------------------------------------------------------------------------- function _claim(address wallet, address currencyCt, uint256 currencyId) private returns (int256) { // Combine claim nonce from rewards uint256 claimNonce = fractionalRewardByWallet[wallet].nonce.clampMin( absoluteRewardByWallet[wallet][currencyCt][currencyId].nonce ); // Require that new claim nonce is strictly greater than current stored one require( claimNonce > claimNonceByWalletCurrency[wallet][currencyCt][currencyId], "Claim nonce not strictly greater than previously claimed nonce [SecurityBond.sol:425]" ); // Combine claim amount from rewards int256 claimAmount = _fractionalRewardAmountByWalletCurrency(wallet, currencyCt, currencyId).add( _absoluteRewardAmountByWalletCurrency(wallet, currencyCt, currencyId) ).clampMax( deposited.get(currencyCt, currencyId) ); // Require that claim amount is strictly positive, indicating that there is an amount to claim require(claimAmount.isNonZeroPositiveInt256(), "Claim amount not strictly positive [SecurityBond.sol:438]"); // Update stored claim nonce for wallet and currency claimNonceByWalletCurrency[wallet][currencyCt][currencyId] = claimNonce; return claimAmount; } function _fractionalRewardAmountByWalletCurrency(address wallet, address currencyCt, uint256 currencyId) private view returns (int256) { if ( claimNonceByWalletCurrency[wallet][currencyCt][currencyId] < fractionalRewardByWallet[wallet].nonce && block.timestamp >= fractionalRewardByWallet[wallet].unlockTime ) return deposited.get(currencyCt, currencyId) .mul(SafeMathIntLib.toInt256(fractionalRewardByWallet[wallet].fraction)) .div(ConstantsLib.PARTS_PER()); else return 0; } function _absoluteRewardAmountByWalletCurrency(address wallet, address currencyCt, uint256 currencyId) private view returns (int256) { if ( claimNonceByWalletCurrency[wallet][currencyCt][currencyId] < absoluteRewardByWallet[wallet][currencyCt][currencyId].nonce && block.timestamp >= absoluteRewardByWallet[wallet][currencyCt][currencyId].unlockTime ) return absoluteRewardByWallet[wallet][currencyCt][currencyId].amount.clampMax( deposited.get(currencyCt, currencyId) ); else return 0; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title SecurityBondable * @notice An ownable that has a security bond property */ contract SecurityBondable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- SecurityBond public securityBond; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetSecurityBondEvent(SecurityBond oldSecurityBond, SecurityBond newSecurityBond); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the security bond contract /// @param newSecurityBond The (address of) SecurityBond contract instance function setSecurityBond(SecurityBond newSecurityBond) public onlyDeployer notNullAddress(address(newSecurityBond)) notSameAddresses(address(newSecurityBond), address(securityBond)) { //set new security bond SecurityBond oldSecurityBond = securityBond; securityBond = newSecurityBond; // Emit event emit SetSecurityBondEvent(oldSecurityBond, newSecurityBond); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier securityBondInitialized() { require(address(securityBond) != address(0), "Security bond not initialized [SecurityBondable.sol:52]"); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title FraudChallenge * @notice Where fraud challenge results are found */ contract FraudChallenge is Ownable, Servable { // // Constants // ----------------------------------------------------------------------------------------------------------------- string constant public ADD_SEIZED_WALLET_ACTION = "add_seized_wallet"; string constant public ADD_DOUBLE_SPENDER_WALLET_ACTION = "add_double_spender_wallet"; string constant public ADD_FRAUDULENT_ORDER_ACTION = "add_fraudulent_order"; string constant public ADD_FRAUDULENT_TRADE_ACTION = "add_fraudulent_trade"; string constant public ADD_FRAUDULENT_PAYMENT_ACTION = "add_fraudulent_payment"; // // Variables // ----------------------------------------------------------------------------------------------------------------- address[] public doubleSpenderWallets; mapping(address => bool) public doubleSpenderByWallet; bytes32[] public fraudulentOrderHashes; mapping(bytes32 => bool) public fraudulentByOrderHash; bytes32[] public fraudulentTradeHashes; mapping(bytes32 => bool) public fraudulentByTradeHash; bytes32[] public fraudulentPaymentHashes; mapping(bytes32 => bool) public fraudulentByPaymentHash; // // Events // ----------------------------------------------------------------------------------------------------------------- event AddDoubleSpenderWalletEvent(address wallet); event AddFraudulentOrderHashEvent(bytes32 hash); event AddFraudulentTradeHashEvent(bytes32 hash); event AddFraudulentPaymentHashEvent(bytes32 hash); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Get the double spender status of given wallet /// @param wallet The wallet address for which to check double spender status /// @return true if wallet is double spender, false otherwise function isDoubleSpenderWallet(address wallet) public view returns (bool) { return doubleSpenderByWallet[wallet]; } /// @notice Get the number of wallets tagged as double spenders /// @return Number of double spender wallets function doubleSpenderWalletsCount() public view returns (uint256) { return doubleSpenderWallets.length; } /// @notice Add given wallets to store of double spender wallets if not already present /// @param wallet The first wallet to add function addDoubleSpenderWallet(address wallet) public onlyEnabledServiceAction(ADD_DOUBLE_SPENDER_WALLET_ACTION) { if (!doubleSpenderByWallet[wallet]) { doubleSpenderWallets.push(wallet); doubleSpenderByWallet[wallet] = true; emit AddDoubleSpenderWalletEvent(wallet); } } /// @notice Get the number of fraudulent order hashes function fraudulentOrderHashesCount() public view returns (uint256) { return fraudulentOrderHashes.length; } /// @notice Get the state about whether the given hash equals the hash of a fraudulent order /// @param hash The hash to be tested function isFraudulentOrderHash(bytes32 hash) public view returns (bool) { return fraudulentByOrderHash[hash]; } /// @notice Add given order hash to store of fraudulent order hashes if not already present function addFraudulentOrderHash(bytes32 hash) public onlyEnabledServiceAction(ADD_FRAUDULENT_ORDER_ACTION) { if (!fraudulentByOrderHash[hash]) { fraudulentByOrderHash[hash] = true; fraudulentOrderHashes.push(hash); emit AddFraudulentOrderHashEvent(hash); } } /// @notice Get the number of fraudulent trade hashes function fraudulentTradeHashesCount() public view returns (uint256) { return fraudulentTradeHashes.length; } /// @notice Get the state about whether the given hash equals the hash of a fraudulent trade /// @param hash The hash to be tested /// @return true if hash is the one of a fraudulent trade, else false function isFraudulentTradeHash(bytes32 hash) public view returns (bool) { return fraudulentByTradeHash[hash]; } /// @notice Add given trade hash to store of fraudulent trade hashes if not already present function addFraudulentTradeHash(bytes32 hash) public onlyEnabledServiceAction(ADD_FRAUDULENT_TRADE_ACTION) { if (!fraudulentByTradeHash[hash]) { fraudulentByTradeHash[hash] = true; fraudulentTradeHashes.push(hash); emit AddFraudulentTradeHashEvent(hash); } } /// @notice Get the number of fraudulent payment hashes function fraudulentPaymentHashesCount() public view returns (uint256) { return fraudulentPaymentHashes.length; } /// @notice Get the state about whether the given hash equals the hash of a fraudulent payment /// @param hash The hash to be tested /// @return true if hash is the one of a fraudulent payment, else null function isFraudulentPaymentHash(bytes32 hash) public view returns (bool) { return fraudulentByPaymentHash[hash]; } /// @notice Add given payment hash to store of fraudulent payment hashes if not already present function addFraudulentPaymentHash(bytes32 hash) public onlyEnabledServiceAction(ADD_FRAUDULENT_PAYMENT_ACTION) { if (!fraudulentByPaymentHash[hash]) { fraudulentByPaymentHash[hash] = true; fraudulentPaymentHashes.push(hash); emit AddFraudulentPaymentHashEvent(hash); } } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title FraudChallengable * @notice An ownable that has a fraud challenge property */ contract FraudChallengable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- FraudChallenge public fraudChallenge; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetFraudChallengeEvent(FraudChallenge oldFraudChallenge, FraudChallenge newFraudChallenge); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the fraud challenge contract /// @param newFraudChallenge The (address of) FraudChallenge contract instance function setFraudChallenge(FraudChallenge newFraudChallenge) public onlyDeployer notNullAddress(address(newFraudChallenge)) notSameAddresses(address(newFraudChallenge), address(fraudChallenge)) { // Set new fraud challenge FraudChallenge oldFraudChallenge = fraudChallenge; fraudChallenge = newFraudChallenge; // Emit event emit SetFraudChallengeEvent(oldFraudChallenge, newFraudChallenge); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier fraudChallengeInitialized() { require(address(fraudChallenge) != address(0), "Fraud challenge not initialized [FraudChallengable.sol:52]"); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title SettlementChallengeTypesLib * @dev Types for settlement challenges */ library SettlementChallengeTypesLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- enum Status {Qualified, Disqualified} struct Proposal { address wallet; uint256 nonce; uint256 referenceBlockNumber; uint256 definitionBlockNumber; uint256 expirationTime; // Status Status status; // Amounts Amounts amounts; // Currency MonetaryTypesLib.Currency currency; // Info on challenged driip Driip challenged; // True is equivalent to reward coming from wallet's balance bool walletInitiated; // True if proposal has been terminated bool terminated; // Disqualification Disqualification disqualification; } struct Amounts { // Cumulative (relative) transfer info int256 cumulativeTransfer; // Stage info int256 stage; // Balances after amounts have been staged int256 targetBalance; } struct Driip { // Kind ("payment", "trade", ...) string kind; // Hash (of operator) bytes32 hash; } struct Disqualification { // Challenger address challenger; uint256 nonce; uint256 blockNumber; // Info on candidate driip Driip candidate; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title NullSettlementChallengeState * @notice Where null settlements challenge state is managed */ contract NullSettlementChallengeState is Ownable, Servable, Configurable, BalanceTrackable { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; // // Constants // ----------------------------------------------------------------------------------------------------------------- string constant public INITIATE_PROPOSAL_ACTION = "initiate_proposal"; string constant public TERMINATE_PROPOSAL_ACTION = "terminate_proposal"; string constant public REMOVE_PROPOSAL_ACTION = "remove_proposal"; string constant public DISQUALIFY_PROPOSAL_ACTION = "disqualify_proposal"; // // Variables // ----------------------------------------------------------------------------------------------------------------- SettlementChallengeTypesLib.Proposal[] public proposals; mapping(address => mapping(address => mapping(uint256 => uint256))) public proposalIndexByWalletCurrency; // // Events // ----------------------------------------------------------------------------------------------------------------- event InitiateProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated); event TerminateProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated); event RemoveProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated); event DisqualifyProposalEvent(address challengedWallet, uint256 challangedNonce, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated, address challengerWallet, uint256 candidateNonce, bytes32 candidateHash, string candidateKind); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Get the number of proposals /// @return The number of proposals function proposalsCount() public view returns (uint256) { return proposals.length; } /// @notice Initiate a proposal /// @param wallet The address of the concerned challenged wallet /// @param nonce The wallet nonce /// @param stageAmount The proposal stage amount /// @param targetBalanceAmount The proposal target balance amount /// @param currency The concerned currency /// @param blockNumber The proposal block number /// @param walletInitiated True if initiated by the concerned challenged wallet function initiateProposal(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency memory currency, uint256 blockNumber, bool walletInitiated) public onlyEnabledServiceAction(INITIATE_PROPOSAL_ACTION) { // Initiate proposal _initiateProposal( wallet, nonce, stageAmount, targetBalanceAmount, currency, blockNumber, walletInitiated ); // Emit event emit InitiateProposalEvent( wallet, nonce, stageAmount, targetBalanceAmount, currency, blockNumber, walletInitiated ); } /// @notice Terminate a proposal /// @param wallet The address of the concerned challenged wallet /// @param currency The concerned currency function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency) public onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION) { // Get the proposal index uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; // Return gracefully if there is no proposal to terminate if (0 == index) return; // Terminate proposal proposals[index - 1].terminated = true; // Emit event emit TerminateProposalEvent( wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated ); } /// @notice Terminate a proposal /// @param wallet The address of the concerned challenged wallet /// @param currency The concerned currency /// @param walletTerminated True if wallet terminated function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated) public onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION) { // Get the proposal index uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; // Return gracefully if there is no proposal to terminate if (0 == index) return; // Require that role that initialized (wallet or operator) can only cancel its own proposal require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [NullSettlementChallengeState.sol:143]"); // Terminate proposal proposals[index - 1].terminated = true; // Emit event emit TerminateProposalEvent( wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated ); } /// @notice Remove a proposal /// @param wallet The address of the concerned challenged wallet /// @param currency The concerned currency function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency) public onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION) { // Get the proposal index uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; // Return gracefully if there is no proposal to remove if (0 == index) return; // Emit event emit RemoveProposalEvent( wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated ); // Remove proposal _removeProposal(index); } /// @notice Remove a proposal /// @param wallet The address of the concerned challenged wallet /// @param currency The concerned currency /// @param walletTerminated True if wallet terminated function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated) public onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION) { // Get the proposal index uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; // Return gracefully if there is no proposal to remove if (0 == index) return; // Require that role that initialized (wallet or operator) can only cancel its own proposal require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [NullSettlementChallengeState.sol:197]"); // Emit event emit RemoveProposalEvent( wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated ); // Remove proposal _removeProposal(index); } /// @notice Disqualify a proposal /// @dev A call to this function will intentionally override previous disqualifications if existent /// @param challengedWallet The address of the concerned challenged wallet /// @param currency The concerned currency /// @param challengerWallet The address of the concerned challenger wallet /// @param blockNumber The disqualification block number /// @param candidateNonce The candidate nonce /// @param candidateHash The candidate hash /// @param candidateKind The candidate kind function disqualifyProposal(address challengedWallet, MonetaryTypesLib.Currency memory currency, address challengerWallet, uint256 blockNumber, uint256 candidateNonce, bytes32 candidateHash, string memory candidateKind) public onlyEnabledServiceAction(DISQUALIFY_PROPOSAL_ACTION) { // Get the proposal index uint256 index = proposalIndexByWalletCurrency[challengedWallet][currency.ct][currency.id]; require(0 != index, "No settlement found for wallet and currency [NullSettlementChallengeState.sol:226]"); // Update proposal proposals[index - 1].status = SettlementChallengeTypesLib.Status.Disqualified; proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout()); proposals[index - 1].disqualification.challenger = challengerWallet; proposals[index - 1].disqualification.nonce = candidateNonce; proposals[index - 1].disqualification.blockNumber = blockNumber; proposals[index - 1].disqualification.candidate.hash = candidateHash; proposals[index - 1].disqualification.candidate.kind = candidateKind; // Emit event emit DisqualifyProposalEvent( challengedWallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated, challengerWallet, candidateNonce, candidateHash, candidateKind ); } /// @notice Gauge whether the proposal for the given wallet and currency has expired /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return true if proposal has expired, else false function hasProposal(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (bool) { // 1-based index return 0 != proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; } /// @notice Gauge whether the proposal for the given wallet and currency has terminated /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return true if proposal has terminated, else false function hasProposalTerminated(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (bool) { // 1-based index uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:269]"); return proposals[index - 1].terminated; } /// @notice Gauge whether the proposal for the given wallet and currency has expired /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return true if proposal has expired, else false function hasProposalExpired(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (bool) { // 1-based index uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:284]"); return block.timestamp >= proposals[index - 1].expirationTime; } /// @notice Get the settlement proposal challenge nonce of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal nonce function proposalNonce(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (uint256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:298]"); return proposals[index - 1].nonce; } /// @notice Get the settlement proposal reference block number of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal reference block number function proposalReferenceBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (uint256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:312]"); return proposals[index - 1].referenceBlockNumber; } /// @notice Get the settlement proposal definition block number of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal reference block number function proposalDefinitionBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (uint256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:326]"); return proposals[index - 1].definitionBlockNumber; } /// @notice Get the settlement proposal expiration time of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal expiration time function proposalExpirationTime(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (uint256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:340]"); return proposals[index - 1].expirationTime; } /// @notice Get the settlement proposal status of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal status function proposalStatus(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (SettlementChallengeTypesLib.Status) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:354]"); return proposals[index - 1].status; } /// @notice Get the settlement proposal stage amount of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal stage amount function proposalStageAmount(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (int256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:368]"); return proposals[index - 1].amounts.stage; } /// @notice Get the settlement proposal target balance amount of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal target balance amount function proposalTargetBalanceAmount(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (int256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:382]"); return proposals[index - 1].amounts.targetBalance; } /// @notice Get the settlement proposal balance reward of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal balance reward function proposalWalletInitiated(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (bool) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:396]"); return proposals[index - 1].walletInitiated; } /// @notice Get the settlement proposal disqualification challenger of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal disqualification challenger function proposalDisqualificationChallenger(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (address) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:410]"); return proposals[index - 1].disqualification.challenger; } /// @notice Get the settlement proposal disqualification block number of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal disqualification block number function proposalDisqualificationBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (uint256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:424]"); return proposals[index - 1].disqualification.blockNumber; } /// @notice Get the settlement proposal disqualification nonce of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal disqualification nonce function proposalDisqualificationNonce(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (uint256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:438]"); return proposals[index - 1].disqualification.nonce; } /// @notice Get the settlement proposal disqualification candidate hash of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal disqualification candidate hash function proposalDisqualificationCandidateHash(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (bytes32) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:452]"); return proposals[index - 1].disqualification.candidate.hash; } /// @notice Get the settlement proposal disqualification candidate kind of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal disqualification candidate kind function proposalDisqualificationCandidateKind(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (string memory) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:466]"); return proposals[index - 1].disqualification.candidate.kind; } // // Private functions // ----------------------------------------------------------------------------------------------------------------- function _initiateProposal(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency memory currency, uint256 referenceBlockNumber, bool walletInitiated) private { // Require that stage and target balance amounts are positive require(stageAmount.isPositiveInt256(), "Stage amount not positive [NullSettlementChallengeState.sol:478]"); require(targetBalanceAmount.isPositiveInt256(), "Target balance amount not positive [NullSettlementChallengeState.sol:479]"); uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; // Create proposal if needed if (0 == index) { index = ++(proposals.length); proposalIndexByWalletCurrency[wallet][currency.ct][currency.id] = index; } // Populate proposal proposals[index - 1].wallet = wallet; proposals[index - 1].nonce = nonce; proposals[index - 1].referenceBlockNumber = referenceBlockNumber; proposals[index - 1].definitionBlockNumber = block.number; proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout()); proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified; proposals[index - 1].currency = currency; proposals[index - 1].amounts.stage = stageAmount; proposals[index - 1].amounts.targetBalance = targetBalanceAmount; proposals[index - 1].walletInitiated = walletInitiated; proposals[index - 1].terminated = false; } function _removeProposal(uint256 index) private returns (bool) { // Remove the proposal and clear references to it proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0; if (index < proposals.length) { proposals[index - 1] = proposals[proposals.length - 1]; proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index; } proposals.length--; } function _activeBalanceLogEntry(address wallet, address currencyCt, uint256 currencyId) private view returns (int256 amount, uint256 blockNumber) { // Get last log record of deposited and settled balances (int256 depositedAmount, uint256 depositedBlockNumber) = balanceTracker.lastFungibleRecord( wallet, balanceTracker.depositedBalanceType(), currencyCt, currencyId ); (int256 settledAmount, uint256 settledBlockNumber) = balanceTracker.lastFungibleRecord( wallet, balanceTracker.settledBalanceType(), currencyCt, currencyId ); // Set amount as the sum of deposited and settled amount = depositedAmount.add(settledAmount); // Set block number as the latest of deposited and settled blockNumber = depositedBlockNumber > settledBlockNumber ? depositedBlockNumber : settledBlockNumber; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library BalanceTrackerLib { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; function fungibleActiveRecordByBlockNumber(BalanceTracker self, address wallet, MonetaryTypesLib.Currency memory currency, uint256 _blockNumber) internal view returns (int256 amount, uint256 blockNumber) { // Get log records of deposited and settled balances (int256 depositedAmount, uint256 depositedBlockNumber) = self.fungibleRecordByBlockNumber( wallet, self.depositedBalanceType(), currency.ct, currency.id, _blockNumber ); (int256 settledAmount, uint256 settledBlockNumber) = self.fungibleRecordByBlockNumber( wallet, self.settledBalanceType(), currency.ct, currency.id, _blockNumber ); // Return the sum of amounts and highest of block numbers amount = depositedAmount.add(settledAmount); blockNumber = depositedBlockNumber.clampMin(settledBlockNumber); } function fungibleActiveBalanceAmountByBlockNumber(BalanceTracker self, address wallet, MonetaryTypesLib.Currency memory currency, uint256 blockNumber) internal view returns (int256) { (int256 amount,) = fungibleActiveRecordByBlockNumber(self, wallet, currency, blockNumber); return amount; } function fungibleActiveDeltaBalanceAmountByBlockNumbers(BalanceTracker self, address wallet, MonetaryTypesLib.Currency memory currency, uint256 fromBlockNumber, uint256 toBlockNumber) internal view returns (int256) { return fungibleActiveBalanceAmountByBlockNumber(self, wallet, currency, toBlockNumber) - fungibleActiveBalanceAmountByBlockNumber(self, wallet, currency, fromBlockNumber); } // TODO Rename? function fungibleActiveRecord(BalanceTracker self, address wallet, MonetaryTypesLib.Currency memory currency) internal view returns (int256 amount, uint256 blockNumber) { // Get last log records of deposited and settled balances (int256 depositedAmount, uint256 depositedBlockNumber) = self.lastFungibleRecord( wallet, self.depositedBalanceType(), currency.ct, currency.id ); (int256 settledAmount, uint256 settledBlockNumber) = self.lastFungibleRecord( wallet, self.settledBalanceType(), currency.ct, currency.id ); // Return the sum of amounts and highest of block numbers amount = depositedAmount.add(settledAmount); blockNumber = depositedBlockNumber.clampMin(settledBlockNumber); } // TODO Rename? function fungibleActiveBalanceAmount(BalanceTracker self, address wallet, MonetaryTypesLib.Currency memory currency) internal view returns (int256) { return self.get(wallet, self.depositedBalanceType(), currency.ct, currency.id).add( self.get(wallet, self.settledBalanceType(), currency.ct, currency.id) ); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title NullSettlementDisputeByPayment * @notice The where payment related disputes of null settlement challenge happens */ contract NullSettlementDisputeByPayment is Ownable, Configurable, Validatable, SecurityBondable, WalletLockable, BalanceTrackable, FraudChallengable, Servable { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using BalanceTrackerLib for BalanceTracker; // // Constants // ----------------------------------------------------------------------------------------------------------------- string constant public CHALLENGE_BY_PAYMENT_ACTION = "challenge_by_payment"; // // Variables // ----------------------------------------------------------------------------------------------------------------- NullSettlementChallengeState public nullSettlementChallengeState; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetNullSettlementChallengeStateEvent(NullSettlementChallengeState oldNullSettlementChallengeState, NullSettlementChallengeState newNullSettlementChallengeState); event ChallengeByPaymentEvent(address wallet, uint256 nonce, PaymentTypesLib.Payment payment, address challenger); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } /// @notice Set the settlement challenge state contract /// @param newNullSettlementChallengeState The (address of) NullSettlementChallengeState contract instance function setNullSettlementChallengeState(NullSettlementChallengeState newNullSettlementChallengeState) public onlyDeployer notNullAddress(address(newNullSettlementChallengeState)) { NullSettlementChallengeState oldNullSettlementChallengeState = nullSettlementChallengeState; nullSettlementChallengeState = newNullSettlementChallengeState; emit SetNullSettlementChallengeStateEvent(oldNullSettlementChallengeState, nullSettlementChallengeState); } /// @notice Challenge the settlement by providing payment candidate /// @dev This challenges the payment sender's side of things /// @param wallet The wallet whose settlement is being challenged /// @param payment The payment candidate that challenges /// @param challenger The address of the challenger function challengeByPayment(address wallet, PaymentTypesLib.Payment memory payment, address challenger) public onlyEnabledServiceAction(CHALLENGE_BY_PAYMENT_ACTION) onlySealedPayment(payment) onlyPaymentSender(payment, wallet) { // Require that payment candidate is not labelled fraudulent require(!fraudChallenge.isFraudulentPaymentHash(payment.seals.operator.hash), "Payment deemed fraudulent [NullSettlementDisputeByPayment.sol:86]"); // Require that proposal has been initiated require(nullSettlementChallengeState.hasProposal(wallet, payment.currency), "No proposal found [NullSettlementDisputeByPayment.sol:89]"); // Require that proposal has not expired require(!nullSettlementChallengeState.hasProposalExpired(wallet, payment.currency), "Proposal found expired [NullSettlementDisputeByPayment.sol:92]"); // Require that payment party's nonce is strictly greater than proposal's nonce and its current // disqualification nonce require(payment.sender.nonce > nullSettlementChallengeState.proposalNonce( wallet, payment.currency ), "Payment nonce not strictly greater than proposal nonce [NullSettlementDisputeByPayment.sol:96]"); require(payment.sender.nonce > nullSettlementChallengeState.proposalDisqualificationNonce( wallet, payment.currency ), "Payment nonce not strictly greater than proposal disqualification nonce [NullSettlementDisputeByPayment.sol:99]"); // Require overrun for this payment to be a valid challenge candidate require(_overrun(wallet, payment), "No overrun found [NullSettlementDisputeByPayment.sol:104]"); // Reward challenger _settleRewards(wallet, payment.sender.balances.current, payment.currency, challenger); // Disqualify proposal, effectively overriding any previous disqualification nullSettlementChallengeState.disqualifyProposal( wallet, payment.currency, challenger, payment.blockNumber, payment.sender.nonce, payment.seals.operator.hash, PaymentTypesLib.PAYMENT_KIND() ); // Emit event emit ChallengeByPaymentEvent( wallet, nullSettlementChallengeState.proposalNonce(wallet, payment.currency), payment, challenger ); } // // Private functions // ----------------------------------------------------------------------------------------------------------------- function _overrun(address wallet, PaymentTypesLib.Payment memory payment) private view returns (bool) { // Get the target balance amount from the proposal int targetBalanceAmount = nullSettlementChallengeState.proposalTargetBalanceAmount( wallet, payment.currency ); // Get the change in active balance since the start of the challenge int256 deltaBalanceSinceStart = balanceTracker.fungibleActiveBalanceAmount( wallet, payment.currency ).sub( balanceTracker.fungibleActiveBalanceAmountByBlockNumber( wallet, payment.currency, nullSettlementChallengeState.proposalReferenceBlockNumber(wallet, payment.currency) ) ); // Get the cumulative transfer of the payment int256 cumulativeTransfer = balanceTracker.fungibleActiveBalanceAmountByBlockNumber( wallet, payment.currency, payment.blockNumber ).sub(payment.sender.balances.current); return targetBalanceAmount.add(deltaBalanceSinceStart) < cumulativeTransfer; } // Lock wallet's balances or reward challenger by stake fraction function _settleRewards(address wallet, int256 walletAmount, MonetaryTypesLib.Currency memory currency, address challenger) private { if (nullSettlementChallengeState.proposalWalletInitiated(wallet, currency)) _settleBalanceReward(wallet, walletAmount, currency, challenger); else _settleSecurityBondReward(wallet, walletAmount, currency, challenger); } function _settleBalanceReward(address wallet, int256 walletAmount, MonetaryTypesLib.Currency memory currency, address challenger) private { // Unlock wallet/currency for existing challenger if previously locked if (SettlementChallengeTypesLib.Status.Disqualified == nullSettlementChallengeState.proposalStatus( wallet, currency )) walletLocker.unlockFungibleByProxy( wallet, nullSettlementChallengeState.proposalDisqualificationChallenger( wallet, currency ), currency.ct, currency.id ); // Lock wallet for new challenger walletLocker.lockFungibleByProxy( wallet, challenger, walletAmount, currency.ct, currency.id, configuration.settlementChallengeTimeout() ); } // Settle the two-component reward from security bond. // The first component is flat figure as obtained from Configuration // The second component is progressive and calculated as // min(walletAmount, fraction of SecurityBond's deposited balance) // both amounts for the given currency function _settleSecurityBondReward(address wallet, int256 walletAmount, MonetaryTypesLib.Currency memory currency, address challenger) private { // Deprive existing challenger of reward if previously locked if (SettlementChallengeTypesLib.Status.Disqualified == nullSettlementChallengeState.proposalStatus( wallet, currency )) securityBond.depriveAbsolute( nullSettlementChallengeState.proposalDisqualificationChallenger( wallet, currency ), currency.ct, currency.id ); // Reward the flat component MonetaryTypesLib.Figure memory flatReward = _flatReward(); securityBond.rewardAbsolute( challenger, flatReward.amount, flatReward.currency.ct, flatReward.currency.id, 0 ); // Reward the progressive component int256 progressiveRewardAmount = walletAmount.clampMax( securityBond.depositedFractionalBalance( currency.ct, currency.id, configuration.operatorSettlementStakeFraction() ) ); securityBond.rewardAbsolute( challenger, progressiveRewardAmount, currency.ct, currency.id, 0 ); } function _flatReward() private view returns (MonetaryTypesLib.Figure memory) { (int256 amount, address currencyCt, uint256 currencyId) = configuration.operatorSettlementStake(); return MonetaryTypesLib.Figure(amount, MonetaryTypesLib.Currency(currencyCt, currencyId)); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title DriipSettlementChallengeState * @notice Where driip settlement challenge state is managed */ contract DriipSettlementChallengeState is Ownable, Servable, Configurable { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; // // Constants // ----------------------------------------------------------------------------------------------------------------- string constant public INITIATE_PROPOSAL_ACTION = "initiate_proposal"; string constant public TERMINATE_PROPOSAL_ACTION = "terminate_proposal"; string constant public REMOVE_PROPOSAL_ACTION = "remove_proposal"; string constant public DISQUALIFY_PROPOSAL_ACTION = "disqualify_proposal"; string constant public QUALIFY_PROPOSAL_ACTION = "qualify_proposal"; // // Variables // ----------------------------------------------------------------------------------------------------------------- SettlementChallengeTypesLib.Proposal[] public proposals; mapping(address => mapping(address => mapping(uint256 => uint256))) public proposalIndexByWalletCurrency; mapping(address => mapping(uint256 => mapping(address => mapping(uint256 => uint256)))) public proposalIndexByWalletNonceCurrency; // // Events // ----------------------------------------------------------------------------------------------------------------- event InitiateProposalEvent(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated, bytes32 challengedHash, string challengedKind); event TerminateProposalEvent(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated, bytes32 challengedHash, string challengedKind); event RemoveProposalEvent(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated, bytes32 challengedHash, string challengedKind); event DisqualifyProposalEvent(address challengedWallet, uint256 challengedNonce, int256 cumulativeTransferAmount, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated, address challengerWallet, uint256 candidateNonce, bytes32 candidateHash, string candidateKind); event QualifyProposalEvent(address challengedWallet, uint256 challengedNonce, int256 cumulativeTransferAmount, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated, address challengerWallet, uint256 candidateNonce, bytes32 candidateHash, string candidateKind); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Get the number of proposals /// @return The number of proposals function proposalsCount() public view returns (uint256) { return proposals.length; } /// @notice Initiate proposal /// @param wallet The address of the concerned challenged wallet /// @param nonce The wallet nonce /// @param cumulativeTransferAmount The proposal cumulative transfer amount /// @param stageAmount The proposal stage amount /// @param targetBalanceAmount The proposal target balance amount /// @param currency The concerned currency /// @param blockNumber The proposal block number /// @param walletInitiated True if reward from candidate balance /// @param challengedHash The candidate driip hash /// @param challengedKind The candidate driip kind function initiateProposal(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency memory currency, uint256 blockNumber, bool walletInitiated, bytes32 challengedHash, string memory challengedKind) public onlyEnabledServiceAction(INITIATE_PROPOSAL_ACTION) { // Initiate proposal _initiateProposal( wallet, nonce, cumulativeTransferAmount, stageAmount, targetBalanceAmount, currency, blockNumber, walletInitiated, challengedHash, challengedKind ); // Emit event emit InitiateProposalEvent( wallet, nonce, cumulativeTransferAmount, stageAmount, targetBalanceAmount, currency, blockNumber, walletInitiated, challengedHash, challengedKind ); } /// @notice Terminate a proposal /// @param wallet The address of the concerned challenged wallet /// @param currency The concerned currency function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool clearNonce) public onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION) { // Get the proposal index uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; // Return gracefully if there is no proposal to terminate if (0 == index) return; // Clear wallet-nonce-currency triplet entry, which enables reinitiation of proposal for that triplet if (clearNonce) proposalIndexByWalletNonceCurrency[wallet][proposals[index - 1].nonce][currency.ct][currency.id] = 0; // Terminate proposal proposals[index - 1].terminated = true; // Emit event emit TerminateProposalEvent( wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer, proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated, proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind ); } /// @notice Terminate a proposal /// @param wallet The address of the concerned challenged wallet /// @param currency The concerned currency /// @param clearNonce Clear wallet-nonce-currency triplet entry /// @param walletTerminated True if wallet terminated function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool clearNonce, bool walletTerminated) public onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION) { // Get the proposal index uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; // Return gracefully if there is no proposal to terminate if (0 == index) return; // Require that role that initialized (wallet or operator) can only cancel its own proposal require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [DriipSettlementChallengeState.sol:163]"); // Clear wallet-nonce-currency triplet entry, which enables reinitiation of proposal for that triplet if (clearNonce) proposalIndexByWalletNonceCurrency[wallet][proposals[index - 1].nonce][currency.ct][currency.id] = 0; // Terminate proposal proposals[index - 1].terminated = true; // Emit event emit TerminateProposalEvent( wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer, proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated, proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind ); } /// @notice Remove a proposal /// @param wallet The address of the concerned challenged wallet /// @param currency The concerned currency function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency) public onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION) { // Get the proposal index uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; // Return gracefully if there is no proposal to remove if (0 == index) return; // Emit event emit RemoveProposalEvent( wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer, proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated, proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind ); // Remove proposal _removeProposal(index); } /// @notice Remove a proposal /// @param wallet The address of the concerned challenged wallet /// @param currency The concerned currency /// @param walletTerminated True if wallet terminated function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated) public onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION) { // Get the proposal index uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; // Return gracefully if there is no proposal to remove if (0 == index) return; // Require that role that initialized (wallet or operator) can only cancel its own proposal require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [DriipSettlementChallengeState.sol:223]"); // Emit event emit RemoveProposalEvent( wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer, proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated, proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind ); // Remove proposal _removeProposal(index); } /// @notice Disqualify a proposal /// @dev A call to this function will intentionally override previous disqualifications if existent /// @param challengedWallet The address of the concerned challenged wallet /// @param currency The concerned currency /// @param challengerWallet The address of the concerned challenger wallet /// @param blockNumber The disqualification block number /// @param candidateNonce The candidate nonce /// @param candidateHash The candidate hash /// @param candidateKind The candidate kind function disqualifyProposal(address challengedWallet, MonetaryTypesLib.Currency memory currency, address challengerWallet, uint256 blockNumber, uint256 candidateNonce, bytes32 candidateHash, string memory candidateKind) public onlyEnabledServiceAction(DISQUALIFY_PROPOSAL_ACTION) { // Get the proposal index uint256 index = proposalIndexByWalletCurrency[challengedWallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:253]"); // Update proposal proposals[index - 1].status = SettlementChallengeTypesLib.Status.Disqualified; proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout()); proposals[index - 1].disqualification.challenger = challengerWallet; proposals[index - 1].disqualification.nonce = candidateNonce; proposals[index - 1].disqualification.blockNumber = blockNumber; proposals[index - 1].disqualification.candidate.hash = candidateHash; proposals[index - 1].disqualification.candidate.kind = candidateKind; // Emit event emit DisqualifyProposalEvent( challengedWallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer, proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated, challengerWallet, candidateNonce, candidateHash, candidateKind ); } /// @notice (Re)Qualify a proposal /// @param wallet The address of the concerned challenged wallet /// @param currency The concerned currency function qualifyProposal(address wallet, MonetaryTypesLib.Currency memory currency) public onlyEnabledServiceAction(QUALIFY_PROPOSAL_ACTION) { // Get the proposal index uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:282]"); // Emit event emit QualifyProposalEvent( wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer, proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated, proposals[index - 1].disqualification.challenger, proposals[index - 1].disqualification.nonce, proposals[index - 1].disqualification.candidate.hash, proposals[index - 1].disqualification.candidate.kind ); // Update proposal proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified; proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout()); delete proposals[index - 1].disqualification; } /// @notice Gauge whether a driip settlement challenge for the given wallet-nonce-currency /// triplet has been proposed and not later removed /// @param wallet The address of the concerned wallet /// @param nonce The wallet nonce /// @param currency The concerned currency /// @return true if driip settlement challenge has been, else false function hasProposal(address wallet, uint256 nonce, MonetaryTypesLib.Currency memory currency) public view returns (bool) { // 1-based index return 0 != proposalIndexByWalletNonceCurrency[wallet][nonce][currency.ct][currency.id]; } /// @notice Gauge whether the proposal for the given wallet and currency has expired /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return true if proposal has expired, else false function hasProposal(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (bool) { // 1-based index return 0 != proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; } /// @notice Gauge whether the proposal for the given wallet and currency has terminated /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return true if proposal has terminated, else false function hasProposalTerminated(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (bool) { // 1-based index uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:340]"); return proposals[index - 1].terminated; } /// @notice Gauge whether the proposal for the given wallet and currency has expired /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return true if proposal has expired, else false function hasProposalExpired(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (bool) { // 1-based index uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:355]"); return block.timestamp >= proposals[index - 1].expirationTime; } /// @notice Get the proposal nonce of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal nonce function proposalNonce(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (uint256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:369]"); return proposals[index - 1].nonce; } /// @notice Get the proposal reference block number of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal reference block number function proposalReferenceBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (uint256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:383]"); return proposals[index - 1].referenceBlockNumber; } /// @notice Get the proposal definition block number of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal definition block number function proposalDefinitionBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (uint256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:397]"); return proposals[index - 1].definitionBlockNumber; } /// @notice Get the proposal expiration time of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal expiration time function proposalExpirationTime(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (uint256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:411]"); return proposals[index - 1].expirationTime; } /// @notice Get the proposal status of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal status function proposalStatus(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (SettlementChallengeTypesLib.Status) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:425]"); return proposals[index - 1].status; } /// @notice Get the proposal cumulative transfer amount of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal cumulative transfer amount function proposalCumulativeTransferAmount(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (int256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:439]"); return proposals[index - 1].amounts.cumulativeTransfer; } /// @notice Get the proposal stage amount of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal stage amount function proposalStageAmount(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (int256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:453]"); return proposals[index - 1].amounts.stage; } /// @notice Get the proposal target balance amount of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal target balance amount function proposalTargetBalanceAmount(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (int256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:467]"); return proposals[index - 1].amounts.targetBalance; } /// @notice Get the proposal challenged hash of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal challenged hash function proposalChallengedHash(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (bytes32) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:481]"); return proposals[index - 1].challenged.hash; } /// @notice Get the proposal challenged kind of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal challenged kind function proposalChallengedKind(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (string memory) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:495]"); return proposals[index - 1].challenged.kind; } /// @notice Get the proposal balance reward of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal balance reward function proposalWalletInitiated(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (bool) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:509]"); return proposals[index - 1].walletInitiated; } /// @notice Get the proposal disqualification challenger of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal disqualification challenger function proposalDisqualificationChallenger(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (address) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:523]"); return proposals[index - 1].disqualification.challenger; } /// @notice Get the proposal disqualification nonce of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal disqualification nonce function proposalDisqualificationNonce(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (uint256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:537]"); return proposals[index - 1].disqualification.nonce; } /// @notice Get the proposal disqualification block number of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal disqualification block number function proposalDisqualificationBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (uint256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:551]"); return proposals[index - 1].disqualification.blockNumber; } /// @notice Get the proposal disqualification candidate hash of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal disqualification candidate hash function proposalDisqualificationCandidateHash(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (bytes32) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:565]"); return proposals[index - 1].disqualification.candidate.hash; } /// @notice Get the proposal disqualification candidate kind of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal disqualification candidate kind function proposalDisqualificationCandidateKind(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (string memory) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:579]"); return proposals[index - 1].disqualification.candidate.kind; } // // Private functions // ----------------------------------------------------------------------------------------------------------------- function _initiateProposal(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency memory currency, uint256 referenceBlockNumber, bool walletInitiated, bytes32 challengedHash, string memory challengedKind) private { // Require that there is no other proposal on the given wallet-nonce-currency triplet require( 0 == proposalIndexByWalletNonceCurrency[wallet][nonce][currency.ct][currency.id], "Existing proposal found for wallet, nonce and currency [DriipSettlementChallengeState.sol:592]" ); // Require that stage and target balance amounts are positive require(stageAmount.isPositiveInt256(), "Stage amount not positive [DriipSettlementChallengeState.sol:598]"); require(targetBalanceAmount.isPositiveInt256(), "Target balance amount not positive [DriipSettlementChallengeState.sol:599]"); uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; // Create proposal if needed if (0 == index) { index = ++(proposals.length); proposalIndexByWalletCurrency[wallet][currency.ct][currency.id] = index; } // Populate proposal proposals[index - 1].wallet = wallet; proposals[index - 1].nonce = nonce; proposals[index - 1].referenceBlockNumber = referenceBlockNumber; proposals[index - 1].definitionBlockNumber = block.number; proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout()); proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified; proposals[index - 1].currency = currency; proposals[index - 1].amounts.cumulativeTransfer = cumulativeTransferAmount; proposals[index - 1].amounts.stage = stageAmount; proposals[index - 1].amounts.targetBalance = targetBalanceAmount; proposals[index - 1].walletInitiated = walletInitiated; proposals[index - 1].terminated = false; proposals[index - 1].challenged.hash = challengedHash; proposals[index - 1].challenged.kind = challengedKind; // Update index of wallet-nonce-currency triplet proposalIndexByWalletNonceCurrency[wallet][nonce][currency.ct][currency.id] = index; } function _removeProposal(uint256 index) private { // Remove the proposal and clear references to it proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0; proposalIndexByWalletNonceCurrency[proposals[index - 1].wallet][proposals[index - 1].nonce][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0; if (index < proposals.length) { proposals[index - 1] = proposals[proposals.length - 1]; proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index; proposalIndexByWalletNonceCurrency[proposals[index - 1].wallet][proposals[index - 1].nonce][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index; } proposals.length--; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title NullSettlementChallengeByPayment * @notice Where null settlements pertaining to payments are started and disputed */ contract NullSettlementChallengeByPayment is Ownable, ConfigurableOperational, BalanceTrackable, WalletLockable { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using BalanceTrackerLib for BalanceTracker; // // Variables // ----------------------------------------------------------------------------------------------------------------- NullSettlementDisputeByPayment public nullSettlementDisputeByPayment; NullSettlementChallengeState public nullSettlementChallengeState; DriipSettlementChallengeState public driipSettlementChallengeState; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetNullSettlementDisputeByPaymentEvent(NullSettlementDisputeByPayment oldNullSettlementDisputeByPayment, NullSettlementDisputeByPayment newNullSettlementDisputeByPayment); event SetNullSettlementChallengeStateEvent(NullSettlementChallengeState oldNullSettlementChallengeState, NullSettlementChallengeState newNullSettlementChallengeState); event SetDriipSettlementChallengeStateEvent(DriipSettlementChallengeState oldDriipSettlementChallengeState, DriipSettlementChallengeState newDriipSettlementChallengeState); event StartChallengeEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount, address currencyCt, uint currencyId); event StartChallengeByProxyEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount, address currencyCt, uint currencyId, address proxy); event StopChallengeEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount, address currencyCt, uint256 currencyId); event StopChallengeByProxyEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount, address currencyCt, uint256 currencyId, address proxy); event ChallengeByPaymentEvent(address challengedWallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount, address currencyCt, uint256 currencyId, address challengerWallet); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the settlement dispute contract /// @param newNullSettlementDisputeByPayment The (address of) NullSettlementDisputeByPayment contract instance function setNullSettlementDisputeByPayment(NullSettlementDisputeByPayment newNullSettlementDisputeByPayment) public onlyDeployer notNullAddress(address(newNullSettlementDisputeByPayment)) { NullSettlementDisputeByPayment oldNullSettlementDisputeByPayment = nullSettlementDisputeByPayment; nullSettlementDisputeByPayment = newNullSettlementDisputeByPayment; emit SetNullSettlementDisputeByPaymentEvent(oldNullSettlementDisputeByPayment, nullSettlementDisputeByPayment); } /// @notice Set the null settlement challenge state contract /// @param newNullSettlementChallengeState The (address of) NullSettlementChallengeState contract instance function setNullSettlementChallengeState(NullSettlementChallengeState newNullSettlementChallengeState) public onlyDeployer notNullAddress(address(newNullSettlementChallengeState)) { NullSettlementChallengeState oldNullSettlementChallengeState = nullSettlementChallengeState; nullSettlementChallengeState = newNullSettlementChallengeState; emit SetNullSettlementChallengeStateEvent(oldNullSettlementChallengeState, nullSettlementChallengeState); } /// @notice Set the driip settlement challenge state contract /// @param newDriipSettlementChallengeState The (address of) DriipSettlementChallengeState contract instance function setDriipSettlementChallengeState(DriipSettlementChallengeState newDriipSettlementChallengeState) public onlyDeployer notNullAddress(address(newDriipSettlementChallengeState)) { DriipSettlementChallengeState oldDriipSettlementChallengeState = driipSettlementChallengeState; driipSettlementChallengeState = newDriipSettlementChallengeState; emit SetDriipSettlementChallengeStateEvent(oldDriipSettlementChallengeState, driipSettlementChallengeState); } /// @notice Start settlement challenge /// @param amount The concerned amount to stage /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function startChallenge(int256 amount, address currencyCt, uint256 currencyId) public { // Require that wallet is not locked require(!walletLocker.isLocked(msg.sender), "Wallet found locked [NullSettlementChallengeByPayment.sol:116]"); // Define currency MonetaryTypesLib.Currency memory currency = MonetaryTypesLib.Currency(currencyCt, currencyId); // Start challenge for wallet _startChallenge(msg.sender, amount, currency, true); // Emit event emit StartChallengeEvent( msg.sender, nullSettlementChallengeState.proposalNonce(msg.sender, currency), amount, nullSettlementChallengeState.proposalTargetBalanceAmount(msg.sender, currency), currencyCt, currencyId ); } /// @notice Start settlement challenge for the given wallet /// @param wallet The address of the concerned wallet /// @param amount The concerned amount to stage /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function startChallengeByProxy(address wallet, int256 amount, address currencyCt, uint256 currencyId) public onlyOperator { // Define currency MonetaryTypesLib.Currency memory currency = MonetaryTypesLib.Currency(currencyCt, currencyId); // Start challenge for wallet _startChallenge(wallet, amount, currency, false); // Emit event emit StartChallengeByProxyEvent( wallet, nullSettlementChallengeState.proposalNonce(wallet, currency), amount, nullSettlementChallengeState.proposalTargetBalanceAmount(wallet, currency), currencyCt, currencyId, msg.sender ); } /// @notice Stop settlement challenge /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function stopChallenge(address currencyCt, uint256 currencyId) public { // Define currency MonetaryTypesLib.Currency memory currency = MonetaryTypesLib.Currency(currencyCt, currencyId); // Stop challenge _stopChallenge(msg.sender, currency, true); // Emit event emit StopChallengeEvent( msg.sender, nullSettlementChallengeState.proposalNonce(msg.sender, currency), nullSettlementChallengeState.proposalStageAmount(msg.sender, currency), nullSettlementChallengeState.proposalTargetBalanceAmount(msg.sender, currency), currencyCt, currencyId ); } /// @notice Stop settlement challenge /// @param wallet The concerned wallet /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function stopChallengeByProxy(address wallet, address currencyCt, uint256 currencyId) public onlyOperator { // Define currency MonetaryTypesLib.Currency memory currency = MonetaryTypesLib.Currency(currencyCt, currencyId); // Stop challenge _stopChallenge(wallet, currency, false); // Emit event emit StopChallengeByProxyEvent( wallet, nullSettlementChallengeState.proposalNonce(wallet, currency), nullSettlementChallengeState.proposalStageAmount(wallet, currency), nullSettlementChallengeState.proposalTargetBalanceAmount(wallet, currency), currencyCt, currencyId, msg.sender ); } /// @notice Gauge whether the proposal for the given wallet and currency has been defined /// @param wallet The address of the concerned wallet /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return true if proposal has been initiated, else false function hasProposal(address wallet, address currencyCt, uint256 currencyId) public view returns (bool) { return nullSettlementChallengeState.hasProposal( wallet, MonetaryTypesLib.Currency(currencyCt, currencyId) ); } /// @notice Gauge whether the proposal for the given wallet and currency has terminated /// @param wallet The address of the concerned wallet /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return true if proposal has terminated, else false function hasProposalTerminated(address wallet, address currencyCt, uint256 currencyId) public view returns (bool) { return nullSettlementChallengeState.hasProposalTerminated( wallet, MonetaryTypesLib.Currency(currencyCt, currencyId) ); } /// @notice Gauge whether the proposal for the given wallet and currency has expired /// @param wallet The address of the concerned wallet /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return true if proposal has expired, else false function hasProposalExpired(address wallet, address currencyCt, uint256 currencyId) public view returns (bool) { return nullSettlementChallengeState.hasProposalExpired( wallet, MonetaryTypesLib.Currency(currencyCt, currencyId) ); } /// @notice Get the challenge nonce of the given wallet /// @param wallet The address of the concerned wallet /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The challenge nonce function proposalNonce(address wallet, address currencyCt, uint256 currencyId) public view returns (uint256) { return nullSettlementChallengeState.proposalNonce( wallet, MonetaryTypesLib.Currency(currencyCt, currencyId) ); } /// @notice Get the settlement proposal block number of the given wallet /// @param wallet The address of the concerned wallet /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The settlement proposal block number function proposalReferenceBlockNumber(address wallet, address currencyCt, uint256 currencyId) public view returns (uint256) { return nullSettlementChallengeState.proposalReferenceBlockNumber( wallet, MonetaryTypesLib.Currency(currencyCt, currencyId) ); } /// @notice Get the settlement proposal end time of the given wallet /// @param wallet The address of the concerned wallet /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The settlement proposal end time function proposalExpirationTime(address wallet, address currencyCt, uint256 currencyId) public view returns (uint256) { return nullSettlementChallengeState.proposalExpirationTime( wallet, MonetaryTypesLib.Currency(currencyCt, currencyId) ); } /// @notice Get the challenge status of the given wallet /// @param wallet The address of the concerned wallet /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The challenge status function proposalStatus(address wallet, address currencyCt, uint256 currencyId) public view returns (SettlementChallengeTypesLib.Status) { return nullSettlementChallengeState.proposalStatus( wallet, MonetaryTypesLib.Currency(currencyCt, currencyId) ); } /// @notice Get the settlement proposal stage amount of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The settlement proposal stage amount function proposalStageAmount(address wallet, address currencyCt, uint256 currencyId) public view returns (int256) { return nullSettlementChallengeState.proposalStageAmount( wallet, MonetaryTypesLib.Currency(currencyCt, currencyId) ); } /// @notice Get the settlement proposal target balance amount of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The settlement proposal target balance amount function proposalTargetBalanceAmount(address wallet, address currencyCt, uint256 currencyId) public view returns (int256) { return nullSettlementChallengeState.proposalTargetBalanceAmount( wallet, MonetaryTypesLib.Currency(currencyCt, currencyId) ); } /// @notice Get the balance reward of the given wallet's settlement proposal /// @param wallet The address of the concerned wallet /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The balance reward of the settlement proposal function proposalWalletInitiated(address wallet, address currencyCt, uint256 currencyId) public view returns (bool) { return nullSettlementChallengeState.proposalWalletInitiated( wallet, MonetaryTypesLib.Currency(currencyCt, currencyId) ); } /// @notice Get the disqualification challenger of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The challenger of the settlement disqualification function proposalDisqualificationChallenger(address wallet, address currencyCt, uint256 currencyId) public view returns (address) { return nullSettlementChallengeState.proposalDisqualificationChallenger( wallet, MonetaryTypesLib.Currency(currencyCt, currencyId) ); } /// @notice Get the disqualification block number of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The block number of the settlement disqualification function proposalDisqualificationBlockNumber(address wallet, address currencyCt, uint256 currencyId) public view returns (uint256) { return nullSettlementChallengeState.proposalDisqualificationBlockNumber( wallet, MonetaryTypesLib.Currency(currencyCt, currencyId) ); } /// @notice Get the disqualification candidate kind of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The candidate kind of the settlement disqualification function proposalDisqualificationCandidateKind(address wallet, address currencyCt, uint256 currencyId) public view returns (string memory) { return nullSettlementChallengeState.proposalDisqualificationCandidateKind( wallet, MonetaryTypesLib.Currency(currencyCt, currencyId) ); } /// @notice Get the disqualification candidate hash of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The candidate hash of the settlement disqualification function proposalDisqualificationCandidateHash(address wallet, address currencyCt, uint256 currencyId) public view returns (bytes32) { return nullSettlementChallengeState.proposalDisqualificationCandidateHash( wallet, MonetaryTypesLib.Currency(currencyCt, currencyId) ); } /// @notice Challenge the settlement by providing payment candidate /// @param wallet The wallet whose settlement is being challenged /// @param payment The payment candidate that challenges the null function challengeByPayment(address wallet, PaymentTypesLib.Payment memory payment) public onlyOperationalModeNormal { // Challenge by payment nullSettlementDisputeByPayment.challengeByPayment(wallet, payment, msg.sender); // Emit event emit ChallengeByPaymentEvent( wallet, nullSettlementChallengeState.proposalNonce(wallet, payment.currency), nullSettlementChallengeState.proposalStageAmount(wallet, payment.currency), nullSettlementChallengeState.proposalTargetBalanceAmount(wallet, payment.currency), payment.currency.ct, payment.currency.id, msg.sender ); } // // Private functions // ----------------------------------------------------------------------------------------------------------------- function _startChallenge(address wallet, int256 stageAmount, MonetaryTypesLib.Currency memory currency, bool walletInitiated) private { // Require that current block number is beyond the earliest settlement challenge block number require( block.number >= configuration.earliestSettlementBlockNumber(), "Current block number below earliest settlement block number [NullSettlementChallengeByPayment.sol:443]" ); // Require that there is no ongoing overlapping null settlement challenge require( !nullSettlementChallengeState.hasProposal(wallet, currency) || nullSettlementChallengeState.hasProposalExpired(wallet, currency), "Overlapping null settlement challenge proposal found [NullSettlementChallengeByPayment.sol:449]" ); // Get the last logged active balance amount and block number, properties of overlapping DSC // and the baseline nonce ( int256 activeBalanceAmount, uint256 activeBalanceBlockNumber, int256 dscCumulativeTransferAmount, int256 dscStageAmount, uint256 nonce ) = _externalProperties( wallet, currency ); // Initiate proposal, including assurance that there is no overlap with active proposal // Target balance amount is calculated as current balance - DSC cumulativeTransferAmount - DSC stage amount - NSC stageAmount nullSettlementChallengeState.initiateProposal( wallet, nonce, stageAmount, activeBalanceAmount.sub( dscCumulativeTransferAmount.add(dscStageAmount).add(stageAmount) ), currency, activeBalanceBlockNumber, walletInitiated ); } function _stopChallenge(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated) private { // Require that there is an unterminated driip settlement challenge proposal require(nullSettlementChallengeState.hasProposal(wallet, currency), "No proposal found [NullSettlementChallengeByPayment.sol:481]"); require(!nullSettlementChallengeState.hasProposalTerminated(wallet, currency), "Proposal found terminated [NullSettlementChallengeByPayment.sol:482]"); // Terminate driip settlement challenge proposal nullSettlementChallengeState.terminateProposal( wallet, currency, walletTerminated ); } function _externalProperties(address wallet, MonetaryTypesLib.Currency memory currency) private view returns ( int256 activeBalanceAmount, uint256 activeBalanceBlockNumber, int256 dscCumulativeTransferAmount, int256 dscStageAmount, uint256 nonce ) { (activeBalanceAmount, activeBalanceBlockNumber) = balanceTracker.fungibleActiveRecord( wallet, currency ); if (driipSettlementChallengeState.hasProposal(wallet, currency)) { if (!driipSettlementChallengeState.hasProposalTerminated(wallet, currency)) { dscCumulativeTransferAmount = driipSettlementChallengeState.proposalCumulativeTransferAmount(wallet, currency); dscStageAmount = driipSettlementChallengeState.proposalStageAmount(wallet, currency); } nonce = driipSettlementChallengeState.proposalNonce(wallet, currency); } if (nullSettlementChallengeState.hasProposal(wallet, currency)) nonce = nonce.clampMin(nullSettlementChallengeState.proposalNonce(wallet, currency)); } }
Gauge whether the given service is authorized for the given wallet service The address of the concerned registered service wallet The address of the concerned wallet return true if service is authorized for the given wallet, else false
function isAuthorizedRegisteredService(address service, address wallet) public view returns (bool) { return isRegisteredActiveService(service) && (isInitialServiceAuthorizedForWallet(service, wallet) || serviceWalletAuthorizedMap[service][wallet]); }
12,574,518
//! FrozenToken ECR20-compliant token contract //! By Parity Technologies, 2017. //! Released under the Apache Licence 2. pragma solidity ^0.4.17; // Owned contract. contract Owned { modifier only_owner { require (msg.sender == owner); _; } event NewOwner(address indexed old, address indexed current); function setOwner(address _new) public only_owner { NewOwner(owner, _new); owner = _new; } address public owner; } // FrozenToken, a bit like an ECR20 token (though not - as it doesn't // implement most of the API). // All token balances are generally non-transferable. // All "tokens" belong to the owner (who is uniquely liquid) at construction. // Liquid accounts can make other accounts liquid and send their tokens // to other axccounts. contract FrozenToken is Owned { event Transfer(address indexed from, address indexed to, uint256 value); // this is as basic as can be, only the associated balance & allowances struct Account { uint balance; bool liquid; } // constructor sets the parameters of execution, _totalSupply is all units function FrozenToken(uint _totalSupply, address _owner) public when_non_zero(_totalSupply) { totalSupply = _totalSupply; owner = _owner; accounts[_owner].balance = totalSupply; accounts[_owner].liquid = true; } // balance of a specific address function balanceOf(address _who) public constant returns (uint256) { return accounts[_who].balance; } // make an account liquid: only liquid accounts can do this. function makeLiquid(address _to) public when_liquid(msg.sender) returns(bool) { accounts[_to].liquid = true; return true; } // transfer function transfer(address _to, uint256 _value) public when_owns(msg.sender, _value) when_liquid(msg.sender) returns(bool) { Transfer(msg.sender, _to, _value); accounts[msg.sender].balance -= _value; accounts[_to].balance += _value; return true; } // no default function, simple contract only, entry-level users function() public { assert(false); } // the balance should be available modifier when_owns(address _owner, uint _amount) { require (accounts[_owner].balance >= _amount); _; } modifier when_liquid(address who) { require (accounts[who].liquid); _; } // a value should be > 0 modifier when_non_zero(uint _value) { require (_value > 0); _; } // Available token supply uint public totalSupply; // Storage and mapping of all balances & allowances mapping (address => Account) accounts; // Conventional metadata. string public constant name = "Frozen Token"; string public constant symbol = "FRZ"; uint8 public constant decimals = 3; }
constructor sets the parameters of execution, _totalSupply is all units
function FrozenToken(uint _totalSupply, address _owner) public when_non_zero(_totalSupply) { totalSupply = _totalSupply; owner = _owner; accounts[_owner].balance = totalSupply; accounts[_owner].liquid = true; }
12,533,594
./full_match/43114/0x4bD45738e0735f015F77a5aBfEDf368E251555aB/sources/IDOBUSD.sol
Calculates amount of tokens to be bought for given bnb purchaseAmountWei amount in wei return amount of tokens that can be bought for given purchaseAmountInWei/
function calculatePurchaseAmount(uint purchaseAmountWei) public view returns(uint256) { return purchaseAmountWei.mul(1e6).div(salePrice); }
4,547,741
pragma solidity 0.4.24; contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } /** * @title SchedulerInterface * @dev The base contract that the higher contracts: BaseScheduler, BlockScheduler and TimestampScheduler all inherit from. */ contract SchedulerInterface { function schedule(address _toAddress, bytes _callData, uint[8] _uintArgs) public payable returns (address); function computeEndowment(uint _bounty, uint _fee, uint _callGas, uint _callValue, uint _gasPrice) public view returns (uint); } contract TransactionRequestInterface { // Primary actions function execute() public returns (bool); function cancel() public returns (bool); function claim() public payable returns (bool); // Proxy function function proxy(address recipient, bytes callData) public payable returns (bool); // Data accessors function requestData() public view returns (address[6], bool[3], uint[15], uint8[1]); function callData() public view returns (bytes); // Pull mechanisms for payments. function refundClaimDeposit() public returns (bool); function sendFee() public returns (bool); function sendBounty() public returns (bool); function sendOwnerEther() public returns (bool); function sendOwnerEther(address recipient) public returns (bool); } contract TransactionRequestCore is TransactionRequestInterface { using RequestLib for RequestLib.Request; using RequestScheduleLib for RequestScheduleLib.ExecutionWindow; RequestLib.Request txnRequest; bool private initialized = false; /* * addressArgs[0] - meta.createdBy * addressArgs[1] - meta.owner * addressArgs[2] - paymentData.feeRecipient * addressArgs[3] - txnData.toAddress * * uintArgs[0] - paymentData.fee * uintArgs[1] - paymentData.bounty * uintArgs[2] - schedule.claimWindowSize * uintArgs[3] - schedule.freezePeriod * uintArgs[4] - schedule.reservedWindowSize * uintArgs[5] - schedule.temporalUnit * uintArgs[6] - schedule.windowSize * uintArgs[7] - schedule.windowStart * uintArgs[8] - txnData.callGas * uintArgs[9] - txnData.callValue * uintArgs[10] - txnData.gasPrice * uintArgs[11] - claimData.requiredDeposit */ function initialize( address[4] addressArgs, uint[12] uintArgs, bytes callData ) public payable { require(!initialized); txnRequest.initialize(addressArgs, uintArgs, callData); initialized = true; } /* * Allow receiving ether. This is needed if there is a large increase in * network gas prices. */ function() public payable {} /* * Actions */ function execute() public returns (bool) { return txnRequest.execute(); } function cancel() public returns (bool) { return txnRequest.cancel(); } function claim() public payable returns (bool) { return txnRequest.claim(); } /* * Data accessor functions. */ // Declaring this function `view`, although it creates a compiler warning, is // necessary to return values from it. function requestData() public view returns (address[6], bool[3], uint[15], uint8[1]) { return txnRequest.serialize(); } function callData() public view returns (bytes data) { data = txnRequest.txnData.callData; } /** * @dev Proxy a call from this contract to another contract. * This function is only callable by the scheduler and can only * be called after the execution window ends. One purpose is to * provide a way to transfer assets held by this contract somewhere else. * For example, if this request was used to buy tokens during an ICO, * it would become the owner of the tokens and this function would need * to be called with the encoded data to the token contract to transfer * the assets somewhere else. */ function proxy(address _to, bytes _data) public payable returns (bool success) { require(txnRequest.meta.owner == msg.sender && txnRequest.schedule.isAfterWindow()); /* solium-disable-next-line */ return _to.call.value(msg.value)(_data); } /* * Pull based payment functions. */ function refundClaimDeposit() public returns (bool) { txnRequest.refundClaimDeposit(); } function sendFee() public returns (bool) { return txnRequest.sendFee(); } function sendBounty() public returns (bool) { return txnRequest.sendBounty(); } function sendOwnerEther() public returns (bool) { return txnRequest.sendOwnerEther(); } function sendOwnerEther(address recipient) public returns (bool) { return txnRequest.sendOwnerEther(recipient); } /** Event duplication from RequestLib.sol. This is so * that these events are available on the contracts ABI.*/ event Aborted(uint8 reason); event Cancelled(uint rewardPayment, uint measuredGasConsumption); event Claimed(); event Executed(uint bounty, uint fee, uint measuredGasConsumption); } contract RequestFactoryInterface { event RequestCreated(address request, address indexed owner, int indexed bucket, uint[12] params); function createRequest(address[3] addressArgs, uint[12] uintArgs, bytes callData) public payable returns (address); function createValidatedRequest(address[3] addressArgs, uint[12] uintArgs, bytes callData) public payable returns (address); function validateRequestParams(address[3] addressArgs, uint[12] uintArgs, uint endowment) public view returns (bool[6]); function isKnownRequest(address _address) public view returns (bool); } contract TransactionRecorder { address owner; bool public wasCalled; uint public lastCallValue; address public lastCaller; bytes public lastCallData = ""; uint public lastCallGas; function TransactionRecorder() public { owner = msg.sender; } function() payable public { lastCallGas = gasleft(); lastCallData = msg.data; lastCaller = msg.sender; lastCallValue = msg.value; wasCalled = true; } function __reset__() public { lastCallGas = 0; lastCallData = ""; lastCaller = 0x0; lastCallValue = 0; wasCalled = false; } function kill() public { require(msg.sender == owner); selfdestruct(owner); } } contract Proxy { SchedulerInterface public scheduler; address public receipient; address public scheduledTransaction; address public owner; function Proxy(address _scheduler, address _receipient, uint _payout, uint _gasPrice, uint _delay) public payable { scheduler = SchedulerInterface(_scheduler); receipient = _receipient; owner = msg.sender; scheduledTransaction = scheduler.schedule.value(msg.value)( this, // toAddress "", // callData [ 2000000, // The amount of gas to be sent with the transaction. _payout, // The amount of wei to be sent. 255, // The size of the execution window. block.number + _delay, // The start of the execution window. _gasPrice, // The gasprice for the transaction 12345 wei, // The fee included in the transaction. 224455 wei, // The bounty that awards the executor of the transaction. 20000 wei // The required amount of wei the claimer must send as deposit. ] ); } function () public payable { if (msg.value > 0) { receipient.transfer(msg.value); } } function sendOwnerEther(address _receipient) public { if (msg.sender == owner && _receipient != 0x0) { TransactionRequestInterface(scheduledTransaction).sendOwnerEther(_receipient); } } } /// Super simple token contract that moves funds into the owner account on creation and /// only exposes an API to be used for `test/proxy.js` contract SimpleToken { address public owner; mapping(address => uint) balances; function SimpleToken (uint _initialSupply) public { owner = msg.sender; balances[owner] = _initialSupply; } function transfer (address _to, uint _amount) public returns (bool success) { require(balances[msg.sender] > _amount); balances[msg.sender] -= _amount; balances[_to] += _amount; success = true; } uint public constant rate = 30; function buyTokens() public payable returns (bool success) { require(msg.value > 0); balances[msg.sender] += msg.value * rate; success = true; } function balanceOf (address _who) public view returns (uint balance) { balance = balances[_who]; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // require(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // require(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) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } /** * @title BaseScheduler * @dev The foundational contract which provides the API for scheduling future transactions on the Alarm Client. */ contract BaseScheduler is SchedulerInterface { // The RequestFactory which produces requests for this scheduler. address public factoryAddress; // The TemporalUnit (Block or Timestamp) for this scheduler. RequestScheduleLib.TemporalUnit public temporalUnit; // The address which will be sent the fee payments. address public feeRecipient; /* * @dev Fallback function to be able to receive ether. This can occur * legitimately when scheduling fails due to a validation error. */ function() public payable {} /// Event that bubbles up the address of new requests made with this scheduler. event NewRequest(address request); /** * @dev Schedules a new TransactionRequest using the 'full' parameters. * @param _toAddress The address destination of the transaction. * @param _callData The bytecode that will be included with the transaction. * @param _uintArgs [0] The callGas of the transaction. * @param _uintArgs [1] The value of ether to be sent with the transaction. * @param _uintArgs [2] The size of the execution window of the transaction. * @param _uintArgs [3] The (block or timestamp) of when the execution window starts. * @param _uintArgs [4] The gasPrice which will be used to execute this transaction. * @param _uintArgs [5] The fee attached to this transaction. * @param _uintArgs [6] The bounty attached to this transaction. * @param _uintArgs [7] The deposit required to claim this transaction. * @return The address of the new TransactionRequest. */ function schedule ( address _toAddress, bytes _callData, uint[8] _uintArgs ) public payable returns (address newRequest) { RequestFactoryInterface factory = RequestFactoryInterface(factoryAddress); uint endowment = computeEndowment( _uintArgs[6], //bounty _uintArgs[5], //fee _uintArgs[0], //callGas _uintArgs[1], //callValue _uintArgs[4] //gasPrice ); require(msg.value >= endowment); if (temporalUnit == RequestScheduleLib.TemporalUnit.Blocks) { newRequest = factory.createValidatedRequest.value(msg.value)( [ msg.sender, // meta.owner feeRecipient, // paymentData.feeRecipient _toAddress // txnData.toAddress ], [ _uintArgs[5], // paymentData.fee _uintArgs[6], // paymentData.bounty 255, // scheduler.claimWindowSize 10, // scheduler.freezePeriod 16, // scheduler.reservedWindowSize uint(temporalUnit), // scheduler.temporalUnit (1: block, 2: timestamp) _uintArgs[2], // scheduler.windowSize _uintArgs[3], // scheduler.windowStart _uintArgs[0], // txnData.callGas _uintArgs[1], // txnData.callValue _uintArgs[4], // txnData.gasPrice _uintArgs[7] // claimData.requiredDeposit ], _callData ); } else if (temporalUnit == RequestScheduleLib.TemporalUnit.Timestamp) { newRequest = factory.createValidatedRequest.value(msg.value)( [ msg.sender, // meta.owner feeRecipient, // paymentData.feeRecipient _toAddress // txnData.toAddress ], [ _uintArgs[5], // paymentData.fee _uintArgs[6], // paymentData.bounty 60 minutes, // scheduler.claimWindowSize 3 minutes, // scheduler.freezePeriod 5 minutes, // scheduler.reservedWindowSize uint(temporalUnit), // scheduler.temporalUnit (1: block, 2: timestamp) _uintArgs[2], // scheduler.windowSize _uintArgs[3], // scheduler.windowStart _uintArgs[0], // txnData.callGas _uintArgs[1], // txnData.callValue _uintArgs[4], // txnData.gasPrice _uintArgs[7] // claimData.requiredDeposit ], _callData ); } else { // unsupported temporal unit revert(); } require(newRequest != 0x0); emit NewRequest(newRequest); return newRequest; } function computeEndowment( uint _bounty, uint _fee, uint _callGas, uint _callValue, uint _gasPrice ) public view returns (uint) { return PaymentLib.computeEndowment( _bounty, _fee, _callGas, _callValue, _gasPrice, RequestLib.getEXECUTION_GAS_OVERHEAD() ); } } /** * @title BlockScheduler * @dev Top-level contract that exposes the API to the Ethereum Alarm Clock service and passes in blocks as temporal unit. */ contract BlockScheduler is BaseScheduler { /** * @dev Constructor * @param _factoryAddress Address of the RequestFactory which creates requests for this scheduler. */ constructor(address _factoryAddress, address _feeRecipient) public { require(_factoryAddress != 0x0); // Default temporal unit is block number. temporalUnit = RequestScheduleLib.TemporalUnit.Blocks; // Sets the factoryAddress variable found in BaseScheduler contract. factoryAddress = _factoryAddress; // Sets the fee recipient for these schedulers. feeRecipient = _feeRecipient; } } /** * @title TimestampScheduler * @dev Top-level contract that exposes the API to the Ethereum Alarm Clock service and passes in timestamp as temporal unit. */ contract TimestampScheduler is BaseScheduler { /** * @dev Constructor * @param _factoryAddress Address of the RequestFactory which creates requests for this scheduler. */ constructor(address _factoryAddress, address _feeRecipient) public { require(_factoryAddress != 0x0); // Default temporal unit is timestamp. temporalUnit = RequestScheduleLib.TemporalUnit.Timestamp; // Sets the factoryAddress variable found in BaseScheduler contract. factoryAddress = _factoryAddress; // Sets the fee recipient for these schedulers. feeRecipient = _feeRecipient; } } /// Truffle-specific contract (Not a part of the EAC) contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) { _; } } function Migrations() public { owner = msg.sender; } function setCompleted(uint completed) restricted public { last_completed_migration = completed; } function upgrade(address new_address) restricted public { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } /** * @title ExecutionLib * @dev Contains the logic for executing a scheduled transaction. */ library ExecutionLib { struct ExecutionData { address toAddress; /// The destination of the transaction. bytes callData; /// The bytecode that will be sent with the transaction. uint callValue; /// The wei value that will be sent with the transaction. uint callGas; /// The amount of gas to be sent with the transaction. uint gasPrice; /// The gasPrice that should be set for the transaction. } /** * @dev Send the transaction according to the parameters outlined in ExecutionData. * @param self The ExecutionData object. */ function sendTransaction(ExecutionData storage self) internal returns (bool) { /// Should never actually reach this require check, but here in case. require(self.gasPrice <= tx.gasprice); /* solium-disable security/no-call-value */ return self.toAddress.call.value(self.callValue).gas(self.callGas)(self.callData); } /** * Returns the maximum possible gas consumption that a transaction request * may consume. The EXTRA_GAS value represents the overhead involved in * request execution. */ function CALL_GAS_CEILING(uint EXTRA_GAS) internal view returns (uint) { return block.gaslimit - EXTRA_GAS; } /* * @dev Validation: ensure that the callGas is not above the total possible gas * for a call. */ function validateCallGas(uint callGas, uint EXTRA_GAS) internal view returns (bool) { return callGas < CALL_GAS_CEILING(EXTRA_GAS); } /* * @dev Validation: ensure that the toAddress is not set to the empty address. */ function validateToAddress(address toAddress) internal pure returns (bool) { return toAddress != 0x0; } } library MathLib { uint constant INT_MAX = 57896044618658097711785492504343953926634992332820282019728792003956564819967; // 2**255 - 1 /* * Subtracts b from a in a manner such that zero is returned when an * underflow condition is met. */ // function flooredSub(uint a, uint b) returns (uint) { // if (b >= a) { // return 0; // } else { // return a - b; // } // } // /* // * Adds b to a in a manner that throws an exception when overflow // * conditions are met. // */ // function safeAdd(uint a, uint b) returns (uint) { // if (a + b >= a) { // return a + b; // } else { // throw; // } // } // /* // * Multiplies a by b in a manner that throws an exception when overflow // * conditions are met. // */ // function safeMultiply(uint a, uint b) returns (uint) { // var result = a * b; // if (b == 0 || result / b == a) { // return a * b; // } else { // throw; // } // } /* * Return the larger of a or b. Returns a if a == b. */ function max(uint a, uint b) public pure returns (uint) { if (a >= b) { return a; } else { return b; } } /* * Return the larger of a or b. Returns a if a == b. */ function min(uint a, uint b) public pure returns (uint) { if (a <= b) { return a; } else { return b; } } /* * Returns a represented as a signed integer in a manner that throw an * exception if casting to signed integer would result in a negative * number. */ function safeCastSigned(uint a) public pure returns (int) { assert(a <= INT_MAX); return int(a); } } /** * @title RequestMetaLib * @dev Small library holding all the metadata about a TransactionRequest. */ library RequestMetaLib { struct RequestMeta { address owner; /// The address that created this request. address createdBy; /// The address of the RequestFactory which created this request. bool isCancelled; /// Was the TransactionRequest cancelled? bool wasCalled; /// Was the TransactionRequest called? bool wasSuccessful; /// Was the return value from the TransactionRequest execution successful? } } library RequestLib { using ClaimLib for ClaimLib.ClaimData; using ExecutionLib for ExecutionLib.ExecutionData; using PaymentLib for PaymentLib.PaymentData; using RequestMetaLib for RequestMetaLib.RequestMeta; using RequestScheduleLib for RequestScheduleLib.ExecutionWindow; using SafeMath for uint; struct Request { ExecutionLib.ExecutionData txnData; RequestMetaLib.RequestMeta meta; PaymentLib.PaymentData paymentData; ClaimLib.ClaimData claimData; RequestScheduleLib.ExecutionWindow schedule; } enum AbortReason { WasCancelled, //0 AlreadyCalled, //1 BeforeCallWindow, //2 AfterCallWindow, //3 ReservedForClaimer, //4 InsufficientGas, //5 TooLowGasPrice //6 } event Aborted(uint8 reason); event Cancelled(uint rewardPayment, uint measuredGasConsumption); event Claimed(); event Executed(uint bounty, uint fee, uint measuredGasConsumption); /** * @dev Validate the initialization parameters of a transaction request. */ function validate( address[4] _addressArgs, uint[12] _uintArgs, uint _endowment ) public view returns (bool[6] isValid) { // The order of these errors matters as it determines which // ValidationError event codes are logged when validation fails. isValid[0] = PaymentLib.validateEndowment( _endowment, _uintArgs[1], //bounty _uintArgs[0], //fee _uintArgs[8], //callGas _uintArgs[9], //callValue _uintArgs[10], //gasPrice EXECUTION_GAS_OVERHEAD ); isValid[1] = RequestScheduleLib.validateReservedWindowSize( _uintArgs[4], //reservedWindowSize _uintArgs[6] //windowSize ); isValid[2] = RequestScheduleLib.validateTemporalUnit(_uintArgs[5]); isValid[3] = RequestScheduleLib.validateWindowStart( RequestScheduleLib.TemporalUnit(MathLib.min(_uintArgs[5], 2)), _uintArgs[3], //freezePeriod _uintArgs[7] //windowStart ); isValid[4] = ExecutionLib.validateCallGas( _uintArgs[8], //callGas EXECUTION_GAS_OVERHEAD ); isValid[5] = ExecutionLib.validateToAddress(_addressArgs[3]); return isValid; } /** * @dev Initialize a new Request. */ function initialize( Request storage self, address[4] _addressArgs, uint[12] _uintArgs, bytes _callData ) public returns (bool) { address[6] memory addressValues = [ 0x0, // self.claimData.claimedBy _addressArgs[0], // self.meta.createdBy _addressArgs[1], // self.meta.owner _addressArgs[2], // self.paymentData.feeRecipient 0x0, // self.paymentData.bountyBenefactor _addressArgs[3] // self.txnData.toAddress ]; bool[3] memory boolValues = [false, false, false]; uint[15] memory uintValues = [ 0, // self.claimData.claimDeposit _uintArgs[0], // self.paymentData.fee 0, // self.paymentData.feeOwed _uintArgs[1], // self.paymentData.bounty 0, // self.paymentData.bountyOwed _uintArgs[2], // self.schedule.claimWindowSize _uintArgs[3], // self.schedule.freezePeriod _uintArgs[4], // self.schedule.reservedWindowSize _uintArgs[5], // self.schedule.temporalUnit _uintArgs[6], // self.schedule.windowSize _uintArgs[7], // self.schedule.windowStart _uintArgs[8], // self.txnData.callGas _uintArgs[9], // self.txnData.callValue _uintArgs[10], // self.txnData.gasPrice _uintArgs[11] // self.claimData.requiredDeposit ]; uint8[1] memory uint8Values = [ 0 ]; require(deserialize(self, addressValues, boolValues, uintValues, uint8Values, _callData)); return true; } function serialize(Request storage self) internal view returns(address[6], bool[3], uint[15], uint8[1]) { address[6] memory addressValues = [ self.claimData.claimedBy, self.meta.createdBy, self.meta.owner, self.paymentData.feeRecipient, self.paymentData.bountyBenefactor, self.txnData.toAddress ]; bool[3] memory boolValues = [ self.meta.isCancelled, self.meta.wasCalled, self.meta.wasSuccessful ]; uint[15] memory uintValues = [ self.claimData.claimDeposit, self.paymentData.fee, self.paymentData.feeOwed, self.paymentData.bounty, self.paymentData.bountyOwed, self.schedule.claimWindowSize, self.schedule.freezePeriod, self.schedule.reservedWindowSize, uint(self.schedule.temporalUnit), self.schedule.windowSize, self.schedule.windowStart, self.txnData.callGas, self.txnData.callValue, self.txnData.gasPrice, self.claimData.requiredDeposit ]; uint8[1] memory uint8Values = [ self.claimData.paymentModifier ]; return (addressValues, boolValues, uintValues, uint8Values); } /** * @dev Populates a Request object from the full output of `serialize`. * * Parameter order is alphabetical by type, then namespace, then name. */ function deserialize( Request storage self, address[6] _addressValues, bool[3] _boolValues, uint[15] _uintValues, uint8[1] _uint8Values, bytes _callData ) internal returns (bool) { // callData is special. self.txnData.callData = _callData; // Address values self.claimData.claimedBy = _addressValues[0]; self.meta.createdBy = _addressValues[1]; self.meta.owner = _addressValues[2]; self.paymentData.feeRecipient = _addressValues[3]; self.paymentData.bountyBenefactor = _addressValues[4]; self.txnData.toAddress = _addressValues[5]; // Boolean values self.meta.isCancelled = _boolValues[0]; self.meta.wasCalled = _boolValues[1]; self.meta.wasSuccessful = _boolValues[2]; // UInt values self.claimData.claimDeposit = _uintValues[0]; self.paymentData.fee = _uintValues[1]; self.paymentData.feeOwed = _uintValues[2]; self.paymentData.bounty = _uintValues[3]; self.paymentData.bountyOwed = _uintValues[4]; self.schedule.claimWindowSize = _uintValues[5]; self.schedule.freezePeriod = _uintValues[6]; self.schedule.reservedWindowSize = _uintValues[7]; self.schedule.temporalUnit = RequestScheduleLib.TemporalUnit(_uintValues[8]); self.schedule.windowSize = _uintValues[9]; self.schedule.windowStart = _uintValues[10]; self.txnData.callGas = _uintValues[11]; self.txnData.callValue = _uintValues[12]; self.txnData.gasPrice = _uintValues[13]; self.claimData.requiredDeposit = _uintValues[14]; // Uint8 values self.claimData.paymentModifier = _uint8Values[0]; return true; } function execute(Request storage self) internal returns (bool) { /* * Execute the TransactionRequest * * +---------------------+ * | Phase 1: Validation | * +---------------------+ * * Must pass all of the following checks: * * 1. Not already called. * 2. Not cancelled. * 3. Not before the execution window. * 4. Not after the execution window. * 5. if (claimedBy == 0x0 or msg.sender == claimedBy): * - windowStart <= block.number * - block.number <= windowStart + windowSize * else if (msg.sender != claimedBy): * - windowStart + reservedWindowSize <= block.number * - block.number <= windowStart + windowSize * else: * - throw (should be impossible) * * 6. gasleft() == callGas * 7. tx.gasprice >= txnData.gasPrice * * +--------------------+ * | Phase 2: Execution | * +--------------------+ * * 1. Mark as called (must be before actual execution to prevent * re-entrance) * 2. Send Transaction and record success or failure. * * +---------------------+ * | Phase 3: Accounting | * +---------------------+ * * 1. Calculate and send fee amount. * 2. Calculate and send bounty amount. * 3. Send remaining ether back to owner. * */ // Record the gas at the beginning of the transaction so we can // calculate how much has been used later. uint startGas = gasleft(); // +----------------------+ // | Begin: Authorization | // +----------------------+ if (gasleft() < requiredExecutionGas(self).sub(PRE_EXECUTION_GAS)) { emit Aborted(uint8(AbortReason.InsufficientGas)); return false; } else if (self.meta.wasCalled) { emit Aborted(uint8(AbortReason.AlreadyCalled)); return false; } else if (self.meta.isCancelled) { emit Aborted(uint8(AbortReason.WasCancelled)); return false; } else if (self.schedule.isBeforeWindow()) { emit Aborted(uint8(AbortReason.BeforeCallWindow)); return false; } else if (self.schedule.isAfterWindow()) { emit Aborted(uint8(AbortReason.AfterCallWindow)); return false; } else if (self.claimData.isClaimed() && msg.sender != self.claimData.claimedBy && self.schedule.inReservedWindow()) { emit Aborted(uint8(AbortReason.ReservedForClaimer)); return false; } else if (self.txnData.gasPrice > tx.gasprice) { emit Aborted(uint8(AbortReason.TooLowGasPrice)); return false; } // +--------------------+ // | End: Authorization | // +--------------------+ // +------------------+ // | Begin: Execution | // +------------------+ // Mark as being called before sending transaction to prevent re-entrance. self.meta.wasCalled = true; // Send the transaction... // The transaction is allowed to fail and the executing agent will still get the bounty. // `.sendTransaction()` will return false on a failed exeuction. self.meta.wasSuccessful = self.txnData.sendTransaction(); // +----------------+ // | End: Execution | // +----------------+ // +-------------------+ // | Begin: Accounting | // +-------------------+ // Compute the fee amount if (self.paymentData.hasFeeRecipient()) { self.paymentData.feeOwed = self.paymentData.getFee() .add(self.paymentData.feeOwed); } // Record this locally so that we can log it later. // `.sendFee()` below will change `self.paymentData.feeOwed` to 0 to prevent re-entrance. uint totalFeePayment = self.paymentData.feeOwed; // Send the fee. This transaction may also fail but can be called again after // execution. self.paymentData.sendFee(); // Compute the bounty amount. self.paymentData.bountyBenefactor = msg.sender; if (self.claimData.isClaimed()) { // If the transaction request was claimed, we add the deposit to the bounty whether // or not the same agent who claimed is executing. self.paymentData.bountyOwed = self.claimData.claimDeposit .add(self.paymentData.bountyOwed); // To prevent re-entrance we zero out the claim deposit since it is now accounted for // in the bounty value. self.claimData.claimDeposit = 0; // Depending on when the transaction request was claimed, we apply the modifier to the // bounty payment and add it to the bounty already owed. self.paymentData.bountyOwed = self.paymentData.getBountyWithModifier(self.claimData.paymentModifier) .add(self.paymentData.bountyOwed); } else { // Not claimed. Just add the full bounty. self.paymentData.bountyOwed = self.paymentData.getBounty().add(self.paymentData.bountyOwed); } // Take down the amount of gas used so far in execution to compensate the executing agent. uint measuredGasConsumption = startGas.sub(gasleft()).add(EXECUTE_EXTRA_GAS); // // +----------------------------------------------------------------------+ // // | NOTE: All code after this must be accounted for by EXECUTE_EXTRA_GAS | // // +----------------------------------------------------------------------+ // Add the gas reimbursment amount to the bounty. self.paymentData.bountyOwed = measuredGasConsumption .mul(self.txnData.gasPrice) .add(self.paymentData.bountyOwed); // Log the bounty and fee. Otherwise it is non-trivial to figure // out how much was payed. emit Executed(self.paymentData.bountyOwed, totalFeePayment, measuredGasConsumption); // Attempt to send the bounty. as with `.sendFee()` it may fail and need to be caled after execution. self.paymentData.sendBounty(); // If any ether is left, send it back to the owner of the transaction request. _sendOwnerEther(self, self.meta.owner); // +-----------------+ // | End: Accounting | // +-----------------+ // Successful return true; } // This is the amount of gas that it takes to enter from the // `TransactionRequest.execute()` contract into the `RequestLib.execute()` // method at the point where the gas check happens. uint public constant PRE_EXECUTION_GAS = 25000; // TODO is this number still accurate? /* * The amount of gas needed to complete the execute method after * the transaction has been sent. */ uint public constant EXECUTION_GAS_OVERHEAD = 180000; // TODO check accuracy of this number /* * The amount of gas used by the portion of the `execute` function * that cannot be accounted for via gas tracking. */ uint public constant EXECUTE_EXTRA_GAS = 90000; // again, check for accuracy... Doubled this from Piper's original - Logan /* * Constant value to account for the gas usage that cannot be accounted * for using gas-tracking within the `cancel` function. */ uint public constant CANCEL_EXTRA_GAS = 85000; // Check accuracy function getEXECUTION_GAS_OVERHEAD() public pure returns (uint) { return EXECUTION_GAS_OVERHEAD; } function requiredExecutionGas(Request storage self) public view returns (uint requiredGas) { requiredGas = self.txnData.callGas.add(EXECUTION_GAS_OVERHEAD); } /* * @dev Performs the checks to see if a request can be cancelled. * Must satisfy the following conditions. * * 1. Not Cancelled * 2. either: * * not wasCalled && afterExecutionWindow * * not claimed && beforeFreezeWindow && msg.sender == owner */ function isCancellable(Request storage self) public view returns (bool) { if (self.meta.isCancelled) { // already cancelled! return false; } else if (!self.meta.wasCalled && self.schedule.isAfterWindow()) { // not called but after the window return true; } else if (!self.claimData.isClaimed() && self.schedule.isBeforeFreeze() && msg.sender == self.meta.owner) { // not claimed and before freezePeriod and owner is cancelling return true; } else { // otherwise cannot cancel return false; } } /* * Cancel the transaction request, attempting to send all appropriate * refunds. To incentivise cancellation by other parties, a small reward * payment is issued to the party that cancels the request if they are not * the owner. */ function cancel(Request storage self) public returns (bool) { uint startGas = gasleft(); uint rewardPayment; uint measuredGasConsumption; // Checks if this transactionRequest can be cancelled. require(isCancellable(self)); // Set here to prevent re-entrance attacks. self.meta.isCancelled = true; // Refund the claim deposit (if there is one) require(self.claimData.refundDeposit()); // Send a reward to the cancelling agent if they are not the owner. // This is to incentivize the cancelling of expired transaction requests. // This also guarantees that it is being cancelled after the call window // since the `isCancellable()` function checks this. if (msg.sender != self.meta.owner) { // Create the rewardBenefactor address rewardBenefactor = msg.sender; // Create the rewardOwed variable, it is one-hundredth // of the bounty. uint rewardOwed = self.paymentData.bountyOwed .add(self.paymentData.bounty.div(100)); // Calculate the amount of gas cancelling agent used in this transaction. measuredGasConsumption = startGas .sub(gasleft()) .add(CANCEL_EXTRA_GAS); // Add their gas fees to the reward.W rewardOwed = measuredGasConsumption .mul(tx.gasprice) .add(rewardOwed); // Take note of the rewardPayment to log it. rewardPayment = rewardOwed; // Transfers the rewardPayment. if (rewardOwed > 0) { self.paymentData.bountyOwed = 0; rewardBenefactor.transfer(rewardOwed); } } // Log it! emit Cancelled(rewardPayment, measuredGasConsumption); // Send the remaining ether to the owner. return sendOwnerEther(self); } /* * @dev Performs some checks to verify that a transaction request is claimable. * @param self The Request object. */ function isClaimable(Request storage self) internal view returns (bool) { // Require not claimed and not cancelled. require(!self.claimData.isClaimed()); require(!self.meta.isCancelled); // Require that it's in the claim window and the value sent is over the required deposit. require(self.schedule.inClaimWindow()); require(msg.value >= self.claimData.requiredDeposit); return true; } /* * @dev Claims the request. * @param self The Request object. * Payable because it requires the sender to send enough ether to cover the claimDeposit. */ function claim(Request storage self) internal returns (bool claimed) { require(isClaimable(self)); emit Claimed(); return self.claimData.claim(self.schedule.computePaymentModifier()); } /* * @dev Refund claimer deposit. */ function refundClaimDeposit(Request storage self) public returns (bool) { require(self.meta.isCancelled || self.schedule.isAfterWindow()); return self.claimData.refundDeposit(); } /* * Send fee. Wrapper over the real function that perform an extra * check to see if it's after the execution window (and thus the first transaction failed) */ function sendFee(Request storage self) public returns (bool) { if (self.schedule.isAfterWindow()) { return self.paymentData.sendFee(); } return false; } /* * Send bounty. Wrapper over the real function that performs an extra * check to see if it's after execution window (and thus the first transaction failed) */ function sendBounty(Request storage self) public returns (bool) { /// check wasCalled if (self.schedule.isAfterWindow()) { return self.paymentData.sendBounty(); } return false; } function canSendOwnerEther(Request storage self) public view returns(bool) { return self.meta.isCancelled || self.schedule.isAfterWindow() || self.meta.wasCalled; } /** * Send owner ether. Wrapper over the real function that performs an extra * check to see if it's after execution window (and thus the first transaction failed) */ function sendOwnerEther(Request storage self, address recipient) public returns (bool) { require(recipient != 0x0); if(canSendOwnerEther(self) && msg.sender == self.meta.owner) { return _sendOwnerEther(self, recipient); } return false; } /** * Send owner ether. Wrapper over the real function that performs an extra * check to see if it's after execution window (and thus the first transaction failed) */ function sendOwnerEther(Request storage self) public returns (bool) { if(canSendOwnerEther(self)) { return _sendOwnerEther(self, self.meta.owner); } return false; } function _sendOwnerEther(Request storage self, address recipient) private returns (bool) { // Note! This does not do any checks since it is used in the execute function. // The public version of the function should be used for checks and in the cancel function. uint ownerRefund = address(this).balance .sub(self.claimData.claimDeposit) .sub(self.paymentData.bountyOwed) .sub(self.paymentData.feeOwed); /* solium-disable security/no-send */ return recipient.send(ownerRefund); } } /** * @title RequestScheduleLib * @dev Library containing the logic for request scheduling. */ library RequestScheduleLib { using SafeMath for uint; /** * The manner in which this schedule specifies time. * * Null: present to require this value be explicitely specified * Blocks: execution schedule determined by block.number * Timestamp: execution schedule determined by block.timestamp */ enum TemporalUnit { Null, // 0 Blocks, // 1 Timestamp // 2 } struct ExecutionWindow { TemporalUnit temporalUnit; /// The type of unit used to measure time. uint windowStart; /// The starting point in temporal units from which the transaction can be executed. uint windowSize; /// The length in temporal units of the execution time period. uint freezePeriod; /// The length in temporal units before the windowStart where no activity is allowed. uint reservedWindowSize; /// The length in temporal units at the beginning of the executionWindow in which only the claim address can execute. uint claimWindowSize; /// The length in temporal units before the freezeperiod in which an address can claim the execution. } /** * @dev Get the `now` represented in the temporal units assigned to this request. * @param self The ExecutionWindow object. * @return The unsigned integer representation of `now` in appropiate temporal units. */ function getNow(ExecutionWindow storage self) public view returns (uint) { return _getNow(self.temporalUnit); } /** * @dev Internal function to return the `now` based on the appropiate temporal units. * @param _temporalUnit The assigned TemporalUnit to this transaction. */ function _getNow(TemporalUnit _temporalUnit) internal view returns (uint) { if (_temporalUnit == TemporalUnit.Timestamp) { return block.timestamp; } if (_temporalUnit == TemporalUnit.Blocks) { return block.number; } /// Only reaches here if the unit is unset, unspecified or unsupported. revert(); } /** * @dev The modifier that will be applied to the bounty value depending * on when a call was claimed. */ function computePaymentModifier(ExecutionWindow storage self) internal view returns (uint8) { uint paymentModifier = (getNow(self).sub(firstClaimBlock(self))) .mul(100) .div(self.claimWindowSize); assert(paymentModifier <= 100); return uint8(paymentModifier); } /* * Helper: computes the end of the execution window. */ function windowEnd(ExecutionWindow storage self) internal view returns (uint) { return self.windowStart.add(self.windowSize); } /* * Helper: computes the end of the reserved portion of the execution * window. */ function reservedWindowEnd(ExecutionWindow storage self) internal view returns (uint) { return self.windowStart.add(self.reservedWindowSize); } /* * Helper: computes the time when the request will be frozen until execution. */ function freezeStart(ExecutionWindow storage self) internal view returns (uint) { return self.windowStart.sub(self.freezePeriod); } /* * Helper: computes the time when the request will be frozen until execution. */ function firstClaimBlock(ExecutionWindow storage self) internal view returns (uint) { return freezeStart(self).sub(self.claimWindowSize); } /* * Helper: Returns boolean if we are before the execution window. */ function isBeforeWindow(ExecutionWindow storage self) internal view returns (bool) { return getNow(self) < self.windowStart; } /* * Helper: Returns boolean if we are after the execution window. */ function isAfterWindow(ExecutionWindow storage self) internal view returns (bool) { return getNow(self) > windowEnd(self); } /* * Helper: Returns boolean if we are inside the execution window. */ function inWindow(ExecutionWindow storage self) internal view returns (bool) { return self.windowStart <= getNow(self) && getNow(self) < windowEnd(self); } /* * Helper: Returns boolean if we are inside the reserved portion of the * execution window. */ function inReservedWindow(ExecutionWindow storage self) internal view returns (bool) { return self.windowStart <= getNow(self) && getNow(self) < reservedWindowEnd(self); } /* * @dev Helper: Returns boolean if we are inside the claim window. */ function inClaimWindow(ExecutionWindow storage self) internal view returns (bool) { /// Checks that the firstClaimBlock is in the past or now. /// Checks that now is before the start of the freezePeriod. return firstClaimBlock(self) <= getNow(self) && getNow(self) < freezeStart(self); } /* * Helper: Returns boolean if we are before the freeze period. */ function isBeforeFreeze(ExecutionWindow storage self) internal view returns (bool) { return getNow(self) < freezeStart(self); } /* * Helper: Returns boolean if we are before the claim window. */ function isBeforeClaimWindow(ExecutionWindow storage self) internal view returns (bool) { return getNow(self) < firstClaimBlock(self); } ///--------------- /// VALIDATION ///--------------- /** * @dev Validation: Ensure that the reservedWindowSize is less than or equal to the windowSize. * @param _reservedWindowSize The size of the reserved window. * @param _windowSize The size of the execution window. * @return True if the reservedWindowSize is within the windowSize. */ function validateReservedWindowSize(uint _reservedWindowSize, uint _windowSize) public pure returns (bool) { return _reservedWindowSize <= _windowSize; } /** * @dev Validation: Ensure that the startWindow is at least freezePeriod amount of time in the future. * @param _temporalUnit The temporalUnit of this request. * @param _freezePeriod The freezePeriod in temporal units. * @param _windowStart The time in the future which represents the start of the execution window. * @return True if the windowStart is at least freezePeriod amount of time in the future. */ function validateWindowStart(TemporalUnit _temporalUnit, uint _freezePeriod, uint _windowStart) public view returns (bool) { return _getNow(_temporalUnit).add(_freezePeriod) <= _windowStart; } /* * Validation: ensure that the temporal unit passed in is constrained to 0 or 1 */ function validateTemporalUnit(uint _temporalUnitAsUInt) public pure returns (bool) { return (_temporalUnitAsUInt != uint(TemporalUnit.Null) && (_temporalUnitAsUInt == uint(TemporalUnit.Blocks) || _temporalUnitAsUInt == uint(TemporalUnit.Timestamp)) ); } } library ClaimLib { struct ClaimData { address claimedBy; // The address that has claimed the txRequest. uint claimDeposit; // The deposit amount that was put down by the claimer. uint requiredDeposit; // The required deposit to claim the txRequest. uint8 paymentModifier; // An integer constrained between 0-100 that will be applied to the // request payment as a percentage. } /* * @dev Mark the request as being claimed. * @param self The ClaimData that is being accessed. * @param paymentModifier The payment modifier. */ function claim( ClaimData storage self, uint8 _paymentModifier ) internal returns (bool) { self.claimedBy = msg.sender; self.claimDeposit = msg.value; self.paymentModifier = _paymentModifier; return true; } /* * Helper: returns whether this request is claimed. */ function isClaimed(ClaimData storage self) internal view returns (bool) { return self.claimedBy != 0x0; } /* * @dev Refund the claim deposit to claimer. * @param self The Request.ClaimData * Called in RequestLib's `cancel()` and `refundClaimDeposit()` */ function refundDeposit(ClaimData storage self) internal returns (bool) { // Check that the claim deposit is non-zero. if (self.claimDeposit > 0) { uint depositAmount; depositAmount = self.claimDeposit; self.claimDeposit = 0; /* solium-disable security/no-send */ return self.claimedBy.send(depositAmount); } return true; } } /** * Library containing the functionality for the bounty and fee payments. * - Bounty payments are the reward paid to the executing agent of transaction * requests. * - Fee payments are the cost of using a Scheduler to make transactions. It is * a way for developers to monetize their work on the EAC. */ library PaymentLib { using SafeMath for uint; struct PaymentData { uint bounty; /// The amount in wei to be paid to the executing agent of the TransactionRequest. address bountyBenefactor; /// The address that the bounty will be sent to. uint bountyOwed; /// The amount that is owed to the bountyBenefactor. uint fee; /// The amount in wei that will be paid to the FEE_RECIPIENT address. address feeRecipient; /// The address that the fee will be sent to. uint feeOwed; /// The amount that is owed to the feeRecipient. } ///--------------- /// GETTERS ///--------------- /** * @dev Getter function that returns true if a request has a benefactor. */ function hasFeeRecipient(PaymentData storage self) internal view returns (bool) { return self.feeRecipient != 0x0; } /** * @dev Computes the amount to send to the feeRecipient. */ function getFee(PaymentData storage self) internal view returns (uint) { return self.fee; } /** * @dev Computes the amount to send to the agent that executed the request. */ function getBounty(PaymentData storage self) internal view returns (uint) { return self.bounty; } /** * @dev Computes the amount to send to the address that fulfilled the request * with an additional modifier. This is used when the call was claimed. */ function getBountyWithModifier(PaymentData storage self, uint8 _paymentModifier) internal view returns (uint) { return getBounty(self).mul(_paymentModifier).div(100); } ///--------------- /// SENDERS ///--------------- /** * @dev Send the feeOwed amount to the feeRecipient. * Note: The send is allowed to fail. */ function sendFee(PaymentData storage self) internal returns (bool) { uint feeAmount = self.feeOwed; if (feeAmount > 0) { // re-entrance protection. self.feeOwed = 0; /* solium-disable security/no-send */ return self.feeRecipient.send(feeAmount); } return true; } /** * @dev Send the bountyOwed amount to the bountyBenefactor. * Note: The send is allowed to fail. */ function sendBounty(PaymentData storage self) internal returns (bool) { uint bountyAmount = self.bountyOwed; if (bountyAmount > 0) { // re-entrance protection. self.bountyOwed = 0; return self.bountyBenefactor.send(bountyAmount); } return true; } ///--------------- /// Endowment ///--------------- /** * @dev Compute the endowment value for the given TransactionRequest parameters. * See request_factory.rst in docs folder under Check #1 for more information about * this calculation. */ function computeEndowment( uint _bounty, uint _fee, uint _callGas, uint _callValue, uint _gasPrice, uint _gasOverhead ) public pure returns (uint) { return _bounty .add(_fee) .add(_callGas.mul(_gasPrice)) .add(_gasOverhead.mul(_gasPrice)) .add(_callValue); } /* * Validation: ensure that the request endowment is sufficient to cover. * - bounty * - fee * - gasReimbursment * - callValue */ function validateEndowment(uint _endowment, uint _bounty, uint _fee, uint _callGas, uint _callValue, uint _gasPrice, uint _gasOverhead) public pure returns (bool) { return _endowment >= computeEndowment( _bounty, _fee, _callGas, _callValue, _gasPrice, _gasOverhead ); } } /** * @title IterTools * @dev Utility library that iterates through a boolean array of length 6. */ library IterTools { /* * @dev Return true if all of the values in the boolean array are true. * @param _values A boolean array of length 6. * @return True if all values are true, False if _any_ are false. */ function all(bool[6] _values) public pure returns (bool) { for (uint i = 0; i < _values.length; i++) { if (!_values[i]) { return false; } } return true; } } /* The MIT License (MIT) Copyright (c) 2018 Murray Software, LLC. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //solhint-disable max-line-length //solhint-disable no-inline-assembly contract CloneFactory { event CloneCreated(address indexed target, address clone); function createClone(address target) internal returns (address result) { bytes memory clone = hex"600034603b57603080600f833981f36000368180378080368173bebebebebebebebebebebebebebebebebebebebe5af43d82803e15602c573d90f35b3d90fd"; bytes20 targetBytes = bytes20(target); for (uint i = 0; i < 20; i++) { clone[26 + i] = targetBytes[i]; } assembly { let len := mload(clone) let data := add(clone, 0x20) result := create(0, data, len) } } } /// Example of using the Scheduler from a smart contract to delay a payment. contract DelayedPayment { SchedulerInterface public scheduler; address recipient; address owner; address public payment; uint lockedUntil; uint value; uint twentyGwei = 20000000000 wei; constructor( address _scheduler, uint _numBlocks, address _recipient, uint _value ) public payable { scheduler = SchedulerInterface(_scheduler); lockedUntil = block.number + _numBlocks; recipient = _recipient; owner = msg.sender; value = _value; uint endowment = scheduler.computeEndowment( twentyGwei, twentyGwei, 200000, 0, twentyGwei ); payment = scheduler.schedule.value(endowment)( // 0.1 ether is to pay for gas, bounty and fee this, // send to self "", // and trigger fallback function [ 200000, // The amount of gas to be sent with the transaction. 0, // The amount of wei to be sent. 255, // The size of the execution window. lockedUntil, // The start of the execution window. twentyGwei, // The gasprice for the transaction (aka 20 gwei) twentyGwei, // The fee included in the transaction. twentyGwei, // The bounty that awards the executor of the transaction. twentyGwei * 2 // The required amount of wei the claimer must send as deposit. ] ); assert(address(this).balance >= value); } function () public payable { if (msg.value > 0) { //this handles recieving remaining funds sent while scheduling (0.1 ether) return; } else if (address(this).balance > 0) { payout(); } else { revert(); } } function payout() public returns (bool) { require(block.number >= lockedUntil); recipient.transfer(value); return true; } function collectRemaining() public returns (bool) { owner.transfer(address(this).balance); } } /// Example of using the Scheduler from a smart contract to delay a payment. contract RecurringPayment { SchedulerInterface public scheduler; uint paymentInterval; uint paymentValue; uint lockedUntil; address recipient; address public currentScheduledTransaction; event PaymentScheduled(address indexed scheduledTransaction, address recipient, uint value); event PaymentExecuted(address indexed scheduledTransaction, address recipient, uint value); function RecurringPayment( address _scheduler, uint _paymentInterval, uint _paymentValue, address _recipient ) public payable { scheduler = SchedulerInterface(_scheduler); paymentInterval = _paymentInterval; recipient = _recipient; paymentValue = _paymentValue; schedule(); } function () public payable { if (msg.value > 0) { //this handles recieving remaining funds sent while scheduling (0.1 ether) return; } process(); } function process() public returns (bool) { payout(); schedule(); } function payout() private returns (bool) { require(block.number >= lockedUntil); require(address(this).balance >= paymentValue); recipient.transfer(paymentValue); emit PaymentExecuted(currentScheduledTransaction, recipient, paymentValue); return true; } function schedule() private returns (bool) { lockedUntil = block.number + paymentInterval; currentScheduledTransaction = scheduler.schedule.value(0.1 ether)( // 0.1 ether is to pay for gas, bounty and fee this, // send to self "", // and trigger fallback function [ 1000000, // The amount of gas to be sent with the transaction. Accounts for payout + new contract deployment 0, // The amount of wei to be sent. 255, // The size of the execution window. lockedUntil, // The start of the execution window. 20000000000 wei, // The gasprice for the transaction (aka 20 gwei) 20000000000 wei, // The fee included in the transaction. 20000000000 wei, // The bounty that awards the executor of the transaction. 30000000000 wei // The required amount of wei the claimer must send as deposit. ] ); emit PaymentScheduled(currentScheduledTransaction, recipient, paymentValue); } } /** * @title RequestFactory * @dev Contract which will produce new TransactionRequests. */ contract RequestFactory is RequestFactoryInterface, CloneFactory, Pausable { using IterTools for bool[6]; TransactionRequestCore public transactionRequestCore; uint constant public BLOCKS_BUCKET_SIZE = 240; //~1h uint constant public TIMESTAMP_BUCKET_SIZE = 3600; //1h constructor( address _transactionRequestCore ) public { require(_transactionRequestCore != 0x0); transactionRequestCore = TransactionRequestCore(_transactionRequestCore); } /** * @dev The lowest level interface for creating a transaction request. * * @param _addressArgs [0] - meta.owner * @param _addressArgs [1] - paymentData.feeRecipient * @param _addressArgs [2] - txnData.toAddress * @param _uintArgs [0] - paymentData.fee * @param _uintArgs [1] - paymentData.bounty * @param _uintArgs [2] - schedule.claimWindowSize * @param _uintArgs [3] - schedule.freezePeriod * @param _uintArgs [4] - schedule.reservedWindowSize * @param _uintArgs [5] - schedule.temporalUnit * @param _uintArgs [6] - schedule.windowSize * @param _uintArgs [7] - schedule.windowStart * @param _uintArgs [8] - txnData.callGas * @param _uintArgs [9] - txnData.callValue * @param _uintArgs [10] - txnData.gasPrice * @param _uintArgs [11] - claimData.requiredDeposit * @param _callData - The call data */ function createRequest( address[3] _addressArgs, uint[12] _uintArgs, bytes _callData ) whenNotPaused public payable returns (address) { // Create a new transaction request clone from transactionRequestCore. address transactionRequest = createClone(transactionRequestCore); // Call initialize on the transaction request clone. TransactionRequestCore(transactionRequest).initialize.value(msg.value)( [ msg.sender, // Created by _addressArgs[0], // meta.owner _addressArgs[1], // paymentData.feeRecipient _addressArgs[2] // txnData.toAddress ], _uintArgs, //uint[12] _callData ); // Track the address locally requests[transactionRequest] = true; // Log the creation. emit RequestCreated( transactionRequest, _addressArgs[0], getBucket(_uintArgs[7], RequestScheduleLib.TemporalUnit(_uintArgs[5])), _uintArgs ); return transactionRequest; } /** * The same as createRequest except that it requires validation prior to * creation. * * Parameters are the same as `createRequest` */ function createValidatedRequest( address[3] _addressArgs, uint[12] _uintArgs, bytes _callData ) public payable returns (address) { bool[6] memory isValid = validateRequestParams( _addressArgs, _uintArgs, msg.value ); if (!isValid.all()) { if (!isValid[0]) { emit ValidationError(uint8(Errors.InsufficientEndowment)); } if (!isValid[1]) { emit ValidationError(uint8(Errors.ReservedWindowBiggerThanExecutionWindow)); } if (!isValid[2]) { emit ValidationError(uint8(Errors.InvalidTemporalUnit)); } if (!isValid[3]) { emit ValidationError(uint8(Errors.ExecutionWindowTooSoon)); } if (!isValid[4]) { emit ValidationError(uint8(Errors.CallGasTooHigh)); } if (!isValid[5]) { emit ValidationError(uint8(Errors.EmptyToAddress)); } // Try to return the ether sent with the message msg.sender.transfer(msg.value); return 0x0; } return createRequest(_addressArgs, _uintArgs, _callData); } /// ---------------------------- /// Internal /// ---------------------------- /* * @dev The enum for launching `ValidationError` events and mapping them to an error. */ enum Errors { InsufficientEndowment, ReservedWindowBiggerThanExecutionWindow, InvalidTemporalUnit, ExecutionWindowTooSoon, CallGasTooHigh, EmptyToAddress } event ValidationError(uint8 error); /* * @dev Validate the constructor arguments for either `createRequest` or `createValidatedRequest`. */ function validateRequestParams( address[3] _addressArgs, uint[12] _uintArgs, uint _endowment ) public view returns (bool[6]) { return RequestLib.validate( [ msg.sender, // meta.createdBy _addressArgs[0], // meta.owner _addressArgs[1], // paymentData.feeRecipient _addressArgs[2] // txnData.toAddress ], _uintArgs, _endowment ); } /// Mapping to hold known requests. mapping (address => bool) requests; function isKnownRequest(address _address) public view returns (bool isKnown) { return requests[_address]; } function getBucket(uint windowStart, RequestScheduleLib.TemporalUnit unit) public pure returns(int) { uint bucketSize; /* since we want to handle both blocks and timestamps and do not want to get into case where buckets overlaps block buckets are going to be negative ints timestamp buckets are going to be positive ints we'll overflow after 2**255-1 blocks instead of 2**256-1 since we encoding this on int256 */ int sign; if (unit == RequestScheduleLib.TemporalUnit.Blocks) { bucketSize = BLOCKS_BUCKET_SIZE; sign = -1; } else if (unit == RequestScheduleLib.TemporalUnit.Timestamp) { bucketSize = TIMESTAMP_BUCKET_SIZE; sign = 1; } else { revert(); } return sign * int(windowStart - (windowStart % bucketSize)); } }
Record the gas at the beginning of the transaction so we can calculate how much has been used later. +----------------------+ | Begin: Authorization | +----------------------+ Compute the fee amount If the transaction request was claimed, we add the deposit to the bounty whether or not the same agent who claimed is executing. To prevent re-entrance we zero out the claim deposit since it is now accounted for in the bounty value. Depending on when the transaction request was claimed, we apply the modifier to the bounty payment and add it to the bounty already owed. Not claimed. Just add the full bounty.
function execute(Request storage self) internal returns (bool) { uint startGas = gasleft(); if (gasleft() < requiredExecutionGas(self).sub(PRE_EXECUTION_GAS)) { emit Aborted(uint8(AbortReason.InsufficientGas)); return false; emit Aborted(uint8(AbortReason.AlreadyCalled)); return false; emit Aborted(uint8(AbortReason.WasCancelled)); return false; emit Aborted(uint8(AbortReason.BeforeCallWindow)); return false; emit Aborted(uint8(AbortReason.AfterCallWindow)); return false; emit Aborted(uint8(AbortReason.ReservedForClaimer)); return false; emit Aborted(uint8(AbortReason.TooLowGasPrice)); return false; } if (self.paymentData.hasFeeRecipient()) { self.paymentData.feeOwed = self.paymentData.getFee() .add(self.paymentData.feeOwed); } if (self.claimData.isClaimed()) { self.paymentData.bountyOwed = self.claimData.claimDeposit .add(self.paymentData.bountyOwed); self.claimData.claimDeposit = 0; self.paymentData.bountyOwed = self.paymentData.getBountyWithModifier(self.claimData.paymentModifier) .add(self.paymentData.bountyOwed); self.paymentData.bountyOwed = self.paymentData.getBounty().add(self.paymentData.bountyOwed); } .mul(self.txnData.gasPrice) .add(self.paymentData.bountyOwed); }
1,732,072
pragma solidity 0.4.26; contract IBancorConverterRegistry { function tokens(uint256 _index) public view returns (address) { _index; } function tokenCount() public view returns (uint256); function converterCount(address _token) public view returns (uint256); function converterAddress(address _token, uint32 _index) public view returns (address); function latestConverterAddress(address _token) public view returns (address); function tokenAddress(address _converter) public view returns (address); } // File: contracts/utility/interfaces/IOwned.sol /* Owned contract interface */ contract IOwned { // this function isn't abstract since the compiler emits automatically generated getter functions as external function owner() public view returns (address) {} function transferOwnership(address _newOwner) public; function acceptOwnership() public; } // File: contracts/utility/Owned.sol /** * @dev Provides support and utilities for contract ownership */ contract Owned is IOwned { address public 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 { require(msg.sender == owner); _; } /** * @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 ownerOnly { require(_newOwner != owner); newOwner = _newOwner; } /** * @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() public { require(msg.sender == newOwner); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } // File: contracts/utility/Utils.sol /** * @dev Utilities & Common Modifiers */ contract Utils { /** * constructor */ constructor() public { } // verifies that an amount is greater than zero modifier greaterThanZero(uint256 _amount) { require(_amount > 0); _; } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != address(0)); _; } // verifies that the address is different than this contract address modifier notThis(address _address) { require(_address != address(this)); _; } } // File: contracts\converter\BancorConverterRegistry.sol /** * @dev Bancor Converter Registry * * The Bancor Converter Registry keeps converter addresses by token addresses and vice versa. The owner can update converter addresses so that the token address always points to the updated list of converters for each token. * * The contract is also able to iterate through all the tokens in the network. * * Note that converter addresses for each token are returned in ascending order (from oldest to newest). * */ contract BancorConverterRegistry is IBancorConverterRegistry, Owned, Utils { mapping (address => address[]) private tokensToConverters; // token address -> converter addresses mapping (address => address) private convertersToTokens; // converter address -> token address address[] public tokens; // list of all token addresses struct TokenInfo { bool valid; uint256 index; } mapping(address => TokenInfo) public tokenTable; /** * @dev triggered when a token is added to the registry * * @param _token token */ event TokenAddition(address indexed _token); /** * @dev triggered when a token is removed from the registry * * @param _token token */ event TokenRemoval(address indexed _token); /** * @dev triggered when a converter is added to the registry * * @param _token token * @param _address converter */ event ConverterAddition(address indexed _token, address _address); /** * @dev triggered when a converter is removed from the registry * * @param _token token * @param _address converter */ event ConverterRemoval(address indexed _token, address _address); /** * @dev initializes a new BancorConverterRegistry instance */ constructor() public { } /** * @dev returns the number of tokens in the registry * * @return number of tokens */ function tokenCount() public view returns (uint256) { return tokens.length; } /** * @dev returns the number of converters associated with the given token * or 0 if the token isn't registered * * @param _token token address * * @return number of converters */ function converterCount(address _token) public view returns (uint256) { return tokensToConverters[_token].length; } /** * @dev returns the converter address associated with the given token * or zero address if no such converter exists * * @param _token token address * @param _index converter index * * @return converter address */ function converterAddress(address _token, uint32 _index) public view returns (address) { if (tokensToConverters[_token].length > _index) return tokensToConverters[_token][_index]; return address(0); } /** * @dev returns the latest converter address associated with the given token * or zero address if no such converter exists * * @param _token token address * * @return latest converter address */ function latestConverterAddress(address _token) public view returns (address) { if (tokensToConverters[_token].length > 0) return tokensToConverters[_token][tokensToConverters[_token].length - 1]; return address(0); } /** * @dev returns the token address associated with the given converter * or zero address if no such converter exists * * @param _converter converter address * * @return token address */ function tokenAddress(address _converter) public view returns (address) { return convertersToTokens[_converter]; } /** * @dev adds a new converter address for a given token to the registry * throws if the converter is already registered * * @param _token token address * @param _converter converter address */ function registerConverter(address _token, address _converter) public ownerOnly validAddress(_token) validAddress(_converter) { require(convertersToTokens[_converter] == address(0)); // add the token to the list of tokens if needed TokenInfo storage tokenInfo = tokenTable[_token]; if (tokenInfo.valid == false) { tokenInfo.valid = true; tokenInfo.index = tokens.push(_token) - 1; emit TokenAddition(_token); } tokensToConverters[_token].push(_converter); convertersToTokens[_converter] = _token; // dispatch the converter addition event emit ConverterAddition(_token, _converter); } /** * @dev removes an existing converter from the registry * note that the function doesn't scale and might be needed to be called * multiple times when removing an older converter from a large converter list * * @param _token token address * @param _index converter index */ function unregisterConverter(address _token, uint32 _index) public ownerOnly validAddress(_token) { require(_index < tokensToConverters[_token].length); address converter = tokensToConverters[_token][_index]; // move all newer converters 1 position lower for (uint32 i = _index + 1; i < tokensToConverters[_token].length; i++) { tokensToConverters[_token][i - 1] = tokensToConverters[_token][i]; } // decrease the number of converters defined for the token by 1 tokensToConverters[_token].length--; // remove the token from the list of tokens if needed if (tokensToConverters[_token].length == 0) { TokenInfo storage tokenInfo = tokenTable[_token]; assert(tokens.length > tokenInfo.index); assert(_token == tokens[tokenInfo.index]); address lastToken = tokens[tokens.length - 1]; tokenTable[lastToken].index = tokenInfo.index; tokens[tokenInfo.index] = lastToken; tokens.length--; delete tokenTable[_token]; emit TokenRemoval(_token); } // remove the converter from the converters -> tokens list delete convertersToTokens[converter]; // dispatch the converter removal event emit ConverterRemoval(_token, converter); } }
returns the token address associated with the given converter or zero address if no such converter exists _converter converter address return token address/
function tokenAddress(address _converter) public view returns (address) { return convertersToTokens[_converter]; }
5,431,383
pragma solidity 0.4.19; import "../mixin/Ownable.sol"; contract Registry is Ownable { uint constant public VERSION = 1; // id -> address mapping mapping(bytes32 => address) public addressMap; // Events event Registered(bytes32 indexed _id, address indexed _address, address indexed _sender); event Unregistered(bytes32 indexed _id); /// @dev contructor function Registry(address _owner) public { owner = _owner; } // Methods /// @dev Registers contract in registry. /// @param _id of contract. /// @param _address of contract. function register(bytes32 _id, address _address) public onlyOwner { addressMap[_id] = _address; Registered(_id, _address, msg.sender); } /// @dev Unregisters contract in registry. /// @param _id of contract. function unregister(bytes32 _id) public onlyOwner { delete addressMap[_id]; Unregistered(_id); } /// @dev Resolves id with contract address. /// @param _id of contract. function resolve(bytes32 _id) public view returns (address _address) { _address = addressMap[_id]; } }
Methods Registers contract in registry. _id of contract. _address of contract.
function register(bytes32 _id, address _address) public onlyOwner { addressMap[_id] = _address; Registered(_id, _address, msg.sender); }
13,002,074
pragma solidity ^0.5.16; import "./KUSDMinter.sol"; /** * @title KUSDMinter is responsible to stake/unstake users' Kine MCD (see KMCD) and mint/burn KUSD (see KineUSD) on behalf of users. * When user want to mint KUSD against their collaterals (see KToken), KUSDMinter will borrow Knie MCD on behalf of user (which will increase user's debt ratio) * and then call KineUSD to mint KUSD to user. When user want to burn KUSD, KUSDMinter will call KineUSD to burn KUSD from user and repay Kine MCD on behalf of user. * KUSDMinter also let treasury account to mint/burn its balance to keep KUSD amount (the part that user transferred into Kine off-chain trading system) synced with Kine off-chain trading system. * @author Kine * * V2 changes: * 1. available to change reward token after each period end, rewards not claimed yet will convert to new reward token according to given scale param * 2. add scaleParamIndex in AccountRewardDetail * 3. add currentScaleParamIndex to note current reward token index * 4. add scaleParams to record history scale params in order to calculate user's reward correctly * * V3 changes: * 1. add liquidator whitelist */ interface LiquidatorWhitelistInterface { function isListed(address liquidatorToVerify) external view returns (bool); } contract KUSDMinterV3 is IRewardDistributionRecipient { using KineSafeMath for uint; using SafeERC20 for IERC20; /// @notice Emitted when KMCD changed event NewKMCD(address oldKMCD, address newKMCD); /// @notice Emitted when KineUSD changed event NewKUSD(address oldKUSD, address newKUSD); /// @notice Emitted when reward token changed event NewRewardToken(address oldRewardToken, address newRewardToken, uint scaleParam, uint leftOverReward, uint replaceReward, address leftoverTokenReceipient); /// @notice Emitted when reward duration changed event NewRewardDuration(uint oldRewardDuration, uint newRewardDuration); /// @notice Emitted when reward release period changed event NewRewardReleasePeriod(uint oldRewardReleasePeriod, uint newRewardReleasePeriod); /// @notice Emitted when burn cool down time changed event NewBurnCooldownTime(uint oldCooldown, uint newCooldownTime); /// @notice Emitted when user mint KUSD event Mint(address indexed user, uint mintKUSDAmount, uint stakedKMCDAmount, uint userStakesNew, uint totalStakesNew); /// @notice Emitted when user burnt KUSD event Burn(address indexed user, uint burntKUSDAmount, uint unstakedKMCDAmount, uint userStakesNew, uint totalStakesNew); /// @notice Emitted when user burnt maximum KUSD event BurnMax(address indexed user, uint burntKUSDAmount, uint unstakedKMCDAmount, uint userStakesNew, uint totalStakesNew); /// @notice Emitted when liquidator liquidate staker's Kine MCD event Liquidate(address indexed liquidator, address indexed staker, uint burntKUSDAmount, uint unstakedKMCDAmount, uint stakerStakesNew, uint totalStakesNew); /// @notice Emitted when distributor notify reward is added event RewardAdded(uint reward); /// @notice Emitted when user claimed reward event RewardPaid(address indexed user, uint reward); /// @notice Emitted when treasury account mint kusd event TreasuryMint(uint amount); /// @notice Emitted when treasury account burn kusd event TreasuryBurn(uint amount); /// @notice Emitted when treasury account changed event NewTreasury(address oldTreasury, address newTreasury); /// @notice Emitted when vault account changed event NewVault(address oldVault, address newVault); /// @notice Emitted when controller changed event NewController(address oldController, address newController); /// @notice Emitted when liquidator whitelist changed event NewLiquidatorWhitelist(address oldLiquidatorWhitelist, address newLiquidatorWhitelist); /** * @notice This is for avoiding reward calculation overflow (see https://sips.synthetix.io/sips/sip-77) * 1.15792e59 < uint(-1) / 1e18 */ uint public constant REWARD_OVERFLOW_CHECK = 1.15792e59; /** * @notice Implementation address slot for delegation mode; */ address public implementation; /// @notice Flag to mark if this contract has been initialized before bool public initialized; /// @notice Contract which holds Kine MCD IKMCD public kMCD; /// @notice Contract which holds Kine USD IKineUSD public kUSD; /// @notice Contract of controller which holds Kine Oracle KineControllerInterface public controller; /// @notice Treasury is responsible to keep KUSD amount consisted with Kine off-chain trading system address public treasury; /// @notice Vault is the place to store Kine trading system's reserved KUSD address public vault; /**************** * Reward related ****************/ /// @notice Contract which hold Kine Token IERC20 public rewardToken; /// @notice Reward distribution duration. Added reward will be distribute to Kine MCD stakers within this duration. uint public rewardDuration; /// @notice Staker's reward will mature gradually in this period. uint public rewardReleasePeriod; /// @notice Start time that users can start staking/burning KUSD and claim their rewards. uint public startTime; /// @notice End time of this round of reward distribution. uint public periodFinish = 0; /// @notice Per second reward to be distributed uint public rewardRate = 0; /// @notice Accrued reward per Kine MCD staked per second. uint public rewardPerTokenStored; /// @notice Last time that rewardPerTokenStored is updated. Happens whenever total stakes going to be changed. uint public lastUpdateTime; /** * @notice The minium cool down time before user can burn kUSD after they mint kUSD everytime. * This is to raise risk and cost to arbitrageurs who front run our prices updates in oracle to drain profit from stakers. * Should be larger then minium price post interval. */ uint public burnCooldownTime; struct AccountRewardDetail { /// @dev Last time account claimed its reward uint lastClaimTime; /// @dev RewardPerTokenStored at last time accrue rewards to this account uint rewardPerTokenUpdated; /// @dev Accrued rewards haven't been claimed of this account uint accruedReward; /// @dev Last time account mint kUSD uint lastMintTime; /// @dev Sys scale param when last time account reward detail updated uint scaleParamIndex; } /// @notice Mapping of account addresses to account reward detail mapping(address => AccountRewardDetail) public accountRewardDetails; /// to support change reward token when duration end /// @notice system wide index of scale param uint public currentScaleParamIndex; /// @notice everytime owner change reward token, will save scale param of old reward token to new reward token uint[] public scaleParams; /// @notice liquidator checker LiquidatorWhitelistInterface public liquidatorWhitelist; function initialize(address rewardToken_, address kUSD_, address kMCD_, address controller_, address treasury_, address vault_, address rewardDistribution_, uint startTime_, uint rewardDuration_, uint rewardReleasePeriod_) external { require(initialized == false, "KUSDMinter can only be initialized once"); rewardToken = IERC20(rewardToken_); kUSD = IKineUSD(kUSD_); kMCD = IKMCD(kMCD_); controller = KineControllerInterface(controller_); treasury = treasury_; vault = vault_; rewardDistribution = rewardDistribution_; startTime = startTime_; rewardDuration = rewardDuration_; rewardReleasePeriod = rewardReleasePeriod_; initialized = true; } /** * @dev Local vars in calculating equivalent amount between KUSD and Kine MCD */ struct CalculateVars { uint equivalentKMCDAmount; uint equivalentKUSDAmount; } /// @notice Prevent stakers' actions before start time modifier checkStart() { require(block.timestamp >= startTime, "not started yet"); _; } /// @notice Prevent accounts other than treasury to mint/burn KUSD modifier onlyTreasury() { require(msg.sender == treasury, "only treasury account is allowed"); _; } modifier afterCooldown(address staker) { require(accountRewardDetails[staker].lastMintTime.add(burnCooldownTime) < block.timestamp, "burn still cooling down"); _; } /*** * @notice Accrue account's rewards and store this time accrued results * @param account Reward status of whom to be updated */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { accountRewardDetails[account].accruedReward = earned(account); accountRewardDetails[account].rewardPerTokenUpdated = rewardPerTokenStored; accountRewardDetails[account].scaleParamIndex = currentScaleParamIndex; if (accountRewardDetails[account].lastClaimTime == 0) { accountRewardDetails[account].lastClaimTime = block.timestamp; } } _; } /// @dev reverts if the caller is not a certified liquidator modifier checkLiquidator() { LiquidatorWhitelistInterface lc = liquidatorWhitelist; require(address(lc) != address(0) && lc.isListed(msg.sender), "not valid liquidator"); _; } /** * @notice Current time which hasn't past this round reward's duration. * @return Current timestamp that hasn't past this round rewards' duration. */ function lastTimeRewardApplicable() public view returns (uint) { return Math.min(block.timestamp, periodFinish); } /** * @notice Calculate new accrued reward per staked Kine MCD. * @return Current accrued reward per staked Kine MCD. */ function rewardPerToken() public view returns (uint) { uint totalStakes = totalStakes(); if (totalStakes == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalStakes) ); } /** * @notice Calculate account's earned rewards so far. * @param account Which account to be viewed. * @return Account's earned rewards so far. */ function earned(address account) public view returns (uint) { AccountRewardDetail memory detail = accountRewardDetails[account]; uint scaledRewardPerTokenUpdated = detail.rewardPerTokenUpdated; uint scaledAccruedReward = detail.accruedReward; for (uint i = detail.scaleParamIndex; i < currentScaleParamIndex; i++) { scaledRewardPerTokenUpdated = scaledRewardPerTokenUpdated.mul(scaleParams[i]).div(1e18); scaledAccruedReward = scaledAccruedReward.mul(scaleParams[i]).div(1e18); } return accountStakes(account) .mul(rewardPerToken().sub(scaledRewardPerTokenUpdated)) .div(1e18) .add(scaledAccruedReward); } /** * @notice Calculate account's claimable rewards so far. * @param account Which account to be viewed. * @return Account's claimable rewards so far. */ function claimable(address account) external view returns (uint) { uint accountNewAccruedReward = earned(account); uint pastTime = block.timestamp.sub(accountRewardDetails[account].lastClaimTime); uint maturedReward = rewardReleasePeriod == 0 ? accountNewAccruedReward : accountNewAccruedReward.mul(pastTime).div(rewardReleasePeriod); if (maturedReward > accountNewAccruedReward) { maturedReward = accountNewAccruedReward; } return maturedReward; } /** * @notice Mint will borrow equivalent Kine MCD for user, stake borrowed MCD and mint specified amount of KUSD. Call will fail if hasn't reached start time. * Mint will fail if hasn't reach start time. * @param kUSDAmount The amount of KUSD user want to mint */ function mint(uint kUSDAmount) external checkStart updateReward(msg.sender) { address payable msgSender = _msgSender(); // update sender's mint time accountRewardDetails[msgSender].lastMintTime = block.timestamp; uint kMCDPriceMantissa = KineOracleInterface(controller.getOracle()).getUnderlyingPrice(address(kMCD)); require(kMCDPriceMantissa != 0, "Mint: get Kine MCD price zero"); CalculateVars memory vars; // KUSD has 18 decimals // KMCD has 18 decimals // kMCDPriceMantissa is KMCD's price (quoted by KUSD, has 6 decimals) scaled by 1e36 / KMCD's decimals = 1e36 / 1e18 = 1e18 // so the calculation of equivalent Kine MCD amount is as below // kUSDAmount 1e12 * 1e6 kUSDAmount * 1e18 // equivalentKMCDAmount = ----------- * ------------------ * 1e18 = ----------------- // 1e18 kMCDPriceMantissa kMCDPriceMantissa vars.equivalentKMCDAmount = kUSDAmount.mul(1e18).div(kMCDPriceMantissa); // call KMCD contract to borrow Kine MCD for user and stake them kMCD.borrowBehalf(msgSender, vars.equivalentKMCDAmount); // mint KUSD to user kUSD.mint(msgSender, kUSDAmount); emit Mint(msgSender, kUSDAmount, vars.equivalentKMCDAmount, accountStakes(msgSender), totalStakes()); } /** * @notice Burn repay equivalent Kine MCD for user and burn specified amount of KUSD * Burn will fail if hasn't reach start time. * @param kUSDAmount The amount of KUSD user want to burn */ function burn(uint kUSDAmount) external checkStart afterCooldown(msg.sender) updateReward(msg.sender) { address msgSender = _msgSender(); // burn user's KUSD kUSD.burn(msgSender, kUSDAmount); // calculate equivalent Kine MCD amount to specified amount of KUSD uint kMCDPriceMantissa = KineOracleInterface(controller.getOracle()).getUnderlyingPrice(address(kMCD)); require(kMCDPriceMantissa != 0, "Burn: get Kine MCD price zero"); CalculateVars memory vars; // KUSD has 18 decimals // KMCD has 18 decimals // kMCDPriceMantissa is KMCD's price (quoted by KUSD, has 6 decimals) scaled by 1e36 / KMCD's decimals = 1e36 / 1e18 = 1e18 // so the calculation of equivalent Kine MCD amount is as below // kUSDAmount 1e12 * 1e6 kUSDAmount * 1e18 // equivalentKMCDAmount = ----------- * ------------------ * 1e18 = ----------------- // 1e18 kMCDPriceMantissa kMCDPriceMantissa vars.equivalentKMCDAmount = kUSDAmount.mul(1e18).div(kMCDPriceMantissa); // call KMCD contract to repay Kine MCD for user kMCD.repayBorrowBehalf(msgSender, vars.equivalentKMCDAmount); emit Burn(msgSender, kUSDAmount, vars.equivalentKMCDAmount, accountStakes(msgSender), totalStakes()); } /** * @notice BurnMax unstake and repay all borrowed Kine MCD for user and burn equivalent KUSD */ function burnMax() external checkStart afterCooldown(msg.sender) updateReward(msg.sender) { address msgSender = _msgSender(); uint kMCDPriceMantissa = KineOracleInterface(controller.getOracle()).getUnderlyingPrice(address(kMCD)); require(kMCDPriceMantissa != 0, "BurnMax: get Kine MCD price zero"); CalculateVars memory vars; // KUSD has 18 decimals // KMCD has 18 decimals // kMCDPriceMantissa is KMCD's price (quoted by KUSD, has 6 decimals) scaled by 1e36 / KMCD's decimals = 1e36 / 1e18 = 1e18 // so the calculation of equivalent KUSD amount is as below // accountStakes kMCDPriceMantissa accountStakes * kMCDPriceMantissa // equivalentKUSDAmount = ------------- * ------------------ * 1e18 = --------------------------------- // 1e18 1e12 * 1e6 1e18 // // try to unstake all Kine MCD uint userStakes = accountStakes(msgSender); vars.equivalentKMCDAmount = userStakes; vars.equivalentKUSDAmount = userStakes.mul(kMCDPriceMantissa).div(1e18); // in case user's kUSD is not enough to unstake all mcd, then just burn all kUSD and unstake part of MCD uint kUSDbalance = kUSD.balanceOf(msgSender); if (vars.equivalentKUSDAmount > kUSDbalance) { vars.equivalentKUSDAmount = kUSDbalance; vars.equivalentKMCDAmount = kUSDbalance.mul(1e18).div(kMCDPriceMantissa); } // burn user's equivalent KUSD kUSD.burn(msgSender, vars.equivalentKUSDAmount); // call KMCD contract to repay Kine MCD for user kMCD.repayBorrowBehalf(msgSender, vars.equivalentKMCDAmount); emit BurnMax(msgSender, vars.equivalentKUSDAmount, vars.equivalentKMCDAmount, accountStakes(msgSender), totalStakes()); } /** * @notice Caller liquidates the staker's Kine MCD and seize staker's collateral. * Liquidate will fail if hasn't reach start time. * @param staker The staker of Kine MCD to be liquidated. * @param unstakeKMCDAmount The amount of Kine MCD to unstake. * @param maxBurnKUSDAmount The max amount limit of KUSD of liquidator to be burned. * @param kTokenCollateral The market in which to seize collateral from the staker. */ function liquidate(address staker, uint unstakeKMCDAmount, uint maxBurnKUSDAmount, address kTokenCollateral, uint minSeizeKToken) external checkLiquidator checkStart updateReward(staker) { address msgSender = _msgSender(); uint kMCDPriceMantissa = KineOracleInterface(controller.getOracle()).getUnderlyingPrice(address(kMCD)); require(kMCDPriceMantissa != 0, "Liquidate: get Kine MCD price zero"); CalculateVars memory vars; // KUSD has 18 decimals // KMCD has 18 decimals // kMCDPriceMantissa is KMCD's price (quoted by KUSD, has 6 decimals) scaled by 1e36 / KMCD's decimals = 1e36 / 1e18 = 1e18 // so the calculation of equivalent KUSD amount is as below // accountStakes kMCDPriceMantissa accountStakes * kMCDPriceMantissa // equivalentKUSDAmount = ------------- * ------------------ * 1e18 = --------------------------------- // 1e18 1e12 * 1e6 1e30 // vars.equivalentKUSDAmount = unstakeKMCDAmount.mul(kMCDPriceMantissa).div(1e18); require(maxBurnKUSDAmount >= vars.equivalentKUSDAmount, "Liquidate: reach out max burn KUSD amount limit"); // burn liquidator's KUSD kUSD.burn(msgSender, vars.equivalentKUSDAmount); // call KMCD contract to liquidate staker's Kine MCD and seize collateral kMCD.liquidateBorrowBehalf(msgSender, staker, unstakeKMCDAmount, kTokenCollateral, minSeizeKToken); emit Liquidate(msgSender, staker, vars.equivalentKUSDAmount, unstakeKMCDAmount, accountStakes(staker), totalStakes()); } /** * @notice Show account's staked Kine MCD amount * @param account The account to be get MCD amount from */ function accountStakes(address account) public view returns (uint) { return kMCD.borrowBalance(account); } /// @notice Show total staked Kine MCD amount function totalStakes() public view returns (uint) { return kMCD.totalBorrows(); } /** * @notice Claim the matured rewards of caller. * Claim will fail if hasn't reach start time. */ function getReward() external checkStart updateReward(msg.sender) { uint reward = accountRewardDetails[msg.sender].accruedReward; if (reward > 0) { uint pastTime = block.timestamp.sub(accountRewardDetails[msg.sender].lastClaimTime); uint maturedReward = rewardReleasePeriod == 0 ? reward : reward.mul(pastTime).div(rewardReleasePeriod); if (maturedReward > reward) { maturedReward = reward; } accountRewardDetails[msg.sender].accruedReward = reward.sub(maturedReward); accountRewardDetails[msg.sender].lastClaimTime = block.timestamp; rewardToken.safeTransfer(msg.sender, maturedReward); emit RewardPaid(msg.sender, maturedReward); } } /** * @notice Notify rewards has been added, trigger a new round of reward period, recalculate reward rate and duration end time. * If distributor notify rewards before this round duration end time, then the leftover rewards of this round will roll over to * next round and will be distributed together with new rewards in next round of reward period. * @param reward How many of rewards has been added for new round of reward period. */ function notifyRewardAmount(uint reward) external onlyRewardDistribution updateReward(address(0)) { if (block.timestamp > startTime) { if (block.timestamp >= periodFinish) { // @dev to avoid of rewardPerToken calculation overflow (see https://sips.synthetix.io/sips/sip-77), we check the reward to be inside a properate range // which is 2^256 / 10^18 require(reward < REWARD_OVERFLOW_CHECK, "reward rate will overflow"); rewardRate = reward.div(rewardDuration); } else { uint remaining = periodFinish.sub(block.timestamp); uint leftover = remaining.mul(rewardRate); // @dev to avoid of rewardPerToken calculation overflow (see https://sips.synthetix.io/sips/sip-77), we check the reward to be inside a properate range // which is 2^256 / 10^18 require(reward.add(leftover) < REWARD_OVERFLOW_CHECK, "reward rate will overflow"); rewardRate = reward.add(leftover).div(rewardDuration); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardDuration); emit RewardAdded(reward); } else { // @dev to avoid of rewardPerToken calculation overflow (see https://sips.synthetix.io/sips/sip-77), we check the reward to be inside a properate range // which is 2^256 / 10^18 require(reward < REWARD_OVERFLOW_CHECK, "reward rate will overflow"); rewardRate = reward.div(rewardDuration); lastUpdateTime = startTime; periodFinish = startTime.add(rewardDuration); emit RewardAdded(reward); } } /** * @notice Set new reward duration, will start a new round of reward period immediately and recalculate rewardRate. * @param newRewardDuration New duration of each reward period round. */ function _setRewardDuration(uint newRewardDuration) external onlyOwner updateReward(address(0)) { uint oldRewardDuration = rewardDuration; rewardDuration = newRewardDuration; if (block.timestamp > startTime) { if (block.timestamp >= periodFinish) { rewardRate = 0; } else { uint remaining = periodFinish.sub(block.timestamp); uint leftover = remaining.mul(rewardRate); rewardRate = leftover.div(rewardDuration); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardDuration); } else { rewardRate = rewardRate.mul(oldRewardDuration).div(rewardDuration); lastUpdateTime = startTime; periodFinish = startTime.add(rewardDuration); } emit NewRewardDuration(oldRewardDuration, newRewardDuration); } /** * @notice Set new reward release period. The unclaimed rewards will be affected immediately. * @param newRewardReleasePeriod New release period of how long all earned rewards will be matured each time * before user claim reward. */ function _setRewardReleasePeriod(uint newRewardReleasePeriod) external onlyOwner updateReward(address(0)) { uint oldRewardReleasePeriod = rewardReleasePeriod; rewardReleasePeriod = newRewardReleasePeriod; emit NewRewardReleasePeriod(oldRewardReleasePeriod, newRewardReleasePeriod); } function _setCooldownTime(uint newCooldownTime) external onlyOwner { uint oldCooldown = burnCooldownTime; burnCooldownTime = newCooldownTime; emit NewBurnCooldownTime(oldCooldown, newCooldownTime); } /** * @notice Mint KUSD to treasury account to keep on-chain KUSD consist with off-chain trading system * @param amount The amount of KUSD to mint to treasury */ function treasuryMint(uint amount) external onlyTreasury { kUSD.mint(vault, amount); emit TreasuryMint(amount); } /** * @notice Burn KUSD from treasury account to keep on-chain KUSD consist with off-chain trading system * @param amount The amount of KUSD to burn from treasury */ function treasuryBurn(uint amount) external onlyTreasury { kUSD.burn(vault, amount); emit TreasuryBurn(amount); } /** * @notice Change treasury account to a new one * @param newTreasury New treasury account address */ function _setTreasury(address newTreasury) external onlyOwner { address oldTreasury = treasury; treasury = newTreasury; emit NewTreasury(oldTreasury, newTreasury); } /** * @notice Change vault account to a new one * @param newVault New vault account address */ function _setVault(address newVault) external onlyOwner { address oldVault = vault; vault = newVault; emit NewVault(oldVault, newVault); } /** * @notice Change KMCD contract address to a new one. * @param newKMCD New KMCD contract address. */ function _setKMCD(address newKMCD) external onlyOwner { address oldKMCD = address(kMCD); kMCD = IKMCD(newKMCD); emit NewKMCD(oldKMCD, newKMCD); } /** * @notice Change KUSD contract address to a new one. * @param newKUSD New KineUSD contract address. */ function _setKUSD(address newKUSD) external onlyOwner { address oldKUSD = address(kUSD); kUSD = IKineUSD(newKUSD); emit NewKUSD(oldKUSD, newKUSD); } /** * @notice Change Kine Controller address to a new one. * @param newController New Controller contract address. */ function _setController(address newController) external onlyOwner { address oldController = address(controller); controller = KineControllerInterface(newController); emit NewController(oldController, newController); } function _changeRewardToken(address newRewardToken, uint scaleParam, address tokenHolder) external onlyOwner updateReward(address(0)) { require(block.timestamp > periodFinish, "period not finished yet"); // 1. convert current rewardPerTokenStored to fit new token rewardPerTokenStored = rewardPerTokenStored.mul(scaleParam).div(1e18); rewardRate = rewardRate.mul(scaleParam).div(1e18); // 2. save scaleParam to array and update sys scaleParamIndex scaleParams.push(scaleParam); currentScaleParamIndex++; // 3. transfer left-over old reward token to tokenHolder uint leftOverReward = rewardToken.balanceOf(address(this)); rewardToken.safeTransfer(tokenHolder, leftOverReward); // 4. set newRewardToken address oldRewardToken = address(rewardToken); rewardToken = IERC20(newRewardToken); // 5. transfer equivalent new reward token to this contract uint replaceReward = leftOverReward.mul(scaleParam).div(1e18); rewardToken.safeTransferFrom(tokenHolder, address(this), replaceReward); emit NewRewardToken(oldRewardToken, newRewardToken, scaleParam, leftOverReward, replaceReward, tokenHolder); } /** * @notice Change liquidator whitelist address to a new one. * @param newLiquidatorWhitelist New whitelist contract address. */ function _setLiquidatorWhitelist(address newLiquidatorWhitelist) external onlyOwner { address oldLiquidatorWhitelist = address(liquidatorWhitelist); require(oldLiquidatorWhitelist != newLiquidatorWhitelist, "same address"); liquidatorWhitelist = LiquidatorWhitelistInterface(newLiquidatorWhitelist); emit NewLiquidatorWhitelist(oldLiquidatorWhitelist, newLiquidatorWhitelist); } } pragma solidity ^0.5.16; import "./KineOracleInterface.sol"; import "./KineControllerInterface.sol"; import "./KUSDMinterDelegate.sol"; import "./Math.sol"; import "./IERC20.sol"; import "./ERC20.sol"; import "./SafeERC20.sol"; /// @notice IKineUSD, a simplified interface of KineUSD (see KineUSD) interface IKineUSD { function mint(address account, uint amount) external; function burn(address account, uint amount) external; function balanceOf(address account) external view returns (uint256); } /// @notice IKMCD, a simplified interface of KMCD (see KMCD) interface IKMCD { function borrowBehalf(address payable borrower, uint borrowAmount) external; function repayBorrowBehalf(address borrower, uint repayAmount) external; function liquidateBorrowBehalf(address liquidator, address borrower, uint repayAmount, address kTokenCollateral, uint minSeizeKToken) external; function borrowBalance(address account) external view returns (uint); function totalBorrows() external view returns (uint); } /** * @title IRewardDistributionRecipient */ contract IRewardDistributionRecipient is KUSDMinterDelegate { /// @notice Emitted when reward distributor changed event NewRewardDistribution(address oldRewardDistribution, address newRewardDistribution); /// @notice The reward distributor who is responsible to transfer rewards to this recipient and notify the recipient that reward is added. address public rewardDistribution; /// @notice Notify this recipient that reward is added. function notifyRewardAmount(uint reward) external; /// @notice Only reward distributor can notify that reward is added. modifier onlyRewardDistribution() { require(_msgSender() == rewardDistribution, "Caller is not reward distribution"); _; } /// @notice Set reward distributor to new one. function setRewardDistribution(address _rewardDistribution) external onlyOwner { address oldRewardDistribution = rewardDistribution; rewardDistribution = _rewardDistribution; emit NewRewardDistribution(oldRewardDistribution, _rewardDistribution); } } /** * @title KUSDMinter is responsible to stake/unstake users' Kine MCD (see KMCD) and mint/burn KUSD (see KineUSD) on behalf of users. * When user want to mint KUSD against their collaterals (see KToken), KUSDMinter will borrow Knie MCD on behalf of user (which will increase user's debt ratio) * and then call KineUSD to mint KUSD to user. When user want to burn KUSD, KUSDMinter will call KineUSD to burn KUSD from user and repay Kine MCD on behalf of user. * KUSDMinter also let treasury account to mint/burn its balance to keep KUSD amount (the part that user transferred into Kine off-chain trading system) synced with Kine off-chain trading system. * @author Kine */ contract KUSDMinter is IRewardDistributionRecipient { using KineSafeMath for uint; using SafeERC20 for IERC20; /// @notice Emitted when KMCD changed event NewKMCD(address oldKMCD, address newKMCD); /// @notice Emitted when KineUSD changed event NewKUSD(address oldKUSD, address newKUSD); /// @notice Emitted when Kine changed event NewKine(address oldKine, address newKine); /// @notice Emitted when reward duration changed event NewRewardDuration(uint oldRewardDuration, uint newRewardDuration); /// @notice Emitted when reward release period changed event NewRewardReleasePeriod(uint oldRewardReleasePeriod, uint newRewardReleasePeriod); /// @notice Emitted when burn cool down time changed event NewBurnCooldownTime(uint oldCooldown, uint newCooldownTime); /// @notice Emitted when user mint KUSD event Mint(address indexed user, uint mintKUSDAmount, uint stakedKMCDAmount, uint userStakesNew, uint totalStakesNew); /// @notice Emitted when user burnt KUSD event Burn(address indexed user, uint burntKUSDAmount, uint unstakedKMCDAmount, uint userStakesNew, uint totalStakesNew); /// @notice Emitted when user burnt maximum KUSD event BurnMax(address indexed user, uint burntKUSDAmount, uint unstakedKMCDAmount, uint userStakesNew, uint totalStakesNew); /// @notice Emitted when liquidator liquidate staker's Kine MCD event Liquidate(address indexed liquidator, address indexed staker, uint burntKUSDAmount, uint unstakedKMCDAmount, uint stakerStakesNew, uint totalStakesNew); /// @notice Emitted when distributor notify reward is added event RewardAdded(uint reward); /// @notice Emitted when user claimed reward event RewardPaid(address indexed user, uint reward); /// @notice Emitted when treasury account mint kusd event TreasuryMint(uint amount); /// @notice Emitted when treasury account burn kusd event TreasuryBurn(uint amount); /// @notice Emitted when treasury account changed event NewTreasury(address oldTreasury, address newTreasury); /// @notice Emitted when vault account changed event NewVault(address oldVault, address newVault); /// @notice Emitted when controller changed event NewController(address oldController, address newController); /** * @notice This is for avoiding reward calculation overflow (see https://sips.synthetix.io/sips/sip-77) * 1.15792e59 < uint(-1) / 1e18 */ uint public constant REWARD_OVERFLOW_CHECK = 1.15792e59; /** * @notice Implementation address slot for delegation mode; */ address public implementation; /// @notice Flag to mark if this contract has been initialized before bool public initialized; /// @notice Contract which holds Kine MCD IKMCD public kMCD; /// @notice Contract which holds Kine USD IKineUSD public kUSD; /// @notice Contract of controller which holds Kine Oracle KineControllerInterface public controller; /// @notice Treasury is responsible to keep KUSD amount consisted with Kine off-chain trading system address public treasury; /// @notice Vault is the place to store Kine trading system's reserved KUSD address public vault; /**************** * Reward related ****************/ /// @notice Contract which hold Kine Token IERC20 public kine; /// @notice Reward distribution duration. Added reward will be distribute to Kine MCD stakers within this duration. uint public rewardDuration; /// @notice Staker's reward will mature gradually in this period. uint public rewardReleasePeriod; /// @notice Start time that users can start staking/burning KUSD and claim their rewards. uint public startTime; /// @notice End time of this round of reward distribution. uint public periodFinish = 0; /// @notice Per second reward to be distributed uint public rewardRate = 0; /// @notice Accrued reward per Kine MCD staked per second. uint public rewardPerTokenStored; /// @notice Last time that rewardPerTokenStored is updated. Happens whenever total stakes going to be changed. uint public lastUpdateTime; /** * @notice The minium cool down time before user can burn kUSD after they mint kUSD everytime. * This is to raise risk and cost to arbitrageurs who front run our prices updates in oracle to drain profit from stakers. * Should be larger then minium price post interval. */ uint public burnCooldownTime; struct AccountRewardDetail { /// @dev Last time account claimed its reward uint lastClaimTime; /// @dev RewardPerTokenStored at last time accrue rewards to this account uint rewardPerTokenUpdated; /// @dev Accrued rewards haven't been claimed of this account uint accruedReward; /// @dev Last time account mint kUSD uint lastMintTime; } /// @notice Mapping of account addresses to account reward detail mapping(address => AccountRewardDetail) public accountRewardDetails; function initialize(address kine_, address kUSD_, address kMCD_, address controller_, address treasury_, address vault_, address rewardDistribution_, uint startTime_, uint rewardDuration_, uint rewardReleasePeriod_) external { require(initialized == false, "KUSDMinter can only be initialized once"); kine = IERC20(kine_); kUSD = IKineUSD(kUSD_); kMCD = IKMCD(kMCD_); controller = KineControllerInterface(controller_); treasury = treasury_; vault = vault_; rewardDistribution = rewardDistribution_; startTime = startTime_; rewardDuration = rewardDuration_; rewardReleasePeriod = rewardReleasePeriod_; initialized = true; } /** * @dev Local vars in calculating equivalent amount between KUSD and Kine MCD */ struct CalculateVars { uint equivalentKMCDAmount; uint equivalentKUSDAmount; } /// @notice Prevent stakers' actions before start time modifier checkStart() { require(block.timestamp >= startTime, "not started yet"); _; } /// @notice Prevent accounts other than treasury to mint/burn KUSD modifier onlyTreasury() { require(msg.sender == treasury, "only treasury account is allowed"); _; } modifier afterCooldown(address staker) { require(accountRewardDetails[staker].lastMintTime.add(burnCooldownTime) < block.timestamp, "burn still cooling down"); _; } /*** * @notice Accrue account's rewards and store this time accrued results * @param account Reward status of whom to be updated */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { accountRewardDetails[account].accruedReward = earned(account); accountRewardDetails[account].rewardPerTokenUpdated = rewardPerTokenStored; if (accountRewardDetails[account].lastClaimTime == 0) { accountRewardDetails[account].lastClaimTime = block.timestamp; } } _; } /** * @notice Current time which hasn't past this round reward's duration. * @return Current timestamp that hasn't past this round rewards' duration. */ function lastTimeRewardApplicable() public view returns (uint) { return Math.min(block.timestamp, periodFinish); } /** * @notice Calculate new accrued reward per staked Kine MCD. * @return Current accrued reward per staked Kine MCD. */ function rewardPerToken() public view returns (uint) { uint totalStakes = totalStakes(); if (totalStakes == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalStakes) ); } /** * @notice Calculate account's earned rewards so far. * @param account Which account to be viewed. * @return Account's earned rewards so far. */ function earned(address account) public view returns (uint) { return accountStakes(account) .mul(rewardPerToken().sub(accountRewardDetails[account].rewardPerTokenUpdated)) .div(1e18) .add(accountRewardDetails[account].accruedReward); } /** * @notice Calculate account's claimable rewards so far. * @param account Which account to be viewed. * @return Account's claimable rewards so far. */ function claimable(address account) external view returns (uint) { uint accountNewAccruedReward = earned(account); uint pastTime = block.timestamp.sub(accountRewardDetails[account].lastClaimTime); uint maturedReward = rewardReleasePeriod == 0 ? accountNewAccruedReward : accountNewAccruedReward.mul(pastTime).div(rewardReleasePeriod); if (maturedReward > accountNewAccruedReward) { maturedReward = accountNewAccruedReward; } return maturedReward; } /** * @notice Mint will borrow equivalent Kine MCD for user, stake borrowed MCD and mint specified amount of KUSD. Call will fail if hasn't reached start time. * Mint will fail if hasn't reach start time. * @param kUSDAmount The amount of KUSD user want to mint */ function mint(uint kUSDAmount) external checkStart updateReward(msg.sender) { address payable msgSender = _msgSender(); // update sender's mint time accountRewardDetails[msgSender].lastMintTime = block.timestamp; uint kMCDPriceMantissa = KineOracleInterface(controller.getOracle()).getUnderlyingPrice(address(kMCD)); require(kMCDPriceMantissa != 0, "Mint: get Kine MCD price zero"); CalculateVars memory vars; // KUSD has 18 decimals // KMCD has 18 decimals // kMCDPriceMantissa is KMCD's price (quoted by KUSD, has 6 decimals) scaled by 1e36 / KMCD's decimals = 1e36 / 1e18 = 1e18 // so the calculation of equivalent Kine MCD amount is as below // kUSDAmount 1e12 * 1e6 kUSDAmount * 1e18 // equivalentKMCDAmount = ----------- * ------------------ * 1e18 = ----------------- // 1e18 kMCDPriceMantissa kMCDPriceMantissa vars.equivalentKMCDAmount = kUSDAmount.mul(1e18).div(kMCDPriceMantissa); // call KMCD contract to borrow Kine MCD for user and stake them kMCD.borrowBehalf(msgSender, vars.equivalentKMCDAmount); // mint KUSD to user kUSD.mint(msgSender, kUSDAmount); emit Mint(msgSender, kUSDAmount, vars.equivalentKMCDAmount, accountStakes(msgSender), totalStakes()); } /** * @notice Burn repay equivalent Kine MCD for user and burn specified amount of KUSD * Burn will fail if hasn't reach start time. * @param kUSDAmount The amount of KUSD user want to burn */ function burn(uint kUSDAmount) external checkStart afterCooldown(msg.sender) updateReward(msg.sender) { address msgSender = _msgSender(); // burn user's KUSD kUSD.burn(msgSender, kUSDAmount); // calculate equivalent Kine MCD amount to specified amount of KUSD uint kMCDPriceMantissa = KineOracleInterface(controller.getOracle()).getUnderlyingPrice(address(kMCD)); require(kMCDPriceMantissa != 0, "Burn: get Kine MCD price zero"); CalculateVars memory vars; // KUSD has 18 decimals // KMCD has 18 decimals // kMCDPriceMantissa is KMCD's price (quoted by KUSD, has 6 decimals) scaled by 1e36 / KMCD's decimals = 1e36 / 1e18 = 1e18 // so the calculation of equivalent Kine MCD amount is as below // kUSDAmount 1e12 * 1e6 kUSDAmount * 1e18 // equivalentKMCDAmount = ----------- * ------------------ * 1e18 = ----------------- // 1e18 kMCDPriceMantissa kMCDPriceMantissa vars.equivalentKMCDAmount = kUSDAmount.mul(1e18).div(kMCDPriceMantissa); // call KMCD contract to repay Kine MCD for user kMCD.repayBorrowBehalf(msgSender, vars.equivalentKMCDAmount); emit Burn(msgSender, kUSDAmount, vars.equivalentKMCDAmount, accountStakes(msgSender), totalStakes()); } /** * @notice BurnMax unstake and repay all borrowed Kine MCD for user and burn equivalent KUSD */ function burnMax() external checkStart afterCooldown(msg.sender) updateReward(msg.sender) { address msgSender = _msgSender(); uint kMCDPriceMantissa = KineOracleInterface(controller.getOracle()).getUnderlyingPrice(address(kMCD)); require(kMCDPriceMantissa != 0, "BurnMax: get Kine MCD price zero"); CalculateVars memory vars; // KUSD has 18 decimals // KMCD has 18 decimals // kMCDPriceMantissa is KMCD's price (quoted by KUSD, has 6 decimals) scaled by 1e36 / KMCD's decimals = 1e36 / 1e18 = 1e18 // so the calculation of equivalent KUSD amount is as below // accountStakes kMCDPriceMantissa accountStakes * kMCDPriceMantissa // equivalentKUSDAmount = ------------- * ------------------ * 1e18 = --------------------------------- // 1e18 1e12 * 1e6 1e18 // // try to unstake all Kine MCD uint userStakes = accountStakes(msgSender); vars.equivalentKMCDAmount = userStakes; vars.equivalentKUSDAmount = userStakes.mul(kMCDPriceMantissa).div(1e18); // in case user's kUSD is not enough to unstake all mcd, then just burn all kUSD and unstake part of MCD uint kUSDbalance = kUSD.balanceOf(msgSender); if (vars.equivalentKUSDAmount > kUSDbalance) { vars.equivalentKUSDAmount = kUSDbalance; vars.equivalentKMCDAmount = kUSDbalance.mul(1e18).div(kMCDPriceMantissa); } // burn user's equivalent KUSD kUSD.burn(msgSender, vars.equivalentKUSDAmount); // call KMCD contract to repay Kine MCD for user kMCD.repayBorrowBehalf(msgSender, vars.equivalentKMCDAmount); emit BurnMax(msgSender, vars.equivalentKUSDAmount, vars.equivalentKMCDAmount, accountStakes(msgSender), totalStakes()); } /** * @notice Caller liquidates the staker's Kine MCD and seize staker's collateral. * Liquidate will fail if hasn't reach start time. * @param staker The staker of Kine MCD to be liquidated. * @param unstakeKMCDAmount The amount of Kine MCD to unstake. * @param maxBurnKUSDAmount The max amount limit of KUSD of liquidator to be burned. * @param kTokenCollateral The market in which to seize collateral from the staker. */ function liquidate(address staker, uint unstakeKMCDAmount, uint maxBurnKUSDAmount, address kTokenCollateral, uint minSeizeKToken) external checkStart updateReward(staker) { address msgSender = _msgSender(); uint kMCDPriceMantissa = KineOracleInterface(controller.getOracle()).getUnderlyingPrice(address(kMCD)); require(kMCDPriceMantissa != 0, "Liquidate: get Kine MCD price zero"); CalculateVars memory vars; // KUSD has 18 decimals // KMCD has 18 decimals // kMCDPriceMantissa is KMCD's price (quoted by KUSD, has 6 decimals) scaled by 1e36 / KMCD's decimals = 1e36 / 1e18 = 1e18 // so the calculation of equivalent KUSD amount is as below // accountStakes kMCDPriceMantissa accountStakes * kMCDPriceMantissa // equivalentKUSDAmount = ------------- * ------------------ * 1e18 = --------------------------------- // 1e18 1e12 * 1e6 1e30 // vars.equivalentKUSDAmount = unstakeKMCDAmount.mul(kMCDPriceMantissa).div(1e18); require(maxBurnKUSDAmount >= vars.equivalentKUSDAmount, "Liquidate: reach out max burn KUSD amount limit"); // burn liquidator's KUSD kUSD.burn(msgSender, vars.equivalentKUSDAmount); // call KMCD contract to liquidate staker's Kine MCD and seize collateral kMCD.liquidateBorrowBehalf(msgSender, staker, unstakeKMCDAmount, kTokenCollateral, minSeizeKToken); emit Liquidate(msgSender, staker, vars.equivalentKUSDAmount, unstakeKMCDAmount, accountStakes(staker), totalStakes()); } /** * @notice Show account's staked Kine MCD amount * @param account The account to be get MCD amount from */ function accountStakes(address account) public view returns (uint) { return kMCD.borrowBalance(account); } /// @notice Show total staked Kine MCD amount function totalStakes() public view returns (uint) { return kMCD.totalBorrows(); } /** * @notice Claim the matured rewards of caller. * Claim will fail if hasn't reach start time. */ function getReward() external checkStart updateReward(msg.sender) { uint reward = accountRewardDetails[msg.sender].accruedReward; if (reward > 0) { uint pastTime = block.timestamp.sub(accountRewardDetails[msg.sender].lastClaimTime); uint maturedReward = rewardReleasePeriod == 0 ? reward : reward.mul(pastTime).div(rewardReleasePeriod); if (maturedReward > reward) { maturedReward = reward; } accountRewardDetails[msg.sender].accruedReward = reward.sub(maturedReward); accountRewardDetails[msg.sender].lastClaimTime = block.timestamp; kine.safeTransfer(msg.sender, maturedReward); emit RewardPaid(msg.sender, maturedReward); } } /** * @notice Notify rewards has been added, trigger a new round of reward period, recalculate reward rate and duration end time. * If distributor notify rewards before this round duration end time, then the leftover rewards of this round will roll over to * next round and will be distributed together with new rewards in next round of reward period. * @param reward How many of rewards has been added for new round of reward period. */ function notifyRewardAmount(uint reward) external onlyRewardDistribution updateReward(address(0)) { if (block.timestamp > startTime) { if (block.timestamp >= periodFinish) { // @dev to avoid of rewardPerToken calculation overflow (see https://sips.synthetix.io/sips/sip-77), we check the reward to be inside a properate range // which is 2^256 / 10^18 require(reward < REWARD_OVERFLOW_CHECK, "reward rate will overflow"); rewardRate = reward.div(rewardDuration); } else { uint remaining = periodFinish.sub(block.timestamp); uint leftover = remaining.mul(rewardRate); // @dev to avoid of rewardPerToken calculation overflow (see https://sips.synthetix.io/sips/sip-77), we check the reward to be inside a properate range // which is 2^256 / 10^18 require(reward.add(leftover) < REWARD_OVERFLOW_CHECK, "reward rate will overflow"); rewardRate = reward.add(leftover).div(rewardDuration); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardDuration); emit RewardAdded(reward); } else { // @dev to avoid of rewardPerToken calculation overflow (see https://sips.synthetix.io/sips/sip-77), we check the reward to be inside a properate range // which is 2^256 / 10^18 require(reward < REWARD_OVERFLOW_CHECK, "reward rate will overflow"); rewardRate = reward.div(rewardDuration); lastUpdateTime = startTime; periodFinish = startTime.add(rewardDuration); emit RewardAdded(reward); } } /** * @notice Set new reward duration, will start a new round of reward period immediately and recalculate rewardRate. * @param newRewardDuration New duration of each reward period round. */ function _setRewardDuration(uint newRewardDuration) external onlyOwner updateReward(address(0)) { uint oldRewardDuration = rewardDuration; rewardDuration = newRewardDuration; if (block.timestamp > startTime) { if (block.timestamp >= periodFinish) { rewardRate = 0; } else { uint remaining = periodFinish.sub(block.timestamp); uint leftover = remaining.mul(rewardRate); rewardRate = leftover.div(rewardDuration); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardDuration); } else { rewardRate = rewardRate.mul(oldRewardDuration).div(rewardDuration); lastUpdateTime = startTime; periodFinish = startTime.add(rewardDuration); } emit NewRewardDuration(oldRewardDuration, newRewardDuration); } /** * @notice Set new reward release period. The unclaimed rewards will be affected immediately. * @param newRewardReleasePeriod New release period of how long all earned rewards will be matured each time * before user claim reward. */ function _setRewardReleasePeriod(uint newRewardReleasePeriod) external onlyOwner updateReward(address(0)) { uint oldRewardReleasePeriod = rewardReleasePeriod; rewardReleasePeriod = newRewardReleasePeriod; emit NewRewardReleasePeriod(oldRewardReleasePeriod, newRewardReleasePeriod); } function _setCooldownTime(uint newCooldownTime) external onlyOwner { uint oldCooldown = burnCooldownTime; burnCooldownTime = newCooldownTime; emit NewBurnCooldownTime(oldCooldown, newCooldownTime); } /** * @notice Mint KUSD to treasury account to keep on-chain KUSD consist with off-chain trading system * @param amount The amount of KUSD to mint to treasury */ function treasuryMint(uint amount) external onlyTreasury { kUSD.mint(vault, amount); emit TreasuryMint(amount); } /** * @notice Burn KUSD from treasury account to keep on-chain KUSD consist with off-chain trading system * @param amount The amount of KUSD to burn from treasury */ function treasuryBurn(uint amount) external onlyTreasury { kUSD.burn(vault, amount); emit TreasuryBurn(amount); } /** * @notice Change treasury account to a new one * @param newTreasury New treasury account address */ function _setTreasury(address newTreasury) external onlyOwner { address oldTreasury = treasury; treasury = newTreasury; emit NewTreasury(oldTreasury, newTreasury); } /** * @notice Change vault account to a new one * @param newVault New vault account address */ function _setVault(address newVault) external onlyOwner { address oldVault = vault; vault = newVault; emit NewVault(oldVault, newVault); } /** * @notice Change KMCD contract address to a new one. * @param newKMCD New KMCD contract address. */ function _setKMCD(address newKMCD) external onlyOwner { address oldKMCD = address(kMCD); kMCD = IKMCD(newKMCD); emit NewKMCD(oldKMCD, newKMCD); } /** * @notice Change KUSD contract address to a new one. * @param newKUSD New KineUSD contract address. */ function _setKUSD(address newKUSD) external onlyOwner { address oldKUSD = address(kUSD); kUSD = IKineUSD(newKUSD); emit NewKUSD(oldKUSD, newKUSD); } /** * @notice Change Kine contract address to a new one. * @param newKine New Kine contract address. */ function _setKine(address newKine) external onlyOwner { address oldKine = address(kine); kine = IERC20(newKine); emit NewKine(oldKine, newKine); } /** * @notice Change Kine Controller address to a new one. * @param newController New Controller contract address. */ function _setController(address newController) external onlyOwner { address oldController = address(controller); controller = KineControllerInterface(newController); emit NewController(oldController, newController); } } pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; /** * @title KineOracleInterface brief abstraction of Price Oracle */ interface KineOracleInterface { /** * @notice Get the underlying collateral price of given kToken. * @dev Returned kToken underlying price is scaled by 1e(36 - underlying token decimals) */ function getUnderlyingPrice(address kToken) external view returns (uint); /** * @notice Post prices of tokens owned by Kine. * @param messages Signed price data of tokens * @param signatures Signatures used to recover reporter public key * @param symbols Token symbols */ function postPrices(bytes[] calldata messages, bytes[] calldata signatures, string[] calldata symbols) external; /** * @notice Post Kine MCD price. */ function postMcdPrice(uint mcdPrice) external; /** * @notice Get the reporter address. */ function reporter() external returns (address); } pragma solidity ^0.5.16; /** Copyright 2020 Compound Labs, Inc. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/ComptrollerInterface.sol * Modified to work in the Kine system. * Main modifications: * 1. removed Comp token related logics. * 2. removed interest rate model related logics. * 3. removed error code propagation mechanism to fail fast and loudly */ contract KineControllerInterface { /// @notice Indicator that this is a Controller contract (for inspection) bool public constant isController = true; /// @notice oracle getter function function getOracle() external view returns (address); /*** Assets You Are In ***/ function enterMarkets(address[] calldata kTokens) external; function exitMarket(address kToken) external; /*** Policy Hooks ***/ function mintAllowed(address kToken, address minter, uint mintAmount) external returns (bool, string memory); function mintVerify(address kToken, address minter, uint mintAmount, uint mintTokens) external; function redeemAllowed(address kToken, address redeemer, uint redeemTokens) external returns (bool, string memory); function redeemVerify(address kToken, address redeemer, uint redeemTokens) external; function borrowAllowed(address kToken, address borrower, uint borrowAmount) external returns (bool, string memory); function borrowVerify(address kToken, address borrower, uint borrowAmount) external; function repayBorrowAllowed( address kToken, address payer, address borrower, uint repayAmount) external returns (bool, string memory); function repayBorrowVerify( address kToken, address payer, address borrower, uint repayAmount) external; function liquidateBorrowAllowed( address kTokenBorrowed, address kTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (bool, string memory); function liquidateBorrowVerify( address kTokenBorrowed, address kTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external; function seizeAllowed( address kTokenCollateral, address kTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (bool, string memory); function seizeVerify( address kTokenCollateral, address kTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external; function transferAllowed(address kToken, address src, address dst, uint transferTokens) external returns (bool, string memory); function transferVerify(address kToken, address src, address dst, uint transferTokens) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address target, address kTokenBorrowed, address kTokenCollateral, uint repayAmount) external view returns (uint); } pragma solidity ^0.5.16; import "./Ownable.sol"; /** * @title KUSDMinterDelegate * @author Kine */ contract KUSDMinterDelegate is Ownable { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Implementation address */ address public implementation; } pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } 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 "./Context.sol"; import "./IERC20.sol"; import "./KineSafeMath.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 Context, IERC20 { using KineSafeMath 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")); } } pragma solidity ^0.5.0; import "./IERC20.sol"; import "./KineSafeMath.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 ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using KineSafeMath 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.0; import "./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 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(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; } } 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; } } 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. */ /** * Original work from OpenZeppelin: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.0/contracts/math/SafeMath.sol * changes we made: * 1. add two methods that take errorMessage as input parameter */ library KineSafeMath { /** * @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 addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. * added by Kine */ function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); 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 multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. * added by Kine */ function mul(uint256 a, uint256 b, string memory errorMessage) 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, errorMessage); 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.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"); } }
IKMCD, a simplified interface of KMCD (see KMCD)
interface IKMCD { function borrowBehalf(address payable borrower, uint borrowAmount) external; function repayBorrowBehalf(address borrower, uint repayAmount) external; function liquidateBorrowBehalf(address liquidator, address borrower, uint repayAmount, address kTokenCollateral, uint minSeizeKToken) external; function borrowBalance(address account) external view returns (uint); function totalBorrows() external view returns (uint); }
300,553
./full_match/7777777/0x57Afa7725FcfeB671Af16aD367E1E286BC279402/sources/library/ColorLib.sol
get gradient color strings for the given addresss
function gradientForAddress( address addr ) internal pure returns (bytes[5] memory) { unchecked { bytes32 addrBytes = bytes32(uint256(uint160(addr))); uint256 startLightness = (uint256(uint8(addrBytes[31 - 2])) * 5) / 34 + uint256 endLightness = 97; endLightness += (((uint256(uint8(addrBytes[31 - 8])) * 5) / 51) + endLightness /= 2; uint256 startSaturation = uint256(uint8(addrBytes[31 - 7])) / 16 + uint256 endSaturation = uint256(uint8(addrBytes[31 - 10]) * 11) / 128 + if (endSaturation > startSaturation - 10) { endSaturation = startSaturation - 10; } return [ lerpHue( uint8(addrBytes[31 - 3]), uint8(addrBytes[31 - 6]) % 2, startHue, 0 ), lerpSaturation( uint8(addrBytes[31 - 3]) % 2, startSaturation, endSaturation, 100 ), lerpLightness( uint8(addrBytes[31 - 5]) % 2, startLightness, endLightness, 100 ) ), lerpHue( uint8(addrBytes[31 - 3]), uint8(addrBytes[31 - 6]) % 2, startHue, 10 ), lerpSaturation( uint8(addrBytes[31 - 3]) % 2, startSaturation, endSaturation, 90 ), lerpLightness( uint8(addrBytes[31 - 5]) % 2, startLightness, endLightness, 90 ) ), lerpHue( uint8(addrBytes[31 - 3]), uint8(addrBytes[31 - 6]) % 2, startHue, 70 ), lerpSaturation( uint8(addrBytes[31 - 3]) % 2, startSaturation, endSaturation, 70 ), lerpLightness( uint8(addrBytes[31 - 5]) % 2, startLightness, endLightness, 70 ) ), lerpHue( uint8(addrBytes[31 - 3]), uint8(addrBytes[31 - 6]) % 2, startHue, 90 ), lerpSaturation( uint8(addrBytes[31 - 3]) % 2, startSaturation, endSaturation, 20 ), lerpLightness( uint8(addrBytes[31 - 5]) % 2, startLightness, endLightness, 20 ) ), lerpHue( uint8(addrBytes[31 - 3]), uint8(addrBytes[31 - 6]) % 2, startHue, 100 ), lerpSaturation( uint8(addrBytes[31 - 3]) % 2, startSaturation, endSaturation, 0 ), startLightness ) ]; } }
7,098,265
/** * Created on 2018-06-05 16:37 * @summary: Our NFT Minting Contract which inherits ERC721 capability from LSNFT * @author: Fazri Zubair & Farhan Khwaja */ pragma solidity ^0.4.23; pragma solidity ^0.4.23; /* NFT Metadata Schema { "title": "Asset Metadata", "type": "object", "properties": { "name": { "type": "string", "description": "Identifies the asset to which this NFT represents", }, "description": { "type": "string", "description": "Describes the asset to which this NFT represents", }, "image": { "type": "string", "description": "A URI pointing to a resource with mime type image/* representing the asset to which this NFT represents. Consider making any images at a width between 320 and 1080 pixels and aspect ratio between 1.91:1 and 4:5 inclusive.", } } } */ /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } } /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(addr) } return size > 0; } } /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic { event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() public view returns (string _name); function symbol() public view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is ERC721Basic { using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 public constant ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require (ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require (isApprovedOrOwner(msg.sender, _tokenId)); _; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require (_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require (owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * @dev The zero address indicates there is no approved address. * @dev There can only be one approved address per token at a given time. * @dev Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require (_to != owner); require (msg.sender == owner || isApprovedForAll(owner, msg.sender)); tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * @dev An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require (_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { require (_from != address(0)); require (_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require (checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner( address _spender, uint256 _tokenId ) internal view returns (bool) { address owner = ownerOf(_tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require (_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @dev Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require (ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require (tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { require (ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * @dev The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ 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 public 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. This function MUST use 50,000 gas or less. Return of other * than the magic value MUST result in the transaction being reverted. * Note: the contract address is always the message sender. * @param _from The sending address * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } contract ERC721Holder is ERC721Receiver { function onERC721Received( address, address, uint256, bytes ) public returns(bytes4) { return ERC721_RECEIVED; } } /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Token is ERC721, ERC721BasicToken { // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Base Server Address for Token MetaData URI string internal tokenURIBase; /** * @dev Returns an URI for a given token ID * @dev Throws if the token ID does not exist. May return an empty string. * @notice The user/developper needs to add the tokenID, in the end of URL, to * use the URI and get all details. Ex. www.<apiURL>.com/token/<tokenID> * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require (exists(_tokenId)); return tokenURIBase; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256) { require (_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * @dev Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require (_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * @dev Reverts if the token ID does not exist * @param _uri string URI to assign */ function _setTokenURIBase(string _uri) internal { tokenURIBase = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); // 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 Gets the token name * @return string representing the token name */ function name() public view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() public view returns (string) { return symbol_; } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } bytes4 constant InterfaceSignature_ERC165 = 0x01ffc9a7; /* bytes4(keccak256(&#39;supportsInterface(bytes4)&#39;)); */ bytes4 constant InterfaceSignature_ERC721Enumerable = 0x780e9d63; /* bytes4(keccak256(&#39;totalSupply()&#39;)) ^ bytes4(keccak256(&#39;tokenOfOwnerByIndex(address,uint256)&#39;)) ^ bytes4(keccak256(&#39;tokenByIndex(uint256)&#39;)); */ bytes4 constant InterfaceSignature_ERC721Metadata = 0x5b5e139f; /* bytes4(keccak256(&#39;name()&#39;)) ^ bytes4(keccak256(&#39;symbol()&#39;)) ^ bytes4(keccak256(&#39;tokenURI(uint256)&#39;)); */ bytes4 constant InterfaceSignature_ERC721 = 0x80ac58cd; /* bytes4(keccak256(&#39;balanceOf(address)&#39;)) ^ bytes4(keccak256(&#39;ownerOf(uint256)&#39;)) ^ bytes4(keccak256(&#39;approve(address,uint256)&#39;)) ^ bytes4(keccak256(&#39;getApproved(uint256)&#39;)) ^ bytes4(keccak256(&#39;setApprovalForAll(address,bool)&#39;)) ^ bytes4(keccak256(&#39;isApprovedForAll(address,address)&#39;)) ^ bytes4(keccak256(&#39;transferFrom(address,address,uint256)&#39;)) ^ bytes4(keccak256(&#39;safeTransferFrom(address,address,uint256)&#39;)) ^ bytes4(keccak256(&#39;safeTransferFrom(address,address,uint256,bytes)&#39;)); */ bytes4 public constant InterfaceSignature_ERC721Optional =- 0x4f558e79; /* bytes4(keccak256(&#39;exists(uint256)&#39;)); */ /** * @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). * @dev Returns true for any standardized interfaces implemented by this contract. * @param _interfaceID bytes4 the interface to check for * @return true for any standardized interfaces implemented by this contract. */ function supportsInterface(bytes4 _interfaceID) external view returns (bool) { return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721) || (_interfaceID == InterfaceSignature_ERC721Enumerable) || (_interfaceID == InterfaceSignature_ERC721Metadata)); } function implementsERC721() public pure returns (bool) { return true; } } /* Lucid Sight, Inc. ERC-721 Collectibles. * @title LSNFT - Lucid Sight, Inc. Non-Fungible Token * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) */ contract LSNFT is ERC721Token { /*** EVENTS ***/ /// @dev The Created event is fired whenever a new collectible comes into existence. event Created(address owner, uint256 tokenId); /*** DATATYPES ***/ struct NFT { // The sequence of potential attributes a Collectible has and can provide in creation events. Used in Creation logic to spwan new Cryptos uint256 attributes; // Current Game Card identifier uint256 currentGameCardId; // MLB Game Identifier (if asset generated as a game reward) uint256 mlbGameId; // player orverride identifier uint256 playerOverrideId; // official MLB Player ID uint256 mlbPlayerId; // earnedBy : In some instances we may want to retroactively write which MLB player triggered // the event that created a Legendary Trophy. This optional field should be able to be written // to after generation if we determine an event was newsworthy enough uint256 earnedBy; // asset metadata uint256 assetDetails; // Attach/Detach Flag uint256 isAttached; } NFT[] allNFTs; function isLSNFT() public view returns (bool) { return true; } /// For creating NFT function _createNFT ( uint256[5] _nftData, address _owner, uint256 _isAttached) internal returns(uint256) { NFT memory _lsnftObj = NFT({ attributes : _nftData[1], currentGameCardId : 0, mlbGameId : _nftData[2], playerOverrideId : _nftData[3], assetDetails: _nftData[0], isAttached: _isAttached, mlbPlayerId: _nftData[4], earnedBy: 0 }); uint256 newLSNFTId = allNFTs.push(_lsnftObj) - 1; _mint(_owner, newLSNFTId); // Created event emit Created(_owner, newLSNFTId); return newLSNFTId; } /// @dev Gets attributes of NFT function _getAttributesOfToken(uint256 _tokenId) internal returns(NFT) { NFT storage lsnftObj = allNFTs[_tokenId]; return lsnftObj; } function _approveForSale(address _owner, address _to, uint256 _tokenId) internal { address owner = ownerOf(_tokenId); require (_to != owner); require (_owner == owner || isApprovedForAll(owner, _owner)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; emit Approval(_owner, _to, _tokenId); } } } /** Controls state and access rights for contract functions * @title Operational Control * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) * Inspired and adapted from contract created by OpenZeppelin * Ref: https://github.com/OpenZeppelin/zeppelin-solidity/ */ contract OperationalControl { /// Facilitates access & control for the game. /// Roles: /// -The Managers (Primary/Secondary): Has universal control of all elements (No ability to withdraw) /// -The Banker: The Bank can withdraw funds and adjust fees / prices. /// -otherManagers: Contracts that need access to functions for gameplay /// @dev Emited when contract is upgraded event ContractUpgrade(address newContract); /// @dev The addresses of the accounts (or contracts) that can execute actions within each roles. address public managerPrimary; address public managerSecondary; address public bankManager; // Contracts that require access for gameplay mapping(address => uint8) public otherManagers; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; // @dev Keeps track whether the contract erroredOut. When that is true, most actions are blocked & refund can be claimed bool public error = false; /** * @dev Operation modifiers for limiting access only to Managers */ modifier onlyManager() { require (msg.sender == managerPrimary || msg.sender == managerSecondary); _; } /** * @dev Operation modifiers for limiting access to only Banker */ modifier onlyBanker() { require (msg.sender == bankManager); _; } /** * @dev Operation modifiers for any Operators */ modifier anyOperator() { require ( msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager || otherManagers[msg.sender] == 1 ); _; } /** * @dev Operation modifier for any Other Manager */ modifier onlyOtherManagers() { require (otherManagers[msg.sender] == 1); _; } /** * @dev Assigns a new address to act as the Primary Manager. * @param _newGM New primary manager address */ function setPrimaryManager(address _newGM) external onlyManager { require (_newGM != address(0)); managerPrimary = _newGM; } /** * @dev Assigns a new address to act as the Secondary Manager. * @param _newGM New Secondary Manager Address */ function setSecondaryManager(address _newGM) external onlyManager { require (_newGM != address(0)); managerSecondary = _newGM; } /** * @dev Assigns a new address to act as the Banker. * @param _newBK New Banker Address */ function setBanker(address _newBK) external onlyManager { require (_newBK != address(0)); bankManager = _newBK; } /// @dev Assigns a new address to act as the Other Manager. (State = 1 is active, 0 is disabled) function setOtherManager(address _newOp, uint8 _state) external onlyManager { require (_newOp != address(0)); otherManagers[_newOp] = _state; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require (!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require (paused); _; } /// @dev Modifier to allow actions only when the contract has Error modifier whenError { require (error); _; } /** * @dev Called by any Operator role to pause the contract. * Used only if a bug or exploit is discovered (Here to limit losses / damage) */ function pause() external onlyManager whenNotPaused { paused = true; } /** * @dev Unpauses the smart contract. Can only be called by the Game Master */ function unpause() public onlyManager whenPaused { // can&#39;t unpause if contract was upgraded paused = false; } /** * @dev Errors out the contract thus mkaing the contract non-functionable */ function hasError() public onlyManager whenPaused { error = true; } /** * @dev Removes the Error Hold from the contract and resumes it for working */ function noError() public onlyManager whenPaused { error = false; } } /** Base contract for DodgersNFT Collectibles. Holds all commons, events and base variables. * @title Lucid Sight MLB NFT 2018 * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) */ contract CollectibleBase is LSNFT { /*** EVENTS ***/ /// @dev Event emitted when an attribute of the player is updated event AssetUpdated(uint256 tokenId); /*** STORAGE ***/ /// @dev A mapping of Team Id to Team Sequence Number to Collectible mapping (uint256 => mapping (uint32 => uint256) ) public nftTeamIdToSequenceIdToCollectible; /// @dev A mapping from Team IDs to the Sequqence Number . mapping (uint256 => uint32) public nftTeamIndexToCollectibleCount; /// @dev Array to hold details on attachment for each LS NFT Collectible mapping(uint256 => uint256[]) public nftCollectibleAttachments; /// @dev Mapping to control the asset generation per season. mapping(uint256 => uint256) public generationSeasonController; /// @dev Mapping for generation Season Dict. mapping(uint256 => uint256) public generationSeasonDict; /// @dev internal function to update player override id function _updatePlayerOverrideId(uint256 _tokenId, uint256 _newPlayerOverrideId) internal { // Get Token Obj NFT storage lsnftObj = allNFTs[_tokenId]; lsnftObj.playerOverrideId = _newPlayerOverrideId; // Update Token Data with new updated attributes allNFTs[_tokenId] = lsnftObj; emit AssetUpdated(_tokenId); } /** * @dev An internal method that helps in generation of new NFT Collectibles * @param _teamId teamId of the asset/token/collectible * @param _attributes attributes of asset/token/collectible * @param _owner owner of asset/token/collectible * @param _isAttached State of the asset (attached or dettached) * @param _nftData Array of data required for creation */ function _createNFTCollectible( uint8 _teamId, uint256 _attributes, address _owner, uint256 _isAttached, uint256[5] _nftData ) internal returns (uint256) { uint256 generationSeason = (_attributes % 1000000).div(1000); require (generationSeasonController[generationSeason] == 1); uint32 _sequenceId = getSequenceId(_teamId); uint256 newNFTCryptoId = _createNFT(_nftData, _owner, _isAttached); nftTeamIdToSequenceIdToCollectible[_teamId][_sequenceId] = newNFTCryptoId; nftTeamIndexToCollectibleCount[_teamId] = _sequenceId; return newNFTCryptoId; } function getSequenceId(uint256 _teamId) internal returns (uint32) { return (nftTeamIndexToCollectibleCount[_teamId] + 1); } /** * @dev Internal function, Helps in updating the Creation Stop Time * @param _season Season UINT Code * @param _value 0 - Not allowed, 1 - Allowed */ function _updateGenerationSeasonFlag(uint256 _season, uint8 _value) internal { generationSeasonController[_season] = _value; } /** @param _owner The owner whose ships tokens we are interested in. * @dev This method MUST NEVER be called by smart contract code. First, it&#39;s fairly * expensive (it walks the entire Collectibles owners array looking for NFT belonging to owner) */ function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalItems = balanceOf(_owner); uint256 resultIndex = 0; // We count on the fact that all Collectible have IDs starting at 0 and increasing // sequentially up to the total count. uint256 _assetId; for (_assetId = 0; _assetId < totalItems; _assetId++) { result[resultIndex] = tokenOfOwnerByIndex(_owner,_assetId); resultIndex++; } return result; } } /// @dev internal function to update MLB player id function _updateMLBPlayerId(uint256 _tokenId, uint256 _newMLBPlayerId) internal { // Get Token Obj NFT storage lsnftObj = allNFTs[_tokenId]; lsnftObj.mlbPlayerId = _newMLBPlayerId; // Update Token Data with new updated attributes allNFTs[_tokenId] = lsnftObj; emit AssetUpdated(_tokenId); } /// @dev internal function to update asset earnedBy value for an asset/token function _updateEarnedBy(uint256 _tokenId, uint256 _earnedBy) internal { // Get Token Obj NFT storage lsnftObj = allNFTs[_tokenId]; lsnftObj.earnedBy = _earnedBy; // Update Token Data with new updated attributes allNFTs[_tokenId] = lsnftObj; emit AssetUpdated(_tokenId); } } /* Handles creating new Collectibles for promo and seed. * @title CollectibleMinting Minting * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) * Inspired and adapted from KittyCore.sol created by Axiom Zen * Ref: ETH Contract - 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d */ contract CollectibleMinting is CollectibleBase, OperationalControl { uint256 public rewardsRedeemed = 0; /// @dev Counts the number of promo collectibles that can be made per-team uint256[31] public promoCreatedCount; /// @dev Counts the number of seed collectibles that can be made in total uint256 public seedCreatedCount; /// @dev Bool to toggle batch support bool public isBatchSupported = true; /// @dev A mapping of contracts that can trigger functions mapping (address => bool) public contractsApprovedList; /** * @dev Helps to toggle batch supported flag * @param _flag The flag */ function updateBatchSupport(bool _flag) public onlyManager { isBatchSupported = _flag; } modifier canCreate() { require (contractsApprovedList[msg.sender] || msg.sender == managerPrimary || msg.sender == managerSecondary); _; } /** * @dev Add an address to the Approved List * @param _newAddress The new address to be approved for interaction with the contract */ function addToApproveList(address _newAddress) public onlyManager { require (!contractsApprovedList[_newAddress]); contractsApprovedList[_newAddress] = true; } /** * @dev Remove an address from Approved List * @param _newAddress The new address to be approved for interaction with the contract */ function removeFromApproveList(address _newAddress) public onlyManager { require (contractsApprovedList[_newAddress]); delete contractsApprovedList[_newAddress]; } /** * @dev Generates promo collectibles. Only callable by Game Master, with isAttached as 0. * @notice The generation of an asset if limited via the generationSeasonController * @param _teamId teamId of the asset/token/collectible * @param _posId position of the asset/token/collectible * @param _attributes attributes of asset/token/collectible * @param _owner owner of asset/token/collectible * @param _gameId mlb game Identifier * @param _playerOverrideId player override identifier * @param _mlbPlayerId official mlb player identifier */ function createPromoCollectible( uint8 _teamId, uint8 _posId, uint256 _attributes, address _owner, uint256 _gameId, uint256 _playerOverrideId, uint256 _mlbPlayerId) external canCreate whenNotPaused returns (uint256) { address nftOwner = _owner; if (nftOwner == address(0)) { nftOwner = managerPrimary; } if(allNFTs.length > 0) { promoCreatedCount[_teamId]++; } uint32 _sequenceId = getSequenceId(_teamId); uint256 assetDetails = uint256(uint64(now)); assetDetails |= uint256(_sequenceId)<<64; assetDetails |= uint256(_teamId)<<96; assetDetails |= uint256(_posId)<<104; uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId]; return _createNFTCollectible(_teamId, _attributes, nftOwner, 0, _nftData); } /** * @dev Generaes a new single seed Collectible, with isAttached as 0. * @notice Helps in creating seed collectible.The generation of an asset if limited via the generationSeasonController * @param _teamId teamId of the asset/token/collectible * @param _posId position of the asset/token/collectible * @param _attributes attributes of asset/token/collectible * @param _owner owner of asset/token/collectible * @param _gameId mlb game Identifier * @param _playerOverrideId player override identifier * @param _mlbPlayerId official mlb player identifier */ function createSeedCollectible( uint8 _teamId, uint8 _posId, uint256 _attributes, address _owner, uint256 _gameId, uint256 _playerOverrideId, uint256 _mlbPlayerId) external canCreate whenNotPaused returns (uint256) { address nftOwner = _owner; if (nftOwner == address(0)) { nftOwner = managerPrimary; } seedCreatedCount++; uint32 _sequenceId = getSequenceId(_teamId); uint256 assetDetails = uint256(uint64(now)); assetDetails |= uint256(_sequenceId)<<64; assetDetails |= uint256(_teamId)<<96; assetDetails |= uint256(_posId)<<104; uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId]; return _createNFTCollectible(_teamId, _attributes, nftOwner, 0, _nftData); } /** * @dev Generate new Reward Collectible and transfer it to the owner, with isAttached as 0. * @notice Helps in redeeming the Rewards using our Oracle. Creates & transfers the asset to the redeemer (_owner) * The generation of an asset if limited via the generationSeasonController * @param _teamId teamId of the asset/token/collectible * @param _posId position of the asset/token/collectible * @param _attributes attributes of asset/token/collectible * @param _owner owner (redeemer) of asset/token/collectible * @param _gameId mlb game Identifier * @param _playerOverrideId player override identifier * @param _mlbPlayerId official mlb player identifier */ function createRewardCollectible ( uint8 _teamId, uint8 _posId, uint256 _attributes, address _owner, uint256 _gameId, uint256 _playerOverrideId, uint256 _mlbPlayerId) external canCreate whenNotPaused returns (uint256) { address nftOwner = _owner; if (nftOwner == address(0)) { nftOwner = managerPrimary; } rewardsRedeemed++; uint32 _sequenceId = getSequenceId(_teamId); uint256 assetDetails = uint256(uint64(now)); assetDetails |= uint256(_sequenceId)<<64; assetDetails |= uint256(_teamId)<<96; assetDetails |= uint256(_posId)<<104; uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId]; return _createNFTCollectible(_teamId, _attributes, nftOwner, 0, _nftData); } /** * @dev Generate new ETH Card Collectible, with isAttached as 2. * @notice Helps to generate Collectibles/Tokens/Asset and transfer to ETH Cards, * which can be redeemed using our web-app.The generation of an asset if limited via the generationSeasonController * @param _teamId teamId of the asset/token/collectible * @param _posId position of the asset/token/collectible * @param _attributes attributes of asset/token/collectible * @param _owner owner of asset/token/collectible * @param _gameId mlb game Identifier * @param _playerOverrideId player override identifier * @param _mlbPlayerId official mlb player identifier */ function createETHCardCollectible ( uint8 _teamId, uint8 _posId, uint256 _attributes, address _owner, uint256 _gameId, uint256 _playerOverrideId, uint256 _mlbPlayerId) external canCreate whenNotPaused returns (uint256) { address nftOwner = _owner; if (nftOwner == address(0)) { nftOwner = managerPrimary; } rewardsRedeemed++; uint32 _sequenceId = getSequenceId(_teamId); uint256 assetDetails = uint256(uint64(now)); assetDetails |= uint256(_sequenceId)<<64; assetDetails |= uint256(_teamId)<<96; assetDetails |= uint256(_posId)<<104; uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId]; return _createNFTCollectible(_teamId, _attributes, nftOwner, 2, _nftData); } } /* @title Interface for DodgersNFT Contract * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) */ contract SaleManager { function createSale(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _owner) external; } /** * DodgersNFT manages all aspects of the Lucid Sight, Inc. CryptoBaseball. * @title DodgersNFT * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) */ contract DodgersNFT is CollectibleMinting { /// @dev Set in case the DodgersNFT contract requires an upgrade address public newContractAddress; string public constant MLB_Legal = "Major League Baseball trademarks and copyrights are used with permission of the applicable MLB entity. All rights reserved."; // Time LS Oracle has to respond to detach requests uint32 public detachmentTime = 0; // Indicates if attached system is Active (Transfers will be blocked if attached and active) bool public attachedSystemActive; // Sale Manager Contract SaleManager public saleManagerAddress; /** * @dev DodgersNFT constructor. */ constructor() public { // Starts paused. paused = true; managerPrimary = msg.sender; managerSecondary = msg.sender; bankManager = msg.sender; name_ = "LucidSight-DODGERS-NFT"; symbol_ = "DNFTCB"; } /** * @dev Sets the address for the NFT Contract * @param _saleManagerAddress The nft address */ function setSaleManagerAddress(address _saleManagerAddress) public onlyManager { require (_saleManagerAddress != address(0)); saleManagerAddress = SaleManager(_saleManagerAddress); } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { uint256 isAttached = checkIsAttached(_tokenId); if(isAttached == 2) { //One-Time Auth for Physical Card Transfers require (msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager || otherManagers[msg.sender] == 1 ); updateIsAttached(_tokenId, 0); } else if(attachedSystemActive == true && isAttached >= 1) { require (msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager || otherManagers[msg.sender] == 1 ); } else { require (isApprovedOrOwner(msg.sender, _tokenId)); } _; } /** * @dev Used to mark the smart contract as upgraded, in case of a issue * @param _v2Address The new contract address */ function setNewAddress(address _v2Address) external onlyManager { require (_v2Address != address(0)); newContractAddress = _v2Address; emit ContractUpgrade(_v2Address); } /** * @dev Returns all the relevant information about a specific Collectible. * @notice Get details about your collectible * @param _tokenId The token identifier * @return isAttached Is Object attached * @return teamId team identifier of the asset/token/collectible * @return positionId position identifier of the asset/token/collectible * @return creationTime creation timestamp * @return attributes attribute of the asset/token/collectible * @return currentGameCardId current game card of the asset/token/collectible * @return mlbGameID mlb game identifier in which the asset/token/collectible was generated * @return playerOverrideId player override identifier of the asset/token/collectible * @return playerStatus status of the player (Rookie/Veteran/Historical) * @return playerHandedness handedness of the asset * @return mlbPlayerId official MLB Player Identifier */ function getCollectibleDetails(uint256 _tokenId) external view returns ( uint256 isAttached, uint32 sequenceId, uint8 teamId, uint8 positionId, uint64 creationTime, uint256 attributes, uint256 playerOverrideId, uint256 mlbGameId, uint256 currentGameCardId, uint256 mlbPlayerId, uint256 earnedBy, uint256 generationSeason ) { NFT memory obj = _getAttributesOfToken(_tokenId); attributes = obj.attributes; currentGameCardId = obj.currentGameCardId; mlbGameId = obj.mlbGameId; playerOverrideId = obj.playerOverrideId; mlbPlayerId = obj.mlbPlayerId; creationTime = uint64(obj.assetDetails); sequenceId = uint32(obj.assetDetails>>64); teamId = uint8(obj.assetDetails>>96); positionId = uint8(obj.assetDetails>>104); isAttached = obj.isAttached; earnedBy = obj.earnedBy; generationSeason = generationSeasonDict[(obj.attributes % 1000000) / 1000]; } /** * @dev This is public rather than external so we can call super.unpause * without using an expensive CALL. */ function unpause() public onlyManager { /// Actually unpause the contract. super.unpause(); } /** * @dev Helper function to get the teamID of a collectible.To avoid using getCollectibleDetails * @notice Returns the teamID associated with the asset/collectible/token * @param _tokenId The token identifier */ function getTeamId(uint256 _tokenId) external view returns (uint256) { NFT memory obj = _getAttributesOfToken(_tokenId); uint256 teamId = uint256(uint8(obj.assetDetails>>96)); return uint256(teamId); } /** * @dev Helper function to get the position of a collectible.To avoid using getCollectibleDetails * @notice Returns the position of the asset/collectible/token * @param _tokenId The token identifier */ function getPositionId(uint256 _tokenId) external view returns (uint256) { NFT memory obj = _getAttributesOfToken(_tokenId); uint256 positionId = uint256(uint8(obj.assetDetails>>104)); return positionId; } /** * @dev Helper function to get the game card. To avoid using getCollectibleDetails * @notice Returns the gameCard associated with the asset/collectible/token * @param _tokenId The token identifier */ function getGameCardId(uint256 _tokenId) public view returns (uint256) { NFT memory obj = _getAttributesOfToken(_tokenId); return obj.currentGameCardId; } /** * @dev Returns isAttached property value for an asset/collectible/token * @param _tokenId The token identifier */ function checkIsAttached(uint256 _tokenId) public view returns (uint256) { NFT memory obj = _getAttributesOfToken(_tokenId); return obj.isAttached; } /** * @dev Helper function to get the attirbute of the collectible.To avoid using getCollectibleDetails * @notice Returns the ability of an asset/collectible/token from attributes. * @param _tokenId The token identifier * @return ability ability of the asset */ function getAbilitiesForCollectibleId(uint256 _tokenId) external view returns (uint256 ability) { NFT memory obj = _getAttributesOfToken(_tokenId); uint256 _attributes = uint256(obj.attributes); ability = (_attributes % 1000); } /** * @dev Only allows trasnctions to go throught if the msg.sender is in the apporved list * @notice Updates the gameCardID properrty of the asset * @param _gameCardNumber The game card number * @param _playerId The player identifier */ function updateCurrentGameCardId(uint256 _gameCardNumber, uint256 _playerId) public whenNotPaused { require (contractsApprovedList[msg.sender]); NFT memory obj = _getAttributesOfToken(_playerId); obj.currentGameCardId = _gameCardNumber; if ( _gameCardNumber == 0 ) { obj.isAttached = 0; } else { obj.isAttached = 1; } allNFTs[_playerId] = obj; } /** * @dev Only Manager can add an attachment (special events) to the collectible * @notice Adds an attachment to collectible. * @param _tokenId The token identifier * @param _attachment The attachment */ function addAttachmentToCollectible ( uint256 _tokenId, uint256 _attachment) external onlyManager whenNotPaused { require (exists(_tokenId)); nftCollectibleAttachments[_tokenId].push(_attachment); emit AssetUpdated(_tokenId); } /** * @dev It will remove the attachment form the collectible. We will need to re-add all attachment(s) if removed. * @notice Removes all attachments from collectible. * @param _tokenId The token identifier */ function removeAllAttachmentsFromCollectible(uint256 _tokenId) external onlyManager whenNotPaused { require (exists(_tokenId)); delete nftCollectibleAttachments[_tokenId]; emit AssetUpdated(_tokenId); } /** * @notice Transfers the ownership of NFT from one address to another address * @dev responsible for gifting assets to other user. * @param _to to address * @param _tokenId The token identifier */ function giftAsset(address _to, uint256 _tokenId) public whenNotPaused { safeTransferFrom(msg.sender, _to, _tokenId); } /** * @dev responsible for setting the tokenURI. * @notice The user/developper needs to add the tokenID, in the end of URL, to * use the URI and get all details. Ex. www.<apiURL>.com/token/<tokenID> * @param _tokenURI The token uri */ function setTokenURIBase (string _tokenURI) public anyOperator { _setTokenURIBase(_tokenURI); } /** * @dev Allowed to be called by onlyGameManager to update a certain collectible playerOverrideID * @notice Sets the player override identifier. * @param _tokenId The token identifier * @param _newOverrideId The new player override identifier */ function setPlayerOverrideId(uint256 _tokenId, uint256 _newOverrideId) public onlyManager whenNotPaused { require (exists(_tokenId)); _updatePlayerOverrideId(_tokenId, _newOverrideId); } /** * @notice Updates the Generation Season Controller. * @dev Allowed to be called by onlyGameManager to update the generation season. * this helps to control the generation of collectible. * @param _season Season UINT representation * @param _value 0-Not allowed, 1-open, >=2 Locked Forever */ function updateGenerationStopTime(uint256 _season, uint8 _value ) public onlyManager whenNotPaused { require (generationSeasonController[_season] == 1 && _value != 0); _updateGenerationSeasonFlag(_season, _value); } /** * @dev set Generation Season Controller, can only be called by Managers._season can be [0,1,2,3..] and * _value can be [0,1,N]. * @notice _value of 1: means generation of collectible is allowed. anything, apart from 1, wont allow generating assets for that season. * @param _season Season UINT representation */ function setGenerationSeasonController(uint256 _season) public onlyManager whenNotPaused { require (generationSeasonController[_season] == 0); _updateGenerationSeasonFlag(_season, 1); } /** * @dev Adding value to DICT helps in showing the season value in getCollectibleDetails * @notice Updates the Generation Season Dict. * @param _season Season UINT representation * @param _value 0-Not allowed,1-allowed */ function updateGenerationDict(uint256 _season, uint64 _value) public onlyManager whenNotPaused { require (generationSeasonDict[_season] <= 1); generationSeasonDict[_season] = _value; } /** * @dev Helper function to avoid calling getCollectibleDetails * @notice Gets the MLB player Id from the player attributes * @param _tokenId The token identifier * @return playerId MLB Player Identifier */ function getPlayerId(uint256 _tokenId) external view returns (uint256 playerId) { NFT memory obj = _getAttributesOfToken(_tokenId); playerId = ((obj.attributes.div(100000000000000000)) % 1000); } /** * @dev Helper function to avoid calling getCollectibleDetails * @notice Gets the attachments for an asset * @param _tokenId The token identifier * @return attachments */ function getAssetAttachment(uint256 _tokenId) external view returns (uint256[]) { uint256[] _attachments = nftCollectibleAttachments[_tokenId]; uint256[] attachments; for(uint i=0;i<_attachments.length;i++){ attachments.push(_attachments[i]); } return attachments; } /** * @dev Can only be trigerred by Managers. Updates the earnedBy property of the NFT * @notice Helps in updating the earned _by property of an asset/token. * @param _tokenId asser/token identifier * @param _earnedBy New asset/token DNA */ function updateEarnedBy(uint256 _tokenId, uint256 _earnedBy) public onlyManager whenNotPaused { require (exists(_tokenId)); _updateEarnedBy(_tokenId, _earnedBy); } /** * @dev A batch function to facilitate batching of asset creation. canCreate modifier * helps in controlling who can call the function * @notice Batch Function to Create Assets * @param _teamId The team identifier * @param _attributes The attributes * @param _playerOverrideId The player override identifier * @param _mlbPlayerId The mlb player identifier * @param _to To Address */ function batchCreateAsset( uint8[] _teamId, uint256[] _attributes, uint256[] _playerOverrideId, uint256[] _mlbPlayerId, address[] _to) external canCreate whenNotPaused { require (isBatchSupported); require (_teamId.length > 0 && _attributes.length > 0 && _playerOverrideId.length > 0 && _mlbPlayerId.length > 0 && _to.length > 0); uint256 assetDetails; uint256[5] memory _nftData; for(uint ii = 0; ii < _attributes.length; ii++){ require (_to[ii] != address(0) && _teamId[ii] != 0 && _attributes.length != 0 && _mlbPlayerId[ii] != 0); assetDetails = uint256(uint64(now)); assetDetails |= uint256(getSequenceId(_teamId[ii]))<<64; assetDetails |= uint256(_teamId[ii])<<96; assetDetails |= uint256((_attributes[ii]/1000000000000000000000000000000000000000)-800)<<104; _nftData = [assetDetails, _attributes[ii], 0, _playerOverrideId[ii], _mlbPlayerId[ii]]; _createNFTCollectible(_teamId[ii], _attributes[ii], _to[ii], 0, _nftData); } } /** * @dev A batch function to facilitate batching of asset creation for ETH Cards. canCreate modifier * helps in controlling who can call the function * @notice Batch Function to Create Assets * @param _teamId The team identifier * @param _attributes The attributes * @param _playerOverrideId The player override identifier * @param _mlbPlayerId The mlb player identifier * @param _to { parameter_description } */ function batchCreateETHCardAsset( uint8[] _teamId, uint256[] _attributes, uint256[] _playerOverrideId, uint256[] _mlbPlayerId, address[] _to) external canCreate whenNotPaused { require (isBatchSupported); require (_teamId.length > 0 && _attributes.length > 0 && _playerOverrideId.length > 0 && _mlbPlayerId.length > 0 && _to.length > 0); uint256 assetDetails; uint256[5] memory _nftData; for(uint ii = 0; ii < _attributes.length; ii++){ require (_to[ii] != address(0) && _teamId[ii] != 0 && _attributes.length != 0 && _mlbPlayerId[ii] != 0); assetDetails = uint256(uint64(now)); assetDetails |= uint256(getSequenceId(_teamId[ii]))<<64; assetDetails |= uint256(_teamId[ii])<<96; assetDetails |= uint256((_attributes[ii]/1000000000000000000000000000000000000000)-800)<<104; _nftData = [assetDetails, _attributes[ii], 0, _playerOverrideId[ii], _mlbPlayerId[ii]]; _createNFTCollectible(_teamId[ii], _attributes[ii], _to[ii], 2, _nftData); } } /** * @dev Overriden TransferFrom, with the modifier canTransfer which uses our attachment system * @notice Helps in trasnferring assets * @param _from the address sending from * @param _to the address sending to * @param _tokenId The token identifier */ function transferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { // Asset should not be in play require (checkIsAttached(_tokenId) == 0); require (_from != address(0)); require (_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Facilitates batch trasnfer of collectible with multiple TO Address, depending if batch is supported on contract. * @notice Batch Trasnfer with multpple TO addresses * @param _tokenIds The token identifiers * @param _fromB the address sending from * @param _toB the address sending to */ function multiBatchTransferFrom( uint256[] _tokenIds, address[] _fromB, address[] _toB) public { require (isBatchSupported); require (_tokenIds.length > 0 && _fromB.length > 0 && _toB.length > 0); uint256 _id; address _to; address _from; for (uint256 i = 0; i < _tokenIds.length; ++i) { require (_tokenIds[i] != 0 && _fromB[i] != 0 && _toB[i] != 0); _id = _tokenIds[i]; _to = _toB[i]; _from = _fromB[i]; transferFrom(_from, _to, _id); } } /** * @dev Facilitates batch trasnfer of collectible, depending if batch is supported on contract * @notice Batch TransferFrom with the same to & from address * @param _tokenIds The asset identifiers * @param _from the address sending from * @param _to the address sending to */ function batchTransferFrom(uint256[] _tokenIds, address _from, address _to) public { require (isBatchSupported); require (_tokenIds.length > 0 && _from != address(0) && _to != address(0)); uint256 _id; for (uint256 i = 0; i < _tokenIds.length; ++i) { require (_tokenIds[i] != 0); _id = _tokenIds[i]; transferFrom(_from, _to, _id); } } /** * @dev Facilitates batch trasnfer of collectible, depending if batch is supported on contract. * Checks for collectible 0,address 0 and then performs the transfer * @notice Batch SafeTransferFrom with multiple From and to Addresses * @param _tokenIds The asset identifiers * @param _fromB the address sending from * @param _toB the address sending to */ function multiBatchSafeTransferFrom( uint256[] _tokenIds, address[] _fromB, address[] _toB ) public { require (isBatchSupported); require (_tokenIds.length > 0 && _fromB.length > 0 && _toB.length > 0); uint256 _id; address _to; address _from; for (uint256 i = 0; i < _tokenIds.length; ++i) { require (_tokenIds[i] != 0 && _fromB[i] != 0 && _toB[i] != 0); _id = _tokenIds[i]; _to = _toB[i]; _from = _fromB[i]; safeTransferFrom(_from, _to, _id); } } /** * @dev Facilitates batch trasnfer of collectible, depending if batch is supported on contract. * Checks for collectible 0,address 0 and then performs the transfer * @notice Batch SafeTransferFrom from a single address to another address * @param _tokenIds The asset identifiers * @param _from the address sending from * @param _to the address sending to */ function batchSafeTransferFrom( uint256[] _tokenIds, address _from, address _to ) public { require (isBatchSupported); require (_tokenIds.length > 0 && _from != address(0) && _to != address(0)); uint256 _id; for (uint256 i = 0; i < _tokenIds.length; ++i) { require (_tokenIds[i] != 0); _id = _tokenIds[i]; safeTransferFrom(_from, _to, _id); } } /** * @notice Batch Function to approve the spender * @dev Helps to approve a batch of collectibles * @param _tokenIds The asset identifiers * @param _spender The spender */ function batchApprove( uint256[] _tokenIds, address _spender ) public { require (isBatchSupported); require (_tokenIds.length > 0 && _spender != address(0)); uint256 _id; for (uint256 i = 0; i < _tokenIds.length; ++i) { require (_tokenIds[i] != 0); _id = _tokenIds[i]; approve(_spender, _id); } } /** * @dev Batch Function to mark spender for approved for all. Does a check * for address(0) and throws if true * @notice Facilitates batch approveAll * @param _spenders The spenders * @param _approved The approved */ function batchSetApprovalForAll( address[] _spenders, bool _approved ) public { require (isBatchSupported); require (_spenders.length > 0); address _spender; for (uint256 i = 0; i < _spenders.length; ++i) { require (address(_spenders[i]) != address(0)); _spender = _spenders[i]; setApprovalForAll(_spender, _approved); } } /** * @dev Function to request Detachment from our Contract * @notice a wallet can request to detach it collectible, so, that it can be used in other third-party contracts. * @param _tokenId The token identifier */ function requestDetachment( uint256 _tokenId ) public { //Request can only be made by owner or approved address require (isApprovedOrOwner(msg.sender, _tokenId)); uint256 isAttached = checkIsAttached(_tokenId); //If collectible is on a gamecard prevent detachment require(getGameCardId(_tokenId) == 0); require (isAttached >= 1); if(attachedSystemActive == true) { //Checks to see if request was made and if time elapsed if(isAttached > 1 && block.timestamp - isAttached > detachmentTime) { isAttached = 0; } else if(isAttached > 1) { //Forces Tx Fail if time is already set for attachment and not less than detachmentTime require (isAttached == 1); } else { //Is attached, set detachment time and make request to detach // emit AssetUpdated(_tokenId); isAttached = block.timestamp; } } else { isAttached = 0; } updateIsAttached(_tokenId, isAttached); } /** * @dev Function to attach the asset, thus, restricting transfer * @notice Attaches the collectible to our contract * @param _tokenId The token identifier */ function attachAsset( uint256 _tokenId ) public canTransfer(_tokenId) { uint256 isAttached = checkIsAttached(_tokenId); require (isAttached == 0); isAttached = 1; updateIsAttached(_tokenId, isAttached); emit AssetUpdated(_tokenId); } /** * @dev Batch attach function * @param _tokenIds The identifiers */ function batchAttachAssets(uint256[] _tokenIds) public { require (isBatchSupported); for(uint i = 0; i < _tokenIds.length; i++) { attachAsset(_tokenIds[i]); } } /** * @dev Batch detach function * @param _tokenIds The identifiers */ function batchDetachAssets(uint256[] _tokenIds) public { require (isBatchSupported); for(uint i = 0; i < _tokenIds.length; i++) { requestDetachment(_tokenIds[i]); } } /** * @dev Function to facilitate detachment when contract is paused * @param _tokenId The identifiers */ function requestDetachmentOnPause (uint256 _tokenId) public whenPaused { //Request can only be made by owner or approved address require (isApprovedOrOwner(msg.sender, _tokenId)); updateIsAttached(_tokenId, 0); } /** * @dev Toggle the Attachment Switch * @param _state The state */ function toggleAttachedEnforcement (bool _state) public onlyManager { attachedSystemActive = _state; } /** * @dev Set Attachment Time Period (this restricts user from continuously trigger detachment) * @param _time The time */ function setDetachmentTime (uint256 _time) public onlyManager { //Detactment Time can not be set greater than 2 weeks. require (_time <= 1209600); detachmentTime = uint32(_time); } /** * @dev Detach Asset From System * @param _tokenId The token iddentifier */ function setNFTDetached(uint256 _tokenId) public anyOperator { require (checkIsAttached(_tokenId) > 0); updateIsAttached(_tokenId, 0); } /** * @dev Batch function to detach multiple assets * @param _tokenIds The token identifiers */ function setBatchDetachCollectibles(uint256[] _tokenIds) public anyOperator { uint256 _id; for(uint i = 0; i < _tokenIds.length; i++) { _id = _tokenIds[i]; setNFTDetached(_id); } } /** * @dev Function to update attach value * @param _tokenId The asset id * @param _isAttached Indicates if attached */ function updateIsAttached(uint256 _tokenId, uint256 _isAttached) internal { NFT memory obj = _getAttributesOfToken(_tokenId); obj.isAttached = _isAttached; allNFTs[_tokenId] = obj; emit AssetUpdated(_tokenId); } /** * @dev Facilitates Creating Sale using the Sale Contract. Forces owner check & collectibleId check * @notice Helps a wallet to create a sale using our Sale Contract * @param _tokenId The token identifier * @param _startingPrice The starting price * @param _endingPrice The ending price * @param _duration The duration */ function initiateCreateSale(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration) external { require (_tokenId != 0); // If DodgersNFT is already on any sale, this will throw // because it will be owned by the sale contract. address owner = ownerOf(_tokenId); require (owner == msg.sender); // Sale contract checks input sizes require (_startingPrice == _startingPrice); require (_endingPrice == _endingPrice); require (_duration == _duration); require (checkIsAttached(_tokenId) == 0); // One time approval for the tokenID _approveForSale(msg.sender, address(saleManagerAddress), _tokenId); saleManagerAddress.createSale(_tokenId, _startingPrice, _endingPrice, _duration, msg.sender); } /** * @dev Facilitates batch auction of collectibles, and enforeces strict checking on the collectibleId,starting/ending price, duration. * @notice Batch function to put 10 or less collectibles on sale * @param _tokenIds The token identifier * @param _startingPrices The starting price * @param _endingPrices The ending price * @param _durations The duration */ function batchCreateAssetSale(uint256[] _tokenIds, uint256[] _startingPrices, uint256[] _endingPrices, uint256[] _durations) external whenNotPaused { require (_tokenIds.length > 0 && _startingPrices.length > 0 && _endingPrices.length > 0 && _durations.length > 0); // Sale contract checks input sizes for(uint ii = 0; ii < _tokenIds.length; ii++){ // Do not process for tokenId 0 require (_tokenIds[ii] != 0); require (_startingPrices[ii] == _startingPrices[ii]); require (_endingPrices[ii] == _endingPrices[ii]); require (_durations[ii] == _durations[ii]); // If DodgersNFT is already on any sale, this will throw // because it will be owned by the sale contract. address _owner = ownerOf(_tokenIds[ii]); address _msgSender = msg.sender; require (_owner == _msgSender); // Check whether the collectible is inPlay. If inPlay cant put it on Sale require (checkIsAttached(_tokenIds[ii]) == 0); // approve token to for Sale creation _approveForSale(msg.sender, address(saleManagerAddress), _tokenIds[ii]); saleManagerAddress.createSale(_tokenIds[ii], _startingPrices[ii], _endingPrices[ii], _durations[ii], msg.sender); } } }
Used to mark the smart contract as upgraded, in case of a issue _v2Address The new contract address/
function setNewAddress(address _v2Address) external onlyManager { require (_v2Address != address(0)); newContractAddress = _v2Address; emit ContractUpgrade(_v2Address); }
7,722,488
pragma solidity ^0.4.21; 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 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) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) 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]; } } 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; } } contract ERC827 is ERC20 { function approve( address _spender, uint256 _value, bytes _data ) public returns (bool); function transfer( address _to, uint256 _value, bytes _data ) public returns (bool); function transferFrom( address _from, address _to, uint256 _value, bytes _data ) public returns (bool); } contract ERC827Token is ERC827, StandardToken { /** @dev Addition to ERC20 token methods. It allows to approve the transfer of value and execute a call with the sent data. 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 that will spend the funds. @param _value The amount of tokens to be spent. @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function approve(address _spender, uint256 _value, bytes _data) public returns (bool) { require(_spender != address(this)); super.approve(_spender, _value); require(_spender.call(_data)); return true; } /** @dev Addition to ERC20 token methods. Transfer tokens to a specified address and execute a call with the sent data on the same transaction @param _to address The address which you want to transfer to @param _value uint256 the amout of tokens to be transfered @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function transfer(address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); super.transfer(_to, _value); require(_to.call(_data)); return true; } /** @dev Addition to ERC20 token methods. Transfer tokens from one address to another and make a contract call on the same transaction @param _from The address which you want to send tokens from @param _to The address which you want to transfer to @param _value The amout of tokens to be transferred @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function transferFrom(address _from, address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); super.transferFrom(_from, _to, _value); require(_to.call(_data)); return true; } /** * @dev Addition to StandardToken methods. Increase the amount of tokens that * an owner allowed to a spender and execute a call with the sent data. * * 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. * @param _data ABI-encoded contract call to call `_spender` address. */ function increaseApproval(address _spender, uint _addedValue, bytes _data) public returns (bool) { require(_spender != address(this)); super.increaseApproval(_spender, _addedValue); require(_spender.call(_data)); return true; } /** * @dev Addition to StandardToken methods. Decrease the amount of tokens that * an owner allowed to a spender and execute a call with the sent data. * * 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. * @param _data ABI-encoded contract call to call `_spender` address. */ function decreaseApproval(address _spender, uint _subtractedValue, bytes _data) public returns (bool) { require(_spender != address(this)); super.decreaseApproval(_spender, _subtractedValue); require(_spender.call(_data)); return true; } } 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); Transfer(burner, address(0), _value); } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title DAOToken, based on zeppelin contract. * @dev ERC20 compatible token. It is a mintable and burnable token. */ contract DAOToken is ERC827Token, MintableToken, BurnableToken { string public name; string public symbol; uint8 public constant decimals = 18; uint public cap; /** * @dev Constructor * @param _name - token name * @param _symbol - token symbol * @param _cap - token cap - 0 value means no cap */ function DAOToken(string _name, string _symbol,uint _cap) public { name = _name; symbol = _symbol; cap = _cap; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { if (cap > 0) require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } }
Constructor _name - token name _symbol - token symbol _cap - token cap - 0 value means no cap/
function DAOToken(string _name, string _symbol,uint _cap) public { name = _name; symbol = _symbol; cap = _cap; }
2,001,695
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } 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; 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.8.3; interface IAddressList { function add(address a) external returns (bool); function remove(address a) external returns (bool); function get(address a) external view returns (uint256); function contains(address a) external view returns (bool); function length() external view returns (uint256); function grantRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IAddressListFactory { function ours(address a) external view returns (bool); function listCount() external view returns (uint256); function listAt(uint256 idx) external view returns (address); function createList() external returns (address listaddr); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; /* solhint-disable func-name-mixedcase */ import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; interface ISwapManager { event OracleCreated(address indexed _sender, address indexed _newOracle, uint256 _period); function N_DEX() external view returns (uint256); function ROUTERS(uint256 i) external view returns (IUniswapV2Router02); function bestOutputFixedInput( address _from, address _to, uint256 _amountIn ) external view returns ( address[] memory path, uint256 amountOut, uint256 rIdx ); function bestPathFixedInput( address _from, address _to, uint256 _amountIn, uint256 _i ) external view returns (address[] memory path, uint256 amountOut); function bestInputFixedOutput( address _from, address _to, uint256 _amountOut ) external view returns ( address[] memory path, uint256 amountIn, uint256 rIdx ); function bestPathFixedOutput( address _from, address _to, uint256 _amountOut, uint256 _i ) external view returns (address[] memory path, uint256 amountIn); function safeGetAmountsOut( uint256 _amountIn, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function unsafeGetAmountsOut( uint256 _amountIn, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function safeGetAmountsIn( uint256 _amountOut, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function unsafeGetAmountsIn( uint256 _amountOut, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function comparePathsFixedInput( address[] memory pathA, address[] memory pathB, uint256 _amountIn, uint256 _i ) external view returns (address[] memory path, uint256 amountOut); function comparePathsFixedOutput( address[] memory pathA, address[] memory pathB, uint256 _amountOut, uint256 _i ) external view returns (address[] memory path, uint256 amountIn); function ours(address a) external view returns (bool); function oracleCount() external view returns (uint256); function oracleAt(uint256 idx) external view returns (address); function getOracle( address _tokenA, address _tokenB, uint256 _period, uint256 _i ) external view returns (address); function createOrUpdateOracle( address _tokenA, address _tokenB, uint256 _period, uint256 _i ) external returns (address oracleAddr); function consultForFree( address _from, address _to, uint256 _amountIn, uint256 _period, uint256 _i ) external view returns (uint256 amountOut, uint256 lastUpdatedAt); /// get the data we want and pay the gas to update function consult( address _from, address _to, uint256 _amountIn, uint256 _period, uint256 _i ) external returns ( uint256 amountOut, uint256 lastUpdatedAt, bool updated ); function updateOracles() external returns (uint256 updated, uint256 expected); function updateOracles(address[] memory _oracleAddrs) external returns (uint256 updated, uint256 expected); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface CToken { function accrueInterest() external returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function mint() external payable; // For ETH function mint(uint256 mintAmount) external returns (uint256); // For ERC20 function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function transfer(address user, uint256 amount) external returns (bool); function transferFrom( address owner, address user, uint256 amount ) external returns (bool); function balanceOf(address owner) external view returns (uint256); } interface Comptroller { function claimComp(address holder, address[] memory) external; function compAccrued(address holder) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IStrategy { function rebalance() external; function sweepERC20(address _fromToken) external; function withdraw(uint256 _amount) external; function feeCollector() external view returns (address); function isReservedToken(address _token) external view returns (bool); function migrate(address _newStrategy) external; function token() external view returns (address); function totalValue() external view returns (uint256); function pool() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../bloq/IAddressList.sol"; interface IVesperPool is IERC20 { function deposit() external payable; function deposit(uint256 _share) external; function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool); function excessDebt(address _strategy) external view returns (uint256); function permit( address, address, uint256, uint256, uint8, bytes32, bytes32 ) external; function poolRewards() external returns (address); function reportEarning( uint256 _profit, uint256 _loss, uint256 _payback ) external; function reportLoss(uint256 _loss) external; function resetApproval() external; function sweepERC20(address _fromToken) external; function withdraw(uint256 _amount) external; function withdrawETH(uint256 _amount) external; function whitelistedWithdraw(uint256 _amount) external; function governor() external view returns (address); function keepers() external view returns (IAddressList); function maintainers() external view returns (IAddressList); function feeCollector() external view returns (address); function pricePerShare() external view returns (uint256); function strategy(address _strategy) external view returns ( bool _active, uint256 _interestFee, uint256 _debtRate, uint256 _lastRebalance, uint256 _totalDebt, uint256 _totalLoss, uint256 _totalProfit, uint256 _debtRatio ); function stopEverything() external view returns (bool); function token() external view returns (IERC20); function tokensHere() external view returns (uint256); function totalDebtOf(address _strategy) external view returns (uint256); function totalValue() external view returns (uint256); function withdrawFee() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "../interfaces/bloq/ISwapManager.sol"; import "../interfaces/bloq/IAddressList.sol"; import "../interfaces/bloq/IAddressListFactory.sol"; import "../interfaces/vesper/IStrategy.sol"; import "../interfaces/vesper/IVesperPool.sol"; abstract contract Strategy is IStrategy, Context { using SafeERC20 for IERC20; IERC20 public immutable collateralToken; address public receiptToken; address public immutable override pool; IAddressList public keepers; address public override feeCollector; ISwapManager public swapManager; uint256 public oraclePeriod = 3600; // 1h uint256 public oracleRouterIdx = 0; // Uniswap V2 uint256 public swapSlippage = 10000; // 100% Don't use oracles by default address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; uint256 internal constant MAX_UINT_VALUE = type(uint256).max; event UpdatedFeeCollector(address indexed previousFeeCollector, address indexed newFeeCollector); event UpdatedSwapManager(address indexed previousSwapManager, address indexed newSwapManager); event UpdatedSwapSlippage(uint256 oldSwapSlippage, uint256 newSwapSlippage); event UpdatedOracleConfig(uint256 oldPeriod, uint256 newPeriod, uint256 oldRouterIdx, uint256 newRouterIdx); constructor( address _pool, address _swapManager, address _receiptToken ) { require(_pool != address(0), "pool-address-is-zero"); require(_swapManager != address(0), "sm-address-is-zero"); swapManager = ISwapManager(_swapManager); pool = _pool; collateralToken = IVesperPool(_pool).token(); receiptToken = _receiptToken; } modifier onlyGovernor { require(_msgSender() == IVesperPool(pool).governor(), "caller-is-not-the-governor"); _; } modifier onlyKeeper() { require(keepers.contains(_msgSender()), "caller-is-not-a-keeper"); _; } modifier onlyPool() { require(_msgSender() == pool, "caller-is-not-vesper-pool"); _; } /** * @notice Add given address in keepers list. * @param _keeperAddress keeper address to add. */ function addKeeper(address _keeperAddress) external onlyGovernor { require(keepers.add(_keeperAddress), "add-keeper-failed"); } /** * @notice Create keeper list * NOTE: Any function with onlyKeeper modifier will not work until this function is called. * NOTE: Due to gas constraint this function cannot be called in constructor. * @param _addressListFactory To support same code in eth side chain, user _addressListFactory as param * ethereum- 0xded8217De022706A191eE7Ee0Dc9df1185Fb5dA3 * polygon-0xD10D5696A350D65A9AA15FE8B258caB4ab1bF291 */ function init(address _addressListFactory) external onlyGovernor { require(address(keepers) == address(0), "keeper-list-already-created"); // Prepare keeper list IAddressListFactory _factory = IAddressListFactory(_addressListFactory); keepers = IAddressList(_factory.createList()); require(keepers.add(_msgSender()), "add-keeper-failed"); } /** * @notice Migrate all asset and vault ownership,if any, to new strategy * @dev _beforeMigration hook can be implemented in child strategy to do extra steps. * @param _newStrategy Address of new strategy */ function migrate(address _newStrategy) external virtual override onlyPool { require(_newStrategy != address(0), "new-strategy-address-is-zero"); require(IStrategy(_newStrategy).pool() == pool, "not-valid-new-strategy"); _beforeMigration(_newStrategy); IERC20(receiptToken).safeTransfer(_newStrategy, IERC20(receiptToken).balanceOf(address(this))); collateralToken.safeTransfer(_newStrategy, collateralToken.balanceOf(address(this))); } /** * @notice Remove given address from keepers list. * @param _keeperAddress keeper address to remove. */ function removeKeeper(address _keeperAddress) external onlyGovernor { require(keepers.remove(_keeperAddress), "remove-keeper-failed"); } /** * @notice Update fee collector * @param _feeCollector fee collector address */ function updateFeeCollector(address _feeCollector) external onlyGovernor { require(_feeCollector != address(0), "fee-collector-address-is-zero"); require(_feeCollector != feeCollector, "fee-collector-is-same"); emit UpdatedFeeCollector(feeCollector, _feeCollector); feeCollector = _feeCollector; } /** * @notice Update swap manager address * @param _swapManager swap manager address */ function updateSwapManager(address _swapManager) external onlyGovernor { require(_swapManager != address(0), "sm-address-is-zero"); require(_swapManager != address(swapManager), "sm-is-same"); emit UpdatedSwapManager(address(swapManager), _swapManager); swapManager = ISwapManager(_swapManager); } function updateSwapSlippage(uint256 _newSwapSlippage) external onlyGovernor { require(_newSwapSlippage <= 10000, "invalid-slippage-value"); emit UpdatedSwapSlippage(swapSlippage, _newSwapSlippage); swapSlippage = _newSwapSlippage; } function updateOracleConfig(uint256 _newPeriod, uint256 _newRouterIdx) external onlyGovernor { require(_newRouterIdx < swapManager.N_DEX(), "invalid-router-index"); if (_newPeriod == 0) _newPeriod = oraclePeriod; require(_newPeriod > 59, "invalid-oracle-period"); emit UpdatedOracleConfig(oraclePeriod, _newPeriod, oracleRouterIdx, _newRouterIdx); oraclePeriod = _newPeriod; oracleRouterIdx = _newRouterIdx; } /// @dev Approve all required tokens function approveToken() external onlyKeeper { _approveToken(0); _approveToken(MAX_UINT_VALUE); } function setupOracles() external onlyKeeper { _setupOracles(); } /** * @dev Withdraw collateral token from lending pool. * @param _amount Amount of collateral token */ function withdraw(uint256 _amount) external override onlyPool { _withdraw(_amount); } /** * @dev Rebalance profit, loss and investment of this strategy */ function rebalance() external virtual override onlyKeeper { (uint256 _profit, uint256 _loss, uint256 _payback) = _generateReport(); IVesperPool(pool).reportEarning(_profit, _loss, _payback); _reinvest(); } /** * @dev sweep given token to feeCollector of strategy * @param _fromToken token address to sweep */ function sweepERC20(address _fromToken) external override onlyKeeper { require(feeCollector != address(0), "fee-collector-not-set"); require(_fromToken != address(collateralToken), "not-allowed-to-sweep-collateral"); require(!isReservedToken(_fromToken), "not-allowed-to-sweep"); if (_fromToken == ETH) { Address.sendValue(payable(feeCollector), address(this).balance); } else { uint256 _amount = IERC20(_fromToken).balanceOf(address(this)); IERC20(_fromToken).safeTransfer(feeCollector, _amount); } } /// @notice Returns address of token correspond to collateral token function token() external view override returns (address) { return receiptToken; } /// @dev Convert from 18 decimals to token defined decimals. Default no conversion. function convertFrom18(uint256 amount) public pure virtual returns (uint256) { return amount; } /** * @notice Calculate total value of asset under management * @dev Report total value in collateral token */ function totalValue() external view virtual override returns (uint256 _value); /// @notice Check whether given token is reserved or not. Reserved tokens are not allowed to sweep. function isReservedToken(address _token) public view virtual override returns (bool); /** * @notice some strategy may want to prepare before doing migration. Example In Maker old strategy want to give vault ownership to new strategy * @param _newStrategy . */ function _beforeMigration(address _newStrategy) internal virtual; /** * @notice Generate report for current profit and loss. Also liquidate asset to payback * excess debt, if any. * @return _profit Calculate any realized profit and convert it to collateral, if not already. * @return _loss Calculate any loss that strategy has made on investment. Convert into collateral token. * @return _payback If strategy has any excess debt, we have to liquidate asset to payback excess debt. */ function _generateReport() internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _payback ) { uint256 _excessDebt = IVesperPool(pool).excessDebt(address(this)); uint256 _totalDebt = IVesperPool(pool).totalDebtOf(address(this)); _profit = _realizeProfit(_totalDebt); _loss = _realizeLoss(_totalDebt); _payback = _liquidate(_excessDebt); } function _calcAmtOutAfterSlippage(uint256 _amount, uint256 _slippage) internal pure returns (uint256) { return (_amount * (10000 - _slippage)) / (10000); } function _simpleOraclePath(address _from, address _to) internal pure returns (address[] memory path) { if (_from == WETH || _to == WETH) { path = new address[](2); path[0] = _from; path[1] = _to; } else { path = new address[](3); path[0] = _from; path[1] = WETH; path[2] = _to; } } function _consultOracle( address _from, address _to, uint256 _amt ) internal returns (uint256, bool) { // from, to, amountIn, period, router (uint256 rate, uint256 lastUpdate, ) = swapManager.consult(_from, _to, _amt, oraclePeriod, oracleRouterIdx); // We're looking at a TWAP ORACLE with a 1 hr Period that has been updated within the last hour if ((lastUpdate > (block.timestamp - oraclePeriod)) && (rate != 0)) return (rate, true); return (0, false); } function _getOracleRate(address[] memory path, uint256 _amountIn) internal returns (uint256 amountOut) { require(path.length > 1, "invalid-oracle-path"); amountOut = _amountIn; bool isValid; for (uint256 i = 0; i < path.length - 1; i++) { (amountOut, isValid) = _consultOracle(path[i], path[i + 1], amountOut); require(isValid, "invalid-oracle-rate"); } } /** * @notice Safe swap via Uniswap / Sushiswap (better rate of the two) * @dev There are many scenarios when token swap via Uniswap can fail, so this * method will wrap Uniswap call in a 'try catch' to make it fail safe. * however, this method will throw minAmountOut is not met * @param _from address of from token * @param _to address of to token * @param _amountIn Amount to be swapped * @param _minAmountOut minimum amount out */ function _safeSwap( address _from, address _to, uint256 _amountIn, uint256 _minAmountOut ) internal { (address[] memory path, uint256 amountOut, uint256 rIdx) = swapManager.bestOutputFixedInput(_from, _to, _amountIn); if (_minAmountOut == 0) _minAmountOut = 1; if (amountOut != 0) { swapManager.ROUTERS(rIdx).swapExactTokensForTokens( _amountIn, _minAmountOut, path, address(this), block.timestamp ); } } // These methods can be implemented by the inheriting strategy. /* solhint-disable no-empty-blocks */ function _claimRewardsAndConvertTo(address _toToken) internal virtual {} /** * @notice Set up any oracles that are needed for this strategy. */ function _setupOracles() internal virtual {} /* solhint-enable */ // These methods must be implemented by the inheriting strategy function _withdraw(uint256 _amount) internal virtual; function _approveToken(uint256 _amount) internal virtual; /** * @notice Withdraw collateral to payback excess debt in pool. * @param _excessDebt Excess debt of strategy in collateral token * @return _payback amount in collateral token. Usually it is equal to excess debt. */ function _liquidate(uint256 _excessDebt) internal virtual returns (uint256 _payback); /** * @notice Calculate earning and withdraw/convert it into collateral token. * @param _totalDebt Total collateral debt of this strategy * @return _profit Profit in collateral token */ function _realizeProfit(uint256 _totalDebt) internal virtual returns (uint256 _profit); /** * @notice Calculate loss * @param _totalDebt Total collateral debt of this strategy * @return _loss Realized loss in collateral token */ function _realizeLoss(uint256 _totalDebt) internal virtual returns (uint256 _loss); /** * @notice Reinvest collateral. * @dev Once we file report back in pool, we might have some collateral in hand * which we want to reinvest aka deposit in lender/provider. */ function _reinvest() internal virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "../Strategy.sol"; import "../../interfaces/compound/ICompound.sol"; /// @title This strategy will deposit collateral token in Compound and earn interest. abstract contract CompoundStrategy is Strategy { using SafeERC20 for IERC20; CToken internal cToken; address internal constant COMP = 0xc00e94Cb662C3520282E6f5717214004A7f26888; Comptroller internal constant COMPTROLLER = Comptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); constructor( address _pool, address _swapManager, address _receiptToken ) Strategy(_pool, _swapManager, _receiptToken) { require(_receiptToken != address(0), "cToken-address-is-zero"); cToken = CToken(_receiptToken); swapSlippage = 10000; // disable oracles on reward swaps by default } /** * @notice Calculate total value using COMP accrued and cToken * @dev Report total value in collateral token */ function totalValue() external view virtual override returns (uint256 _totalValue) { uint256 _compAccrued = COMPTROLLER.compAccrued(address(this)); if (_compAccrued != 0) { (, _totalValue) = swapManager.bestPathFixedInput(COMP, address(collateralToken), _compAccrued, 0); } _totalValue += _convertToCollateral(cToken.balanceOf(address(this))); } function isReservedToken(address _token) public view virtual override returns (bool) { return _token == address(cToken) || _token == COMP; } /// @notice Approve all required tokens function _approveToken(uint256 _amount) internal virtual override { collateralToken.safeApprove(pool, _amount); collateralToken.safeApprove(address(cToken), _amount); for (uint256 i = 0; i < swapManager.N_DEX(); i++) { IERC20(COMP).safeApprove(address(swapManager.ROUTERS(i)), _amount); } } /** * @notice Claim COMP and transfer to new strategy * @param _newStrategy Address of new strategy. */ function _beforeMigration(address _newStrategy) internal virtual override { _claimComp(); IERC20(COMP).safeTransfer(_newStrategy, IERC20(COMP).balanceOf(address(this))); } /// @notice Claim comp function _claimComp() internal { address[] memory _markets = new address[](1); _markets[0] = address(cToken); COMPTROLLER.claimComp(address(this), _markets); } /// @notice Claim COMP and convert COMP into collateral token. function _claimRewardsAndConvertTo(address _toToken) internal override { _claimComp(); uint256 _compAmount = IERC20(COMP).balanceOf(address(this)); if (_compAmount != 0) { uint256 minAmtOut = (swapSlippage != 10000) ? _calcAmtOutAfterSlippage( _getOracleRate(_simpleOraclePath(COMP, _toToken), _compAmount), swapSlippage ) : 1; _safeSwap(COMP, _toToken, _compAmount, minAmtOut); } } /// @notice Withdraw collateral to payback excess debt function _liquidate(uint256 _excessDebt) internal override returns (uint256 _payback) { if (_excessDebt != 0) { _payback = _safeWithdraw(_excessDebt); } } /** * @notice Calculate earning and withdraw it from Compound. * @dev Claim COMP and convert into collateral * @dev If somehow we got some collateral token in strategy then we want to * include those in profit. That's why we used 'return' outside 'if' condition. * @param _totalDebt Total collateral debt of this strategy * @return profit in collateral token */ function _realizeProfit(uint256 _totalDebt) internal virtual override returns (uint256) { _claimRewardsAndConvertTo(address(collateralToken)); uint256 _collateralBalance = _convertToCollateral(cToken.balanceOf(address(this))); if (_collateralBalance > _totalDebt) { _withdrawHere(_collateralBalance - _totalDebt); } return collateralToken.balanceOf(address(this)); } /** * @notice Calculate realized loss. * @return _loss Realized loss in collateral token */ function _realizeLoss(uint256 _totalDebt) internal view override returns (uint256 _loss) { uint256 _collateralBalance = _convertToCollateral(cToken.balanceOf(address(this))); if (_collateralBalance < _totalDebt) { _loss = _totalDebt - _collateralBalance; } } /// @notice Deposit collateral in Compound function _reinvest() internal virtual override { uint256 _collateralBalance = collateralToken.balanceOf(address(this)); if (_collateralBalance != 0) { require(cToken.mint(_collateralBalance) == 0, "deposit-to-compound-failed"); } } /// @dev Withdraw collateral and transfer it to pool function _withdraw(uint256 _amount) internal override { _safeWithdraw(_amount); collateralToken.safeTransfer(pool, collateralToken.balanceOf(address(this))); } /** * @notice Safe withdraw will make sure to check asking amount against available amount. * @param _amount Amount of collateral to withdraw. * @return Actual collateral withdrawn */ function _safeWithdraw(uint256 _amount) internal returns (uint256) { uint256 _collateralBalance = _convertToCollateral(cToken.balanceOf(address(this))); // Get minimum of _amount and _collateralBalance return _withdrawHere(_amount < _collateralBalance ? _amount : _collateralBalance); } /// @dev Withdraw collateral here. Do not transfer to pool function _withdrawHere(uint256 _amount) internal returns (uint256) { if (_amount != 0) { require(cToken.redeemUnderlying(_amount) == 0, "withdraw-from-compound-failed"); _afterRedeem(); } return _amount; } function _setupOracles() internal override { swapManager.createOrUpdateOracle(COMP, WETH, oraclePeriod, oracleRouterIdx); if (address(collateralToken) != WETH) { swapManager.createOrUpdateOracle(WETH, address(collateralToken), oraclePeriod, oracleRouterIdx); } } /** * @dev Compound support ETH as collateral not WETH. This hook will take * care of conversion from WETH to ETH and vice versa. * @dev This will be used in ETH strategy only, hence empty implementation */ //solhint-disable-next-line no-empty-blocks function _afterRedeem() internal virtual {} function _convertToCollateral(uint256 _cTokenAmount) internal view returns (uint256) { return (_cTokenAmount * cToken.exchangeRateStored()) / 1e18; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "../compound/CompoundStrategy.sol"; /// @title This strategy will deposit collateral token in C.R.E.A.M. and earn interest. abstract contract CreamStrategy is CompoundStrategy { using SafeERC20 for IERC20; // solhint-disable no-empty-blocks constructor( address _pool, address _swapManager, address _receiptToken ) CompoundStrategy(_pool, _swapManager, _receiptToken) {} // solhint-enable no-empty-blocks /** * @notice Calculate total value using underlying token * @dev Report total value in collateral token */ function totalValue() external view override returns (uint256 _totalValue) { _totalValue = _convertToCollateral(cToken.balanceOf(address(this))); } function isReservedToken(address _token) public view override returns (bool) { return _token == address(cToken); } /// @notice Approve all required tokens function _approveToken(uint256 _amount) internal override { collateralToken.safeApprove(pool, _amount); collateralToken.safeApprove(address(cToken), _amount); } // solhint-disable-next-line function _beforeMigration(address _newStrategy) internal override {} /** * @notice Calculate earning and withdraw it from C.R.E.A.M. * @dev If somehow we got some collateral token in strategy then we want to * include those in profit. That's why we used 'return' outside 'if' condition. * Since there aren't token rewards here, we call accrueInterst * to make sure we get the maximum accrued interest on rebalance * @param _totalDebt Total collateral debt of this strategy * @return profit in collateral token */ function _realizeProfit(uint256 _totalDebt) internal override returns (uint256) { cToken.accrueInterest(); uint256 _collateralBalance = _convertToCollateral(cToken.balanceOf(address(this))); if (_collateralBalance > _totalDebt) { _withdrawHere(_collateralBalance - _totalDebt); } return collateralToken.balanceOf(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "./CreamStrategy.sol"; // solhint-disable no-empty-blocks /// @title Deposit USDT in C.R.E.A.M. and earn interest. contract CreamStrategyUSDT is CreamStrategy { string public constant NAME = "Cream-Strategy-USDT"; string public constant VERSION = "3.0.10"; // crUSDT = 0x797AAB1ce7c01eB727ab980762bA88e7133d2157 constructor(address _pool, address _swapManager) CreamStrategy(_pool, _swapManager, 0x797AAB1ce7c01eB727ab980762bA88e7133d2157) {} }
Calculate total value using COMP accrued and cToken Report total value in collateral token/
function totalValue() external view virtual override returns (uint256 _totalValue) { uint256 _compAccrued = COMPTROLLER.compAccrued(address(this)); if (_compAccrued != 0) { (, _totalValue) = swapManager.bestPathFixedInput(COMP, address(collateralToken), _compAccrued, 0); } _totalValue += _convertToCollateral(cToken.balanceOf(address(this))); }
6,207,872
// Sources flattened with hardhat v2.8.0 https://hardhat.org // File contracts/PriceOracle.sol pragma solidity ^0.8.4; abstract contract PriceOracle { /// @notice Indicator that this is a PriceOracle contract (for inspection) bool public constant isPriceOracle = true; /** * @notice Get the price of a token * @param token The token to get the price of * @return The asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getTokenPrice(address token) external view virtual returns (uint256); } // File @openzeppelin/contracts/utils/math/[email protected] pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/utils/[email protected] pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/interfaces/IERC20Extended.sol pragma solidity ^0.8.4; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Extended { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/interfaces/IPriceOracle.sol pragma solidity ^0.8.4; interface IPriceOracle { /** * @notice Get the price of a token * @param token The token to get the price of * @return The asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getTokenPrice(address token) external view returns (uint256); } // File contracts/ConnextPriceOracle.sol pragma solidity ^0.8.4; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } contract ConnextPriceOracle is PriceOracle { using SafeMath for uint256; using SafeERC20 for IERC20Extended; address public admin; address public wrapped; address public v1PriceOracle; /// @notice Chainlink Aggregators mapping(address => AggregatorV3Interface) public aggregators; struct PriceInfo { address token; // Address of token contract, TOKEN address baseToken; // Address of base token contract, BASETOKEN address lpToken; // Address of TOKEN-BASETOKEN pair contract bool active; // Active status of price record 0 } mapping(address => PriceInfo) public priceRecords; mapping(address => uint256) public assetPrices; event NewAdmin(address oldAdmin, address newAdmin); event PriceRecordUpdated(address token, address baseToken, address lpToken, bool _active); event DirectPriceUpdated(address token, uint256 oldPrice, uint256 newPrice); event AggregatorUpdated(address tokenAddress, address source); event V1PriceOracleUpdated(address oldAddress, address newAddress); modifier onlyAdmin() { require(msg.sender == admin, "caller is not the admin"); _; } constructor(address _wrapped) { wrapped = _wrapped; admin = msg.sender; } function getTokenPrice(address _tokenAddress) public view override returns (uint256) { address tokenAddress = _tokenAddress; if (_tokenAddress == address(0)) { tokenAddress = wrapped; } uint256 tokenPrice = assetPrices[tokenAddress]; if (tokenPrice == 0) { tokenPrice = getPriceFromOracle(tokenAddress); } if (tokenPrice == 0) { tokenPrice = getPriceFromDex(tokenAddress); } if (tokenPrice == 0 && v1PriceOracle != address(0)) { tokenPrice = IPriceOracle(v1PriceOracle).getTokenPrice(tokenAddress); } return tokenPrice; } function getPriceFromDex(address _tokenAddress) public view returns (uint256) { PriceInfo storage priceInfo = priceRecords[_tokenAddress]; if (priceInfo.active) { uint256 rawTokenAmount = IERC20Extended(priceInfo.token).balanceOf(priceInfo.lpToken); uint256 tokenDecimalDelta = 18 - uint256(IERC20Extended(priceInfo.token).decimals()); uint256 tokenAmount = rawTokenAmount.mul(10**tokenDecimalDelta); uint256 rawBaseTokenAmount = IERC20Extended(priceInfo.baseToken).balanceOf(priceInfo.lpToken); uint256 baseTokenDecimalDelta = 18 - uint256(IERC20Extended(priceInfo.baseToken).decimals()); uint256 baseTokenAmount = rawBaseTokenAmount.mul(10**baseTokenDecimalDelta); uint256 baseTokenPrice = getTokenPrice(priceInfo.baseToken); uint256 tokenPrice = baseTokenPrice.mul(baseTokenAmount).div(tokenAmount); return tokenPrice; } else { return 0; } } function getPriceFromOracle(address _tokenAddress) public view returns (uint256) { uint256 chainLinkPrice = getPriceFromChainlink(_tokenAddress); return chainLinkPrice; } function getPriceFromChainlink(address _tokenAddress) public view returns (uint256) { AggregatorV3Interface aggregator = aggregators[_tokenAddress]; if (address(aggregator) != address(0)) { (, int256 answer, , , ) = aggregator.latestRoundData(); // It's fine for price to be 0. We have two price feeds. if (answer == 0) { return 0; } // Extend the decimals to 1e18. uint256 retVal = uint256(answer); uint256 price = retVal.mul(10**(18 - uint256(aggregator.decimals()))); return price; } return 0; } function setDexPriceInfo( address _token, address _baseToken, address _lpToken, bool _active ) external onlyAdmin { PriceInfo storage priceInfo = priceRecords[_token]; uint256 baseTokenPrice = getTokenPrice(_baseToken); require(baseTokenPrice > 0, "invalid base token"); priceInfo.token = _token; priceInfo.baseToken = _baseToken; priceInfo.lpToken = _lpToken; priceInfo.active = _active; emit PriceRecordUpdated(_token, _baseToken, _lpToken, _active); } function setDirectPrice(address _token, uint256 _price) external onlyAdmin { emit DirectPriceUpdated(_token, assetPrices[_token], _price); assetPrices[_token] = _price; } function setV1PriceOracle(address _v1PriceOracle) external onlyAdmin { emit V1PriceOracleUpdated(v1PriceOracle, _v1PriceOracle); v1PriceOracle = _v1PriceOracle; } function setAdmin(address newAdmin) external onlyAdmin { address oldAdmin = admin; admin = newAdmin; emit NewAdmin(oldAdmin, newAdmin); } function setAggregators(address[] calldata tokenAddresses, address[] calldata sources) external onlyAdmin { for (uint256 i = 0; i < tokenAddresses.length; i++) { aggregators[tokenAddresses[i]] = AggregatorV3Interface(sources[i]); emit AggregatorUpdated(tokenAddresses[i], sources[i]); } } } // File contracts/interfaces/IFulfillInterpreter.sol pragma solidity 0.8.4; interface IFulfillInterpreter { event Executed( bytes32 indexed transactionId, address payable callTo, address assetId, address payable fallbackAddress, uint256 amount, bytes callData, bytes returnData, bool success, bool isContract ); function getTransactionManager() external returns (address); function execute( bytes32 transactionId, address payable callTo, address assetId, address payable fallbackAddress, uint256 amount, bytes calldata callData ) external payable returns ( bool success, bool isContract, bytes memory returnData ); } // File contracts/lib/LibAsset.sol pragma solidity 0.8.4; /** * @title LibAsset * @author Connext <[email protected]> * @notice This library contains helpers for dealing with onchain transfers * of assets, including accounting for the native asset `assetId` * conventions and any noncompliant ERC20 transfers */ library LibAsset { /** * @dev All native assets use the empty address for their asset id * by convention */ address constant NATIVE_ASSETID = address(0); /** * @notice Determines whether the given assetId is the native asset * @param assetId The asset identifier to evaluate * @return Boolean indicating if the asset is the native asset */ function isNativeAsset(address assetId) internal pure returns (bool) { return assetId == NATIVE_ASSETID; } /** * @notice Gets the balance of the inheriting contract for the given asset * @param assetId The asset identifier to get the balance of * @return Balance held by contracts using this library */ function getOwnBalance(address assetId) internal view returns (uint256) { return isNativeAsset(assetId) ? address(this).balance : IERC20(assetId).balanceOf(address(this)); } /** * @notice Transfers ether from the inheriting contract to a given * recipient * @param recipient Address to send ether to * @param amount Amount to send to given recipient */ function transferNativeAsset(address payable recipient, uint256 amount) internal { Address.sendValue(recipient, amount); } /** * @notice Transfers tokens from the inheriting contract to a given * recipient * @param assetId Token address to transfer * @param recipient Address to send ether to * @param amount Amount to send to given recipient */ function transferERC20( address assetId, address recipient, uint256 amount ) internal { SafeERC20.safeTransfer(IERC20(assetId), recipient, amount); } /** * @notice Transfers tokens from a sender to a given recipient * @param assetId Token address to transfer * @param from Address of sender/owner * @param to Address of recipient/spender * @param amount Amount to transfer from owner to spender */ function transferFromERC20( address assetId, address from, address to, uint256 amount ) internal { SafeERC20.safeTransferFrom(IERC20(assetId), from, to, amount); } /** * @notice Increases the allowance of a token to a spender * @param assetId Token address of asset to increase allowance of * @param spender Account whos allowance is increased * @param amount Amount to increase allowance by */ function increaseERC20Allowance( address assetId, address spender, uint256 amount ) internal { require(!isNativeAsset(assetId), "#IA:034"); SafeERC20.safeIncreaseAllowance(IERC20(assetId), spender, amount); } /** * @notice Decreases the allowance of a token to a spender * @param assetId Token address of asset to decrease allowance of * @param spender Account whos allowance is decreased * @param amount Amount to decrease allowance by */ function decreaseERC20Allowance( address assetId, address spender, uint256 amount ) internal { require(!isNativeAsset(assetId), "#DA:034"); SafeERC20.safeDecreaseAllowance(IERC20(assetId), spender, amount); } /** * @notice Wrapper function to transfer a given asset (native or erc20) to * some recipient. Should handle all non-compliant return value * tokens as well by using the SafeERC20 contract by open zeppelin. * @param assetId Asset id for transfer (address(0) for native asset, * token address for erc20s) * @param recipient Address to send asset to * @param amount Amount to send to given recipient */ function transferAsset( address assetId, address payable recipient, uint256 amount ) internal { isNativeAsset(assetId) ? transferNativeAsset(recipient, amount) : transferERC20(assetId, recipient, amount); } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/access/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File @openzeppelin/contracts/security/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File contracts/interpreters/FulfillInterpreter.sol pragma solidity 0.8.4; /** * @title FulfillInterpreter * @author Connext <[email protected]> * @notice This library contains an `execute` function that is callabale by * an associated TransactionManager contract. This is used to execute * arbitrary calldata on a receiving chain. */ contract FulfillInterpreter is ReentrancyGuard, IFulfillInterpreter { address private immutable _transactionManager; constructor(address transactionManager) { _transactionManager = transactionManager; } /** * @notice Errors if the sender is not the transaction manager */ modifier onlyTransactionManager() { require(msg.sender == _transactionManager, "#OTM:027"); _; } /** * @notice Returns the transaction manager address (only address that can * call the `execute` function) * @return The address of the associated transaction manager */ function getTransactionManager() external view override returns (address) { return _transactionManager; } /** * @notice Executes some arbitrary call data on a given address. The * call data executes can be payable, and will have `amount` sent * along with the function (or approved to the contract). If the * call fails, rather than reverting, funds are sent directly to * some provided fallbaack address * @param transactionId Unique identifier of transaction id that necessitated * calldata execution * @param callTo The address to execute the calldata on * @param assetId The assetId of the funds to approve to the contract or * send along with the call * @param fallbackAddress The address to send funds to if the `call` fails * @param amount The amount to approve or send with the call * @param callData The data to execute */ function execute( bytes32 transactionId, address payable callTo, address assetId, address payable fallbackAddress, uint256 amount, bytes calldata callData ) external payable override onlyTransactionManager returns ( bool, bool, bytes memory ) { // If it is not ether, approve the callTo // We approve here rather than transfer since many external contracts // simply require an approval, and it is unclear if they can handle // funds transferred directly to them (i.e. Uniswap) bool isNative = LibAsset.isNativeAsset(assetId); if (!isNative) { LibAsset.increaseERC20Allowance(assetId, callTo, amount); } // Check if the callTo is a contract bool success; bytes memory returnData; bool isContract = Address.isContract(callTo); if (isContract) { // Try to execute the callData // the low level call will return `false` if its execution reverts (success, returnData) = callTo.call{value: isNative ? amount : 0}(callData); } // Handle failure cases if (!success) { // If it fails, transfer to fallback LibAsset.transferAsset(assetId, fallbackAddress, amount); // Decrease allowance if (!isNative) { LibAsset.decreaseERC20Allowance(assetId, callTo, amount); } } // Emit event emit Executed(transactionId, callTo, assetId, fallbackAddress, amount, callData, returnData, success, isContract); return (success, isContract, returnData); } } // File contracts/interfaces/ITransactionManager.sol pragma solidity 0.8.4; interface ITransactionManager { // Structs // Holds all data that is constant between sending and // receiving chains. The hash of this is what gets signed // to ensure the signature can be used on both chains. struct InvariantTransactionData { address receivingChainTxManagerAddress; address user; address router; address initiator; // msg.sender of sending side address sendingAssetId; address receivingAssetId; address sendingChainFallback; // funds sent here on cancel address receivingAddress; address callTo; uint256 sendingChainId; uint256 receivingChainId; bytes32 callDataHash; // hashed to prevent free option bytes32 transactionId; } // Holds all data that varies between sending and receiving // chains. The hash of this is stored onchain to ensure the // information passed in is valid. struct VariantTransactionData { uint256 amount; uint256 expiry; uint256 preparedBlockNumber; } // All Transaction data, constant and variable struct TransactionData { address receivingChainTxManagerAddress; address user; address router; address initiator; // msg.sender of sending side address sendingAssetId; address receivingAssetId; address sendingChainFallback; address receivingAddress; address callTo; bytes32 callDataHash; bytes32 transactionId; uint256 sendingChainId; uint256 receivingChainId; uint256 amount; uint256 expiry; uint256 preparedBlockNumber; // Needed for removal of active blocks on fulfill/cancel } // The structure of the signed data for fulfill struct SignedFulfillData { bytes32 transactionId; uint256 relayerFee; string functionIdentifier; // "fulfill" or "cancel" uint256 receivingChainId; // For domain separation address receivingChainTxManagerAddress; // For domain separation } // The structure of the signed data for cancellation struct SignedCancelData { bytes32 transactionId; string functionIdentifier; uint256 receivingChainId; address receivingChainTxManagerAddress; // For domain separation } /** * Arguments for calling prepare() * @param invariantData The data for a crosschain transaction that will * not change between sending and receiving chains. * The hash of this data is used as the key to store * the inforamtion that does change between chains * (amount,expiry,preparedBlock) for verification * @param amount The amount of the transaction on this chain * @param expiry The block.timestamp when the transaction will no longer be * fulfillable and is freely cancellable on this chain * @param encryptedCallData The calldata to be executed when the tx is * fulfilled. Used in the function to allow the user * to reconstruct the tx from events. Hash is stored * onchain to prevent shenanigans. * @param encodedBid The encoded bid that was accepted by the user for this * crosschain transfer. It is supplied as a param to the * function but is only used in event emission * @param bidSignature The signature of the bidder on the encoded bid for * this transaction. Only used within the function for * event emission. The validity of the bid and * bidSignature are enforced offchain * @param encodedMeta The meta for the function */ struct PrepareArgs { InvariantTransactionData invariantData; uint256 amount; uint256 expiry; bytes encryptedCallData; bytes encodedBid; bytes bidSignature; bytes encodedMeta; } /** * @param txData All of the data (invariant and variant) for a crosschain * transaction. The variant data provided is checked against * what was stored when the `prepare` function was called. * @param relayerFee The fee that should go to the relayer when they are * calling the function on the receiving chain for the user * @param signature The users signature on the transaction id + fee that * can be used by the router to unlock the transaction on * the sending chain * @param callData The calldata to be sent to and executed by the * `FulfillHelper` * @param encodedMeta The meta for the function */ struct FulfillArgs { TransactionData txData; uint256 relayerFee; bytes signature; bytes callData; bytes encodedMeta; } /** * Arguments for calling cancel() * @param txData All of the data (invariant and variant) for a crosschain * transaction. The variant data provided is checked against * what was stored when the `prepare` function was called. * @param signature The user's signature that allows a transaction to be * cancelled by a relayer * @param encodedMeta The meta for the function */ struct CancelArgs { TransactionData txData; bytes signature; bytes encodedMeta; } // Adding/removing asset events event RouterAdded(address indexed addedRouter, address indexed caller); event RouterRemoved(address indexed removedRouter, address indexed caller); // Adding/removing router events event AssetAdded(address indexed addedAssetId, address indexed caller); event AssetRemoved(address indexed removedAssetId, address indexed caller); // Liquidity events event LiquidityAdded(address indexed router, address indexed assetId, uint256 amount, address caller); event LiquidityRemoved(address indexed router, address indexed assetId, uint256 amount, address recipient); // Transaction events event TransactionPrepared( address indexed user, address indexed router, bytes32 indexed transactionId, TransactionData txData, address caller, PrepareArgs args ); event TransactionFulfilled( address indexed user, address indexed router, bytes32 indexed transactionId, FulfillArgs args, bool success, bool isContract, bytes returnData, address caller ); event TransactionCancelled( address indexed user, address indexed router, bytes32 indexed transactionId, CancelArgs args, address caller ); // Getters function getChainId() external view returns (uint256); function getStoredChainId() external view returns (uint256); // Owner only methods function addRouter(address router) external; function removeRouter(address router) external; function addAssetId(address assetId) external; function removeAssetId(address assetId) external; // Router only methods function addLiquidityFor( uint256 amount, address assetId, address router ) external payable; function addLiquidity(uint256 amount, address assetId) external payable; function removeLiquidity( uint256 amount, address assetId, address payable recipient ) external; // Methods for crosschain transfers // called in the following order (in happy case) // 1. prepare by user on sending chain // 2. prepare by router on receiving chain // 3. fulfill by user on receiving chain // 4. fulfill by router on sending chain function prepare(PrepareArgs calldata args) external payable returns (TransactionData memory); function fulfill(FulfillArgs calldata args) external returns (TransactionData memory); function cancel(CancelArgs calldata args) external returns (TransactionData memory); } // File @openzeppelin/contracts/utils/cryptography/[email protected] pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @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. * * 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] */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // 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 recover(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 recover(hash, r, vs); } else { revert("ECDSA: invalid signature length"); } } /** * @dev Overload of {ECDSA-recover} 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.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return recover(hash, v, r, s); } /** * @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) { // 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. require( uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value" ); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // File contracts/Router.sol pragma solidity ^0.8.4; contract Router is Ownable { address public immutable routerFactory; ITransactionManager public transactionManager; uint256 private chainId; address public recipient; address public routerSigner; struct SignedPrepareData { ITransactionManager.PrepareArgs args; address routerRelayerFeeAsset; uint256 routerRelayerFee; uint256 chainId; // For domain separation } struct SignedFulfillData { ITransactionManager.FulfillArgs args; address routerRelayerFeeAsset; uint256 routerRelayerFee; uint256 chainId; // For domain separation } struct SignedCancelData { ITransactionManager.CancelArgs args; address routerRelayerFeeAsset; uint256 routerRelayerFee; uint256 chainId; // For domain separation } struct SignedRemoveLiquidityData { uint256 amount; address assetId; address routerRelayerFeeAsset; uint256 routerRelayerFee; uint256 chainId; // For domain separation } event RelayerFeeAdded(address assetId, uint256 amount, address caller); event RelayerFeeRemoved(address assetId, uint256 amount, address caller); event RemoveLiquidity( uint256 amount, address assetId, address routerRelayerFeeAsset, uint256 routerRelayerFee, address caller ); event Prepare( ITransactionManager.InvariantTransactionData invariantData, address routerRelayerFeeAsset, uint256 routerRelayerFee, address caller ); event Fulfill( ITransactionManager.TransactionData txData, address routerRelayerFeeAsset, uint256 routerRelayerFee, address caller ); event Cancel( ITransactionManager.TransactionData txData, address routerRelayerFeeAsset, uint256 routerRelayerFee, address caller ); constructor(address _routerFactory) { routerFactory = _routerFactory; } // Prevents from calling methods other than routerFactory contract modifier onlyViaFactory() { require(msg.sender == routerFactory, "ONLY_VIA_FACTORY"); _; } function init( address _transactionManager, uint256 _chainId, address _routerSigner, address _recipient, address _owner ) external onlyViaFactory { transactionManager = ITransactionManager(_transactionManager); chainId = _chainId; routerSigner = _routerSigner; recipient = _recipient; transferOwnership(_owner); } function setRecipient(address _recipient) external onlyOwner { recipient = _recipient; } function setSigner(address _routerSigner) external onlyOwner { routerSigner = _routerSigner; } function addRelayerFee(uint256 amount, address assetId) external payable { // Sanity check: nonzero amounts require(amount > 0, "#RC_ARF:002"); // Transfer funds to contract // Validate correct amounts are transferred if (LibAsset.isNativeAsset(assetId)) { require(msg.value == amount, "#RC_ARF:005"); } else { require(msg.value == 0, "#RC_ARF:006"); LibAsset.transferFromERC20(assetId, msg.sender, address(this), amount); } // Emit event emit RelayerFeeAdded(assetId, amount, msg.sender); } function removeRelayerFee(uint256 amount, address assetId) external onlyOwner { // Sanity check: nonzero amounts require(amount > 0, "#RC_RRF:002"); // Transfer funds from contract LibAsset.transferAsset(assetId, payable(recipient), amount); // Emit event emit RelayerFeeRemoved(assetId, amount, msg.sender); } function removeLiquidity( uint256 amount, address assetId, address routerRelayerFeeAsset, uint256 routerRelayerFee, bytes calldata signature ) external { if (msg.sender != routerSigner) { SignedRemoveLiquidityData memory payload = SignedRemoveLiquidityData({ amount: amount, assetId: assetId, routerRelayerFeeAsset: routerRelayerFeeAsset, routerRelayerFee: routerRelayerFee, chainId: chainId }); address recovered = recoverSignature(abi.encode(payload), signature); require(recovered == routerSigner, "#RC_RL:040"); // Send the relayer the fee if (routerRelayerFee > 0) { LibAsset.transferAsset(routerRelayerFeeAsset, payable(msg.sender), routerRelayerFee); } } emit RemoveLiquidity(amount, assetId, routerRelayerFeeAsset, routerRelayerFee, msg.sender); return transactionManager.removeLiquidity(amount, assetId, payable(recipient)); } function prepare( ITransactionManager.PrepareArgs calldata args, address routerRelayerFeeAsset, uint256 routerRelayerFee, bytes calldata signature ) external payable returns (ITransactionManager.TransactionData memory) { if (msg.sender != routerSigner) { SignedPrepareData memory payload = SignedPrepareData({ args: args, routerRelayerFeeAsset: routerRelayerFeeAsset, routerRelayerFee: routerRelayerFee, chainId: chainId }); address recovered = recoverSignature(abi.encode(payload), signature); require(recovered == routerSigner, "#RC_P:040"); // Send the relayer the fee if (routerRelayerFee > 0) { LibAsset.transferAsset(routerRelayerFeeAsset, payable(msg.sender), routerRelayerFee); } } emit Prepare(args.invariantData, routerRelayerFeeAsset, routerRelayerFee, msg.sender); return transactionManager.prepare(args); } function fulfill( ITransactionManager.FulfillArgs calldata args, address routerRelayerFeeAsset, uint256 routerRelayerFee, bytes calldata signature ) external returns (ITransactionManager.TransactionData memory) { if (msg.sender != routerSigner) { SignedFulfillData memory payload = SignedFulfillData({ args: args, routerRelayerFeeAsset: routerRelayerFeeAsset, routerRelayerFee: routerRelayerFee, chainId: chainId }); address recovered = recoverSignature(abi.encode(payload), signature); require(recovered == routerSigner, "#RC_F:040"); // Send the relayer the fee if (routerRelayerFee > 0) { LibAsset.transferAsset(routerRelayerFeeAsset, payable(msg.sender), routerRelayerFee); } } emit Fulfill(args.txData, routerRelayerFeeAsset, routerRelayerFee, msg.sender); return transactionManager.fulfill(args); } function cancel( ITransactionManager.CancelArgs calldata args, address routerRelayerFeeAsset, uint256 routerRelayerFee, bytes calldata signature ) external returns (ITransactionManager.TransactionData memory) { if (msg.sender != routerSigner) { SignedCancelData memory payload = SignedCancelData({ args: args, routerRelayerFeeAsset: routerRelayerFeeAsset, routerRelayerFee: routerRelayerFee, chainId: chainId }); address recovered = recoverSignature(abi.encode(payload), signature); require(recovered == routerSigner, "#RC_C:040"); // Send the relayer the fee if (routerRelayerFee > 0) { LibAsset.transferAsset(routerRelayerFeeAsset, payable(msg.sender), routerRelayerFee); } } emit Cancel(args.txData, routerRelayerFeeAsset, routerRelayerFee, msg.sender); return transactionManager.cancel(args); } /** * @notice Holds the logic to recover the routerSigner from an encoded payload. * Will hash and convert to an eth signed message. * @param encodedPayload The payload that was signed * @param signature The signature you are recovering the routerSigner from */ function recoverSignature(bytes memory encodedPayload, bytes calldata signature) internal pure returns (address) { // Recover return ECDSA.recover(ECDSA.toEthSignedMessageHash(keccak256(encodedPayload)), signature); } receive() external payable {} } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer. * `CREATE2` can be used to compute in advance the address where a smart * contract will be deployed, which allows for interesting new mechanisms known * as 'counterfactual interactions'. * * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more * information. */ library Create2 { /** * @dev Deploys a contract using `CREATE2`. The address where the contract * will be deployed can be known in advance via {computeAddress}. * * The bytecode for a contract can be obtained from Solidity with * `type(contractName).creationCode`. * * Requirements: * * - `bytecode` must not be empty. * - `salt` must have not been used for `bytecode` already. * - the factory must have a balance of at least `amount`. * - if `amount` is non-zero, `bytecode` must have a `payable` constructor. */ function deploy( uint256 amount, bytes32 salt, bytes memory bytecode ) internal returns (address) { address addr; require(address(this).balance >= amount, "Create2: insufficient balance"); require(bytecode.length != 0, "Create2: bytecode length is zero"); assembly { addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt) } require(addr != address(0), "Create2: Failed on deploy"); return addr; } /** * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the * `bytecodeHash` or `salt` will result in a new destination address. */ function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) { return computeAddress(salt, bytecodeHash, address(this)); } /** * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}. */ function computeAddress( bytes32 salt, bytes32 bytecodeHash, address deployer ) internal pure returns (address) { bytes32 _data = keccak256(abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash)); return address(uint160(uint256(_data))); } } // File contracts/interfaces/IRouterFactory.sol pragma solidity ^0.8.4; interface IRouterFactory { event RouterCreated(address router, address routerSigner, address recipient, address transactionManager); function getRouterAddress(address routerSigner) external view returns (address); function createRouter(address router, address recipient) external returns (address); } // File contracts/RouterFactory.sol pragma solidity ^0.8.4; contract RouterFactory is IRouterFactory, Ownable { /** * @dev The stored chain id of the contract, may be passed in to avoid any * evm issues */ uint256 private chainId; /** * @dev The transaction Manager contract */ ITransactionManager public transactionManager; /** * @dev Mapping of routerSigner to created Router contract address */ mapping(address => address) public routerAddresses; constructor(address _owner) { transferOwnership(_owner); } function init(address _transactionManager) external onlyOwner { require(address(_transactionManager) != address(0), "#RF_I:042"); transactionManager = ITransactionManager(_transactionManager); chainId = ITransactionManager(_transactionManager).getChainId(); } /** * @notice Allows us to create new router contract * @param routerSigner address router signer * @param recipient address recipient */ function createRouter(address routerSigner, address recipient) external override returns (address) { require(address(transactionManager) != address(0), "#RF_CR:042"); require(routerSigner != address(0), "#RF_CR:041"); require(recipient != address(0), "#RF_CR:007"); address payable router = payable(Create2.deploy(0, generateSalt(routerSigner), getBytecode())); Router(router).init(address(transactionManager), chainId, routerSigner, recipient, msg.sender); routerAddresses[routerSigner] = router; emit RouterCreated(router, routerSigner, recipient, address(transactionManager)); return router; } /** * @notice Allows us to get the address for a new router contract created via `createRouter` * @param routerSigner address router signer */ function getRouterAddress(address routerSigner) external view override returns (address) { return Create2.computeAddress(generateSalt(routerSigner), keccak256(getBytecode())); } //////////////////////////////////////// // Internal Methods function getBytecode() internal view returns (bytes memory) { bytes memory bytecode = type(Router).creationCode; return abi.encodePacked(bytecode, abi.encode(address(this))); } function generateSalt(address routerSigner) internal pure returns (bytes32) { return keccak256(abi.encodePacked(routerSigner)); } } // File contracts/test/Counter.sol pragma solidity 0.8.4; contract Counter { bool public shouldRevert; uint256 public count = 0; constructor() { shouldRevert = false; } function setShouldRevert(bool value) public { shouldRevert = value; } function increment() public { require(!shouldRevert, "increment: shouldRevert is true"); count += 1; } function incrementAndSend( address assetId, address recipient, uint256 amount ) public payable { if (LibAsset.isNativeAsset(assetId)) { require(msg.value == amount, "incrementAndSend: INVALID_ETH_AMOUNT"); } else { require(msg.value == 0, "incrementAndSend: ETH_WITH_ERC"); LibAsset.transferFromERC20(assetId, msg.sender, address(this), amount); } increment(); LibAsset.transferAsset(assetId, payable(recipient), amount); } } // File contracts/interfaces/IERC20Minimal.sol pragma solidity >=0.5.0; /// @title Minimal ERC20 interface for Uniswap /// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3 interface IERC20Minimal { /// @notice Returns the balance of a token /// @param account The account for which to look up the number of tokens it has, i.e. its balance /// @return The number of tokens held by the account function balanceOf(address account) external view returns (uint256); /// @notice Transfers the amount of token from the `msg.sender` to the recipient /// @param recipient The account that will receive the amount transferred /// @param amount The number of tokens to send from the sender to the recipient /// @return Returns true for a successful transfer, false for an unsuccessful transfer function transfer(address recipient, uint256 amount) external returns (bool); /// @notice Returns the current allowance given to a spender by an owner /// @param owner The account of the token owner /// @param spender The account of the token spender /// @return The current allowance granted by `owner` to `spender` function allowance(address owner, address spender) external view returns (uint256); /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount` /// @param spender The account which will be allowed to spend a given amount of the owners tokens /// @param amount The amount of tokens allowed to be used by `spender` /// @return Returns true for a successful approval, false for unsuccessful function approve(address spender, uint256 amount) external returns (bool); /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender` /// @param sender The account from which the transfer will be initiated /// @param recipient The recipient of the transfer /// @param amount The amount of the transfer /// @return Returns true for a successful transfer, false for unsuccessful function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`. /// @param from The account from which the tokens were sent, i.e. the balance decreased /// @param to The account to which the tokens were sent, i.e. the balance increased /// @param value The amount of tokens that were transferred event Transfer(address indexed from, address indexed to, uint256 value); /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes. /// @param owner The account that approved spending of its tokens /// @param spender The account for which the spending allowance was modified /// @param value The new allowance from the owner to the spender event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] pragma solidity ^0.8.0; /** * @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 @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity ^0.8.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, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File contracts/test/FeeERC20.sol pragma solidity 0.8.4; /* This token is ONLY useful for testing * Anybody can mint as many tokens as they like * Anybody can burn anyone else's tokens */ contract FeeERC20 is ERC20 { uint256 public fee = 1; constructor() ERC20("Fee Token", "FEERC20") { _mint(msg.sender, 1000000 ether); } function setFee(uint256 _fee) external { fee = _fee; } function mint(address account, uint256 amount) external { _mint(account, amount); } function burn(address account, uint256 amount) external { _burn(account, amount); } function transfer(address account, uint256 amount) public override returns (bool) { uint256 toTransfer = amount - fee; _transfer(msg.sender, account, toTransfer); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { uint256 toTransfer = amount - fee; _burn(sender, fee); _transfer(sender, recipient, toTransfer); return true; } } // File contracts/test/LibAssetTest.sol pragma solidity 0.8.4; /// @title LibAssetTest /// @author Connext /// @notice Used to easily test the internal methods of /// LibAsset.sol by aliasing them to public /// methods. contract LibAssetTest { constructor() {} receive() external payable {} function isNativeAsset(address assetId) public pure returns (bool) { return LibAsset.isNativeAsset(assetId); } function getOwnBalance(address assetId) public view returns (uint256) { return LibAsset.getOwnBalance(assetId); } function transferNativeAsset(address payable recipient, uint256 amount) public { LibAsset.transferNativeAsset(recipient, amount); } function increaseERC20Allowance( address assetId, address spender, uint256 amount ) public { LibAsset.increaseERC20Allowance(assetId, spender, amount); } function decreaseERC20Allowance( address assetId, address spender, uint256 amount ) public { LibAsset.decreaseERC20Allowance(assetId, spender, amount); } function transferERC20( address assetId, address recipient, uint256 amount ) public { LibAsset.transferERC20(assetId, recipient, amount); } // This function is a wrapper for transfers of Ether or ERC20 tokens, // both standard-compliant ones as well as tokens that exhibit the // missing-return-value bug. function transferAsset( address assetId, address payable recipient, uint256 amount ) public { LibAsset.transferAsset(assetId, recipient, amount); } } // File contracts/test/RevertableERC20.sol pragma solidity 0.8.4; /* This token is ONLY useful for testing * Anybody can mint as many tokens as they like * Anybody can burn anyone else's tokens */ contract RevertableERC20 is ERC20 { bool public shouldRevert = false; constructor() ERC20("Revertable Token", "RVRT") { _mint(msg.sender, 1000000 ether); } function mint(address account, uint256 amount) external { require(!shouldRevert, "mint: SHOULD_REVERT"); _mint(account, amount); } function burn(address account, uint256 amount) external { require(!shouldRevert, "burn: SHOULD_REVERT"); _burn(account, amount); } function transfer(address account, uint256 amount) public override returns (bool) { require(!shouldRevert, "transfer: SHOULD_REVERT"); _transfer(msg.sender, account, amount); return true; } function balanceOf(address account) public view override returns (uint256) { require(!shouldRevert, "balanceOf: SHOULD_REVERT"); return super.balanceOf(account); } function setShouldRevert(bool _shouldRevert) external { shouldRevert = _shouldRevert; } } // File contracts/test/TestERC20.sol pragma solidity 0.8.4; /* This token is ONLY useful for testing * Anybody can mint as many tokens as they like * Anybody can burn anyone else's tokens */ contract TestERC20 is ERC20 { constructor() ERC20("Test Token", "TEST") { _mint(msg.sender, 1000000 ether); } function mint(address account, uint256 amount) external { _mint(account, amount); } function burn(address account, uint256 amount) external { _burn(account, amount); } } // File contracts/ProposedOwnable.sol pragma solidity 0.8.4; /** * @title ProposedOwnable * @notice 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 via a two step process: * 1. Call `proposeOwner` * 2. Wait out the delay period * 3. Call `acceptOwner` * * @dev 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. * * @dev The majority of this code was taken from the openzeppelin Ownable * contract * */ abstract contract ProposedOwnable { address private _owner; address private _proposed; uint256 private _proposedOwnershipTimestamp; bool private _routerOwnershipRenounced; uint256 private _routerOwnershipTimestamp; bool private _assetOwnershipRenounced; uint256 private _assetOwnershipTimestamp; uint256 private constant _delay = 7 days; event RouterOwnershipRenunciationProposed(uint256 timestamp); event RouterOwnershipRenounced(bool renounced); event AssetOwnershipRenunciationProposed(uint256 timestamp); event AssetOwnershipRenounced(bool renounced); event OwnershipProposed(address indexed proposedOwner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @notice Initializes the contract setting the deployer as the initial * owner. */ constructor() { _setOwner(msg.sender); } /** * @notice Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @notice Returns the address of the proposed owner. */ function proposed() public view virtual returns (address) { return _proposed; } /** * @notice Returns the address of the proposed owner. */ function proposedTimestamp() public view virtual returns (uint256) { return _proposedOwnershipTimestamp; } /** * @notice Returns the timestamp when router ownership was last proposed to be renounced */ function routerOwnershipTimestamp() public view virtual returns (uint256) { return _routerOwnershipTimestamp; } /** * @notice Returns the timestamp when asset ownership was last proposed to be renounced */ function assetOwnershipTimestamp() public view virtual returns (uint256) { return _assetOwnershipTimestamp; } /** * @notice Returns the delay period before a new owner can be accepted. */ function delay() public view virtual returns (uint256) { return _delay; } /** * @notice Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == msg.sender, "#OO:029"); _; } /** * @notice Throws if called by any account other than the proposed owner. */ modifier onlyProposed() { require(_proposed == msg.sender, "#OP:035"); _; } /** * @notice Indicates if the ownership of the router whitelist has * been renounced */ function isRouterOwnershipRenounced() public view returns (bool) { return _owner == address(0) || _routerOwnershipRenounced; } /** * @notice Indicates if the ownership of the router whitelist has * been renounced */ function proposeRouterOwnershipRenunciation() public virtual onlyOwner { // Use contract as source of truth // Will fail if all ownership is renounced by modifier require(!_routerOwnershipRenounced, "#PROR:038"); // Begin delay, emit event _setRouterOwnershipTimestamp(); } /** * @notice Indicates if the ownership of the asset whitelist has * been renounced */ function renounceRouterOwnership() public virtual onlyOwner { // Contract as sournce of truth // Will fail if all ownership is renounced by modifier require(!_routerOwnershipRenounced, "#RRO:038"); // Ensure there has been a proposal cycle started require(_routerOwnershipTimestamp > 0, "#RRO:037"); // Delay has elapsed require((block.timestamp - _routerOwnershipTimestamp) > _delay, "#RRO:030"); // Set renounced, emit event, reset timestamp to 0 _setRouterOwnership(true); } /** * @notice Indicates if the ownership of the asset whitelist has * been renounced */ function isAssetOwnershipRenounced() public view returns (bool) { return _owner == address(0) || _assetOwnershipRenounced; } /** * @notice Indicates if the ownership of the asset whitelist has * been renounced */ function proposeAssetOwnershipRenunciation() public virtual onlyOwner { // Contract as sournce of truth // Will fail if all ownership is renounced by modifier require(!_assetOwnershipRenounced, "#PAOR:038"); // Start cycle, emit event _setAssetOwnershipTimestamp(); } /** * @notice Indicates if the ownership of the asset whitelist has * been renounced */ function renounceAssetOwnership() public virtual onlyOwner { // Contract as sournce of truth // Will fail if all ownership is renounced by modifier require(!_assetOwnershipRenounced, "#RAO:038"); // Ensure there has been a proposal cycle started require(_assetOwnershipTimestamp > 0, "#RAO:037"); // Ensure delay has elapsed require((block.timestamp - _assetOwnershipTimestamp) > _delay, "#RAO:030"); // Set ownership, reset timestamp, emit event _setAssetOwnership(true); } /** * @notice Indicates if the ownership has been renounced() by * checking if current owner is address(0) */ function renounced() public view returns (bool) { return _owner == address(0); } /** * @notice Sets the timestamp for an owner to be proposed, and sets the * newly proposed owner as step 1 in a 2-step process */ function proposeNewOwner(address newlyProposed) public virtual onlyOwner { // Contract as source of truth require(_proposed != newlyProposed || newlyProposed == address(0), "#PNO:036"); // Sanity check: reasonable proposal require(_owner != newlyProposed, "#PNO:038"); _setProposed(newlyProposed); } /** * @notice Renounces ownership of the contract after a delay */ function renounceOwnership() public virtual onlyOwner { // Ensure there has been a proposal cycle started require(_proposedOwnershipTimestamp > 0, "#RO:037"); // Ensure delay has elapsed require((block.timestamp - _proposedOwnershipTimestamp) > _delay, "#RO:030"); // Require proposed is set to 0 require(_proposed == address(0), "#RO:036"); // Emit event, set new owner, reset timestamp _setOwner(_proposed); } /** * @notice Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function acceptProposedOwner() public virtual onlyProposed { // Contract as source of truth require(_owner != _proposed, "#APO:038"); // NOTE: no need to check if _proposedOwnershipTimestamp > 0 because // the only time this would happen is if the _proposed was never // set (will fail from modifier) or if the owner == _proposed (checked // above) // Ensure delay has elapsed require((block.timestamp - _proposedOwnershipTimestamp) > _delay, "#APO:030"); // Emit event, set new owner, reset timestamp _setOwner(_proposed); } ////// INTERNAL ////// function _setRouterOwnershipTimestamp() private { _routerOwnershipTimestamp = block.timestamp; emit RouterOwnershipRenunciationProposed(_routerOwnershipTimestamp); } function _setRouterOwnership(bool value) private { _routerOwnershipRenounced = value; _routerOwnershipTimestamp = 0; emit RouterOwnershipRenounced(value); } function _setAssetOwnershipTimestamp() private { _assetOwnershipTimestamp = block.timestamp; emit AssetOwnershipRenunciationProposed(_assetOwnershipTimestamp); } function _setAssetOwnership(bool value) private { _assetOwnershipRenounced = value; _assetOwnershipTimestamp = 0; emit AssetOwnershipRenounced(value); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; _proposedOwnershipTimestamp = 0; emit OwnershipTransferred(oldOwner, newOwner); } function _setProposed(address newlyProposed) private { _proposedOwnershipTimestamp = block.timestamp; _proposed = newlyProposed; emit OwnershipProposed(_proposed); } } // File contracts/TransactionManager.sol pragma solidity 0.8.4; /** * * @title TransactionManager * @author Connext <[email protected]> * @notice This contract holds the logic to facilitate crosschain transactions. * Transactions go through three phases in the happy case: * * 1. Route Auction (offchain): User broadcasts to our network * signalling their desired route. Routers respond with sealed bids * containing commitments to fulfilling the transaction within a * certain time and price range. * * 2. Prepare: Once the auction is completed, the transaction can be * prepared. The user submits a transaction to `TransactionManager` * contract on sender-side chain containing router's signed bid. This * transaction locks up the users funds on the sending chain. Upon * detecting an event containing their signed bid from the chain, * router submits the same transaction to `TransactionManager` on the * receiver-side chain, and locks up a corresponding amount of * liquidity. The amount locked on the receiving chain is `sending * amount - auction fee` so the router is incentivized to complete the * transaction. * * 3. Fulfill: Upon detecting the `TransactionPrepared` event on the * receiver-side chain, the user signs a message and sends it to a * relayer, who will earn a fee for submission. The relayer (which may * be the router) then submits the message to the `TransactionManager` * to complete their transaction on receiver-side chain and claim the * funds locked by the router. A relayer is used here to allow users * to submit transactions with arbitrary calldata on the receiving * chain without needing gas to do so. The router then submits the * same signed message and completes transaction on sender-side, * unlocking the original `amount`. * * If a transaction is not fulfilled within a fixed timeout, it * reverts and can be reclaimed by the party that called `prepare` on * each chain (initiator). Additionally, transactions can be cancelled * unilaterally by the person owed funds on that chain (router for * sending chain, user for receiving chain) prior to expiry. */ contract TransactionManager is ReentrancyGuard, ProposedOwnable, ITransactionManager { /** * @dev Mapping of router to balance specific to asset */ mapping(address => mapping(address => uint256)) public routerBalances; /** * @dev Mapping of allowed router addresses. Must be added to both * sending and receiving chains when forwarding a transfer. */ mapping(address => bool) public approvedRouters; /** * @dev Mapping of allowed assetIds on same chain as contract */ mapping(address => bool) public approvedAssets; /** * @dev Mapping of hash of `InvariantTransactionData` to the hash * of the `VariantTransactionData` */ mapping(bytes32 => bytes32) public variantTransactionData; /** * @dev The stored chain id of the contract, may be passed in to avoid any * evm issues */ uint256 private immutable chainId; /** * @dev Minimum timeout (will be the lowest on the receiving chain) */ uint256 public constant MIN_TIMEOUT = 1 days; // 24 hours /** * @dev Maximum timeout (will be the highest on the sending chain) */ uint256 public constant MAX_TIMEOUT = 30 days; // 720 hours /** * @dev The external contract that will execute crosschain * calldata */ IFulfillInterpreter public immutable interpreter; constructor(uint256 _chainId) { chainId = _chainId; interpreter = new FulfillInterpreter(address(this)); } /** * @notice Gets the chainId for this contract. If not specified during init * will use the block.chainId */ function getChainId() public view override returns (uint256 _chainId) { // Hold in memory to reduce sload calls uint256 chain = chainId; if (chain == 0) { // If not provided, pull from block chain = block.chainid; } return chain; } /** * @notice Allows us to get the chainId that this contract has stored */ function getStoredChainId() external view override returns (uint256) { return chainId; } /** * @notice Used to add routers that can transact crosschain * @param router Router address to add */ function addRouter(address router) external override onlyOwner { // Sanity check: not empty require(router != address(0), "#AR:001"); // Sanity check: needs approval require(approvedRouters[router] == false, "#AR:032"); // Update mapping approvedRouters[router] = true; // Emit event emit RouterAdded(router, msg.sender); } /** * @notice Used to remove routers that can transact crosschain * @param router Router address to remove */ function removeRouter(address router) external override onlyOwner { // Sanity check: not empty require(router != address(0), "#RR:001"); // Sanity check: needs removal require(approvedRouters[router] == true, "#RR:033"); // Update mapping approvedRouters[router] = false; // Emit event emit RouterRemoved(router, msg.sender); } /** * @notice Used to add assets on same chain as contract that can * be transferred. * @param assetId AssetId to add */ function addAssetId(address assetId) external override onlyOwner { // Sanity check: needs approval require(approvedAssets[assetId] == false, "#AA:032"); // Update mapping approvedAssets[assetId] = true; // Emit event emit AssetAdded(assetId, msg.sender); } /** * @notice Used to remove assets on same chain as contract that can * be transferred. * @param assetId AssetId to remove */ function removeAssetId(address assetId) external override onlyOwner { // Sanity check: already approval require(approvedAssets[assetId] == true, "#RA:033"); // Update mapping approvedAssets[assetId] = false; // Emit event emit AssetRemoved(assetId, msg.sender); } /** * @notice This is used by anyone to increase a router's available * liquidity for a given asset. * @param amount The amount of liquidity to add for the router * @param assetId The address (or `address(0)` if native asset) of the * asset you're adding liquidity for * @param router The router you are adding liquidity on behalf of */ function addLiquidityFor( uint256 amount, address assetId, address router ) external payable override nonReentrant { _addLiquidityForRouter(amount, assetId, router); } /** * @notice This is used by any router to increase their available * liquidity for a given asset. * @param amount The amount of liquidity to add for the router * @param assetId The address (or `address(0)` if native asset) of the * asset you're adding liquidity for */ function addLiquidity(uint256 amount, address assetId) external payable override nonReentrant { _addLiquidityForRouter(amount, assetId, msg.sender); } /** * @notice This is used by any router to decrease their available * liquidity for a given asset. * @param amount The amount of liquidity to remove for the router * @param assetId The address (or `address(0)` if native asset) of the * asset you're removing liquidity for * @param recipient The address that will receive the liquidity being removed */ function removeLiquidity( uint256 amount, address assetId, address payable recipient ) external override nonReentrant { // Sanity check: recipient is sensible require(recipient != address(0), "#RL:007"); // Sanity check: nonzero amounts require(amount > 0, "#RL:002"); uint256 routerBalance = routerBalances[msg.sender][assetId]; // Sanity check: amount can be deducted for the router require(routerBalance >= amount, "#RL:008"); // Update router balances unchecked { routerBalances[msg.sender][assetId] = routerBalance - amount; } // Transfer from contract to specified recipient LibAsset.transferAsset(assetId, recipient, amount); // Emit event emit LiquidityRemoved(msg.sender, assetId, amount, recipient); } /** * @notice This function creates a crosschain transaction. When called on * the sending chain, the user is expected to lock up funds. When * called on the receiving chain, the router deducts the transfer * amount from the available liquidity. The majority of the * information about a given transfer does not change between chains, * with three notable exceptions: `amount`, `expiry`, and * `preparedBlock`. The `amount` and `expiry` are decremented * between sending and receiving chains to provide an incentive for * the router to complete the transaction and time for the router to * fulfill the transaction on the sending chain after the unlocking * signature is revealed, respectively. * @param args TODO */ function prepare(PrepareArgs calldata args) external payable override nonReentrant returns (TransactionData memory) { // Sanity check: user is sensible require(args.invariantData.user != address(0), "#P:009"); // Sanity check: router is sensible require(args.invariantData.router != address(0), "#P:001"); // Router is approved *on both chains* require(isRouterOwnershipRenounced() || approvedRouters[args.invariantData.router], "#P:003"); // Sanity check: sendingChainFallback is sensible require(args.invariantData.sendingChainFallback != address(0), "#P:010"); // Sanity check: valid fallback require(args.invariantData.receivingAddress != address(0), "#P:026"); // Make sure the chains are different require(args.invariantData.sendingChainId != args.invariantData.receivingChainId, "#P:011"); // Make sure the chains are relevant uint256 _chainId = getChainId(); require(args.invariantData.sendingChainId == _chainId || args.invariantData.receivingChainId == _chainId, "#P:012"); { // Expiry scope // Make sure the expiry is greater than min uint256 buffer = args.expiry - block.timestamp; require(buffer >= MIN_TIMEOUT, "#P:013"); // Make sure the expiry is lower than max require(buffer <= MAX_TIMEOUT, "#P:014"); } // Make sure the hash is not a duplicate bytes32 digest = keccak256(abi.encode(args.invariantData)); require(variantTransactionData[digest] == bytes32(0), "#P:015"); // NOTE: the `encodedBid` and `bidSignature` are simply passed through // to the contract emitted event to ensure the availability of // this information. Their validity is asserted offchain, and // is out of scope of this contract. They are used as inputs so // in the event of a router or user crash, they may recover the // correct bid information without requiring an offchain store. // Amount actually used (if fee-on-transfer will be different than // supplied) uint256 amount = args.amount; // First determine if this is sender side or receiver side if (args.invariantData.sendingChainId == _chainId) { // Check the sender is correct require(msg.sender == args.invariantData.initiator, "#P:039"); // Sanity check: amount is sensible // Only check on sending chain to enforce router fees. Transactions could // be 0-valued on receiving chain if it is just a value-less call to some // `IFulfillHelper` require(args.amount > 0, "#P:002"); // Assets are approved // NOTE: Cannot check this on receiving chain because of differing // chain contexts require(isAssetOwnershipRenounced() || approvedAssets[args.invariantData.sendingAssetId], "#P:004"); // This is sender side prepare. The user is beginning the process of // submitting an onchain tx after accepting some bid. They should // lock their funds in the contract for the router to claim after // they have revealed their signature on the receiving chain via // submitting a corresponding `fulfill` tx // Validate correct amounts on msg and transfer from user to // contract amount = transferAssetToContract(args.invariantData.sendingAssetId, args.amount); // Store the transaction variants. This happens after transferring to // account for fee on transfer tokens variantTransactionData[digest] = hashVariantTransactionData(amount, args.expiry, block.number); } else { // This is receiver side prepare. The router has proposed a bid on the // transfer which the user has accepted. They can now lock up their // own liquidity on th receiving chain, which the user can unlock by // calling `fulfill`. When creating the `amount` and `expiry` on the // receiving chain, the router should have decremented both. The // expiry should be decremented to ensure the router has time to // complete the sender-side transaction after the user completes the // receiver-side transactoin. The amount should be decremented to act as // a fee to incentivize the router to complete the transaction properly. // Check that the callTo is a contract // NOTE: This cannot happen on the sending chain (different chain // contexts), so a user could mistakenly create a transfer that must be // cancelled if this is incorrect require(args.invariantData.callTo == address(0) || Address.isContract(args.invariantData.callTo), "#P:031"); // Check that the asset is approved // NOTE: This cannot happen on both chains because of differing chain // contexts. May be possible for user to create transaction that is not // prepare-able on the receiver chain. require(isAssetOwnershipRenounced() || approvedAssets[args.invariantData.receivingAssetId], "#P:004"); // Check that the caller is the router require(msg.sender == args.invariantData.router, "#P:016"); // Check that the router isnt accidentally locking funds in the contract require(msg.value == 0, "#P:017"); // Check that router has liquidity uint256 balance = routerBalances[args.invariantData.router][args.invariantData.receivingAssetId]; require(balance >= amount, "#P:018"); // Store the transaction variants variantTransactionData[digest] = hashVariantTransactionData(amount, args.expiry, block.number); // Decrement the router liquidity // using unchecked because underflow protected against with require unchecked { routerBalances[args.invariantData.router][args.invariantData.receivingAssetId] = balance - amount; } } // Emit event TransactionData memory txData = TransactionData({ receivingChainTxManagerAddress: args.invariantData.receivingChainTxManagerAddress, user: args.invariantData.user, router: args.invariantData.router, initiator: args.invariantData.initiator, sendingAssetId: args.invariantData.sendingAssetId, receivingAssetId: args.invariantData.receivingAssetId, sendingChainFallback: args.invariantData.sendingChainFallback, callTo: args.invariantData.callTo, receivingAddress: args.invariantData.receivingAddress, callDataHash: args.invariantData.callDataHash, transactionId: args.invariantData.transactionId, sendingChainId: args.invariantData.sendingChainId, receivingChainId: args.invariantData.receivingChainId, amount: amount, expiry: args.expiry, preparedBlockNumber: block.number }); emit TransactionPrepared(txData.user, txData.router, txData.transactionId, txData, msg.sender, args); return txData; } /** * @notice This function completes a crosschain transaction. When called on * the receiving chain, the user reveals their signature on the * transactionId and is sent the amount corresponding to the number * of shares the router locked when calling `prepare`. The router * then uses this signature to unlock the corresponding funds on the * receiving chain, which are then added back to their available * liquidity. The user includes a relayer fee since it is not * assumed they will have gas on the receiving chain. This function * *must* be called before the transaction expiry has elapsed. * @param args TODO */ function fulfill(FulfillArgs calldata args) external override nonReentrant returns (TransactionData memory) { // Get the hash of the invariant tx data. This hash is the same // between sending and receiving chains. The variant data is stored // in the contract when `prepare` is called within the mapping. { // scope: validation and effects bytes32 digest = hashInvariantTransactionData(args.txData); // Make sure that the variant data matches what was stored require( variantTransactionData[digest] == hashVariantTransactionData(args.txData.amount, args.txData.expiry, args.txData.preparedBlockNumber), "#F:019" ); // Make sure the expiry has not elapsed require(args.txData.expiry >= block.timestamp, "#F:020"); // Make sure the transaction wasn't already completed require(args.txData.preparedBlockNumber > 0, "#F:021"); // Check provided callData matches stored hash require(keccak256(args.callData) == args.txData.callDataHash, "#F:024"); // To prevent `fulfill` / `cancel` from being called multiple times, the // preparedBlockNumber is set to 0 before being hashed. The value of the // mapping is explicitly *not* zeroed out so users who come online without // a store can tell the difference between a transaction that has not been // prepared, and a transaction that was already completed on the receiver // chain. variantTransactionData[digest] = hashVariantTransactionData(args.txData.amount, args.txData.expiry, 0); } // Declare these variables for the event emission. Are only assigned // IFF there is an external call on the receiving chain bool success; bool isContract; bytes memory returnData; uint256 _chainId = getChainId(); if (args.txData.sendingChainId == _chainId) { // The router is completing the transaction, they should get the // amount that the user deposited credited to their liquidity // reserves. // Make sure that the user is not accidentally fulfilling the transaction // on the sending chain require(msg.sender == args.txData.router, "#F:016"); // Validate the user has signed require( recoverFulfillSignature( args.txData.transactionId, args.relayerFee, args.txData.receivingChainId, args.txData.receivingChainTxManagerAddress, args.signature ) == args.txData.user, "#F:022" ); // Complete tx to router for original sending amount routerBalances[args.txData.router][args.txData.sendingAssetId] += args.txData.amount; } else { // Validate the user has signed, using domain of contract require( recoverFulfillSignature(args.txData.transactionId, args.relayerFee, _chainId, address(this), args.signature) == args.txData.user, "#F:022" ); // Sanity check: fee <= amount. Allow `=` in case of only // wanting to execute 0-value crosschain tx, so only providing // the fee amount require(args.relayerFee <= args.txData.amount, "#F:023"); (success, isContract, returnData) = _receivingChainFulfill(args.txData, args.relayerFee, args.callData); } // Emit event emit TransactionFulfilled( args.txData.user, args.txData.router, args.txData.transactionId, args, success, isContract, returnData, msg.sender ); return args.txData; } /** * @notice Any crosschain transaction can be cancelled after it has been * created to prevent indefinite lock up of funds. After the * transaction has expired, anyone can cancel it. Before the * expiry, only the recipient of the funds on the given chain is * able to cancel. On the sending chain, this means only the router * is able to cancel before the expiry, while only the user can * prematurely cancel on the receiving chain. * @param args TODO */ function cancel(CancelArgs calldata args) external override nonReentrant returns (TransactionData memory) { // Make sure params match against stored data // Also checks that there is an active transfer here // Also checks that sender or receiver chainID is this chainId (bc we checked it previously) // Get the hash of the invariant tx data. This hash is the same // between sending and receiving chains. The variant data is stored // in the contract when `prepare` is called within the mapping. bytes32 digest = hashInvariantTransactionData(args.txData); // Verify the variant data is correct require( variantTransactionData[digest] == hashVariantTransactionData(args.txData.amount, args.txData.expiry, args.txData.preparedBlockNumber), "#C:019" ); // Make sure the transaction wasn't already completed require(args.txData.preparedBlockNumber > 0, "#C:021"); // To prevent `fulfill` / `cancel` from being called multiple times, the // preparedBlockNumber is set to 0 before being hashed. The value of the // mapping is explicitly *not* zeroed out so users who come online without // a store can tell the difference between a transaction that has not been // prepared, and a transaction that was already completed on the receiver // chain. variantTransactionData[digest] = hashVariantTransactionData(args.txData.amount, args.txData.expiry, 0); // Get chainId for gas uint256 _chainId = getChainId(); // Return the appropriate locked funds if (args.txData.sendingChainId == _chainId) { // Sender side, funds must be returned to the user if (args.txData.expiry >= block.timestamp) { // Timeout has not expired and tx may only be cancelled by router // NOTE: no need to validate the signature here, since you are requiring // the router must be the sender when the cancellation is during the // fulfill-able window require(msg.sender == args.txData.router, "#C:025"); } // Return users locked funds // NOTE: no need to check if amount > 0 because cant be prepared on // sending chain with 0 value LibAsset.transferAsset(args.txData.sendingAssetId, payable(args.txData.sendingChainFallback), args.txData.amount); } else { // Receiver side, router liquidity is returned if (args.txData.expiry >= block.timestamp) { // Timeout has not expired and tx may only be cancelled by user // Validate signature require( msg.sender == args.txData.user || recoverCancelSignature(args.txData.transactionId, _chainId, address(this), args.signature) == args.txData.user, "#C:022" ); // NOTE: there is no incentive here for relayers to submit this on // behalf of the user (i.e. fee not respected) because the user has not // locked funds on this contract. However, if the user reveals their // cancel signature to the router, they are incentivized to submit it // to unlock their own funds } // Return liquidity to router routerBalances[args.txData.router][args.txData.receivingAssetId] += args.txData.amount; } // Emit event emit TransactionCancelled(args.txData.user, args.txData.router, args.txData.transactionId, args, msg.sender); // Return return args.txData; } ////////////////////////// /// Private functions /// ////////////////////////// /** * @notice Contains the logic to verify + increment a given routers liquidity * @param amount The amount of liquidity to add for the router * @param assetId The address (or `address(0)` if native asset) of the * asset you're adding liquidity for * @param router The router you are adding liquidity on behalf of */ function _addLiquidityForRouter( uint256 amount, address assetId, address router ) internal { // Sanity check: router is sensible require(router != address(0), "#AL:001"); // Sanity check: nonzero amounts require(amount > 0, "#AL:002"); // Router is approved require(isRouterOwnershipRenounced() || approvedRouters[router], "#AL:003"); // Asset is approved require(isAssetOwnershipRenounced() || approvedAssets[assetId], "#AL:004"); // Transfer funds to contract amount = transferAssetToContract(assetId, amount); // Update the router balances. Happens after pulling funds to account for // the fee on transfer tokens routerBalances[router][assetId] += amount; // Emit event emit LiquidityAdded(router, assetId, amount, msg.sender); } /** * @notice Handles transferring funds from msg.sender to the * transaction manager contract. Used in prepare, addLiquidity * @param assetId The address to transfer * @param specifiedAmount The specified amount to transfer. May not be the * actual amount transferred (i.e. fee on transfer * tokens) */ function transferAssetToContract(address assetId, uint256 specifiedAmount) internal returns (uint256) { uint256 trueAmount = specifiedAmount; // Validate correct amounts are transferred if (LibAsset.isNativeAsset(assetId)) { require(msg.value == specifiedAmount, "#TA:005"); } else { uint256 starting = LibAsset.getOwnBalance(assetId); require(msg.value == 0, "#TA:006"); LibAsset.transferFromERC20(assetId, msg.sender, address(this), specifiedAmount); // Calculate the *actual* amount that was sent here trueAmount = LibAsset.getOwnBalance(assetId) - starting; } return trueAmount; } /// @notice Recovers the signer from the signature provided by the user /// @param transactionId Transaction identifier of tx being recovered /// @param signature The signature you are recovering the signer from function recoverCancelSignature( bytes32 transactionId, uint256 receivingChainId, address receivingChainTxManagerAddress, bytes calldata signature ) internal pure returns (address) { // Create the signed payload SignedCancelData memory payload = SignedCancelData({ transactionId: transactionId, functionIdentifier: "cancel", receivingChainId: receivingChainId, receivingChainTxManagerAddress: receivingChainTxManagerAddress }); // Recover return recoverSignature(abi.encode(payload), signature); } /** * @notice Recovers the signer from the signature provided by the user * @param transactionId Transaction identifier of tx being recovered * @param relayerFee The fee paid to the relayer for submitting the * tx on behalf of the user. * @param signature The signature you are recovering the signer from */ function recoverFulfillSignature( bytes32 transactionId, uint256 relayerFee, uint256 receivingChainId, address receivingChainTxManagerAddress, bytes calldata signature ) internal pure returns (address) { // Create the signed payload SignedFulfillData memory payload = SignedFulfillData({ transactionId: transactionId, relayerFee: relayerFee, functionIdentifier: "fulfill", receivingChainId: receivingChainId, receivingChainTxManagerAddress: receivingChainTxManagerAddress }); // Recover return recoverSignature(abi.encode(payload), signature); } /** * @notice Holds the logic to recover the signer from an encoded payload. * Will hash and convert to an eth signed message. * @param encodedPayload The payload that was signed * @param signature The signature you are recovering the signer from */ function recoverSignature(bytes memory encodedPayload, bytes calldata signature) internal pure returns (address) { // Recover return ECDSA.recover(ECDSA.toEthSignedMessageHash(keccak256(encodedPayload)), signature); } /** * @notice Returns the hash of only the invariant portions of a given * crosschain transaction * @param txData TransactionData to hash */ function hashInvariantTransactionData(TransactionData calldata txData) internal pure returns (bytes32) { InvariantTransactionData memory invariant = InvariantTransactionData({ receivingChainTxManagerAddress: txData.receivingChainTxManagerAddress, user: txData.user, router: txData.router, initiator: txData.initiator, sendingAssetId: txData.sendingAssetId, receivingAssetId: txData.receivingAssetId, sendingChainFallback: txData.sendingChainFallback, callTo: txData.callTo, receivingAddress: txData.receivingAddress, sendingChainId: txData.sendingChainId, receivingChainId: txData.receivingChainId, callDataHash: txData.callDataHash, transactionId: txData.transactionId }); return keccak256(abi.encode(invariant)); } /** * @notice Returns the hash of only the variant portions of a given * crosschain transaction * @param amount amount to hash * @param expiry expiry to hash * @param preparedBlockNumber preparedBlockNumber to hash * @return Hash of the variant data * */ function hashVariantTransactionData( uint256 amount, uint256 expiry, uint256 preparedBlockNumber ) internal pure returns (bytes32) { VariantTransactionData memory variant = VariantTransactionData({ amount: amount, expiry: expiry, preparedBlockNumber: preparedBlockNumber }); return keccak256(abi.encode(variant)); } /** * @notice Handles the receiving-chain fulfillment. This function should * pay the relayer and either send funds to the specified address * or execute the calldata. Will return a tuple of boolean,bytes * indicating the success and return data of the external call. * @dev Separated from fulfill function to avoid stack too deep errors * * @param txData The TransactionData that needs to be fulfilled * @param relayerFee The fee to be paid to the relayer for submission * @param callData The data to be executed on the receiving chain * * @return Tuple representing (success, returnData) of the external call */ function _receivingChainFulfill( TransactionData calldata txData, uint256 relayerFee, bytes calldata callData ) internal returns ( bool, bool, bytes memory ) { // The user is completing the transaction, they should get the // amount that the router deposited less fees for relayer. // Get the amount to send uint256 toSend; unchecked { toSend = txData.amount - relayerFee; } // Send the relayer the fee if (relayerFee > 0) { LibAsset.transferAsset(txData.receivingAssetId, payable(msg.sender), relayerFee); } // Handle receiver chain external calls if needed if (txData.callTo == address(0)) { // No external calls, send directly to receiving address if (toSend > 0) { LibAsset.transferAsset(txData.receivingAssetId, payable(txData.receivingAddress), toSend); } return (false, false, new bytes(0)); } else { // Handle external calls with a fallback to the receiving // address in case the call fails so the funds dont remain // locked. bool isNativeAsset = LibAsset.isNativeAsset(txData.receivingAssetId); // First, transfer the funds to the helper if needed if (!isNativeAsset && toSend > 0) { LibAsset.transferERC20(txData.receivingAssetId, address(interpreter), toSend); } // Next, call `execute` on the helper. Helpers should internally // track funds to make sure no one user is able to take all funds // for tx, and handle the case of reversions return interpreter.execute{value: isNativeAsset ? toSend : 0}( txData.transactionId, payable(txData.callTo), txData.receivingAssetId, payable(txData.receivingAddress), toSend, callData ); } } } // File contracts/Multicall.sol pragma solidity ^0.8.4; pragma experimental ABIEncoderV2; /// @title Multicall - Aggregate results from multiple read-only function calls contract Multicall { struct Call { address target; bytes callData; } function aggregate(Call[] memory calls) public returns (uint256 blockNumber, bytes[] memory returnData) { blockNumber = block.number; returnData = new bytes[](calls.length); for (uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory ret) = calls[i].target.call(calls[i].callData); require(success); returnData[i] = ret; } } } // File contracts/test/TestAggregator.sol pragma solidity 0.8.4; /* * This aggregator is ONLY useful for testing */ contract TestAggregator { uint8 public decimals = 18; string public description = "Chainlink Test Aggregator"; uint256 public version = 1; int256 public mockAnswer = 1e18; // 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 ) { return (_roundId, mockAnswer, 0, block.timestamp, 1e18); } function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return (1, mockAnswer, 0, block.timestamp, 1e18); } function updateMockAnswer(int256 _answer) public { mockAnswer = _answer; } }
It's fine for price to be 0. We have two price feeds.
function getPriceFromChainlink(address _tokenAddress) public view returns (uint256) { AggregatorV3Interface aggregator = aggregators[_tokenAddress]; if (address(aggregator) != address(0)) { (, int256 answer, , , ) = aggregator.latestRoundData(); if (answer == 0) { return 0; } uint256 price = retVal.mul(10**(18 - uint256(aggregator.decimals()))); return price; } return 0; }
15,843,381
./full_match/80001/0xCBF7Ac49153AB8f5c3c4c38ad673EB8C121bF18F/sources/contracts/UpbondNFTMintableCreator.sol
Creates a new edition contract as a factory with a deterministic address Important: None of these fields (except the Url fields with the same hash) can be changed after calling _name Name of the edition contract _symbol Symbol of the edition contract _description Metadata: Description of the edition entry _url Metadata: The URI may point to a JSON file that conforms to the "ERC721string memory _publisher_publisher Returns the ID of the recently created minting contract Also increments for the next contract creation call
function createAssets( string memory _name, string memory _symbol, string memory _description, string memory _url ) external returns (uint256) { uint256 newId = atContract.current(); address newContract = ClonesUpgradeable.cloneDeterministic( implementation, bytes32(abi.encodePacked(newId)) ); UpbondNFTMintable(newContract)._initialize( msg.sender, _name, _symbol, _description, _url ); emit CreatedAssets(newId, msg.sender, newContract); atContract.increment(); return newId; }
9,466,780
// File: contracts/WBGLToken.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol /** * @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); } } } } // File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.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 || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File: @openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface 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); } // File: @openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.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 initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // File: @openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override { require(hasRole(getRoleAdmin(role), _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 override { require(hasRole(getRoleAdmin(role), _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 override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // File: @openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol /** * @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)); } } // File: @openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerableUpgradeable { function getRoleMember(bytes32 role, uint256 index) external view returns (address); function getRoleMemberCount(bytes32 role) external view returns (uint256); } /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); } function __AccessControlEnumerable_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping (bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } uint256[49] private __gap; } // File: @openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @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 this function is * overloaded; * * 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 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[45] private __gap; } // File: @openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20CappedUpgradeable.sol /** * @dev Extension of {ERC20} that adds a cap to the supply of tokens. */ abstract contract ERC20CappedUpgradeable is Initializable, ERC20Upgradeable { uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ function __ERC20Capped_init(uint256 cap_) internal initializer { __Context_init_unchained(); __ERC20Capped_init_unchained(cap_); } function __ERC20Capped_init_unchained(uint256 cap_) internal initializer { require(cap_ > 0, "ERC20Capped: cap is 0"); _cap = cap_; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view virtual returns (uint256) { return _cap; } /** * @dev See {ERC20-_mint}. */ function _mint(address account, uint256 amount) internal virtual override { require(ERC20Upgradeable.totalSupply() + amount <= cap(), "ERC20Capped: cap exceeded"); super._mint(account, amount); } uint256[50] private __gap; } // File: @openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20BurnableUpgradeable.sol /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable { function __ERC20Burnable_init() internal initializer { __Context_init_unchained(); __ERC20Burnable_init_unchained(); } function __ERC20Burnable_init_unchained() internal initializer { } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), currentAllowance - amount); _burn(account, amount); } uint256[50] private __gap; } // File: @openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // File: @openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PausableUpgradeable.sol /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20PausableUpgradeable is Initializable, ERC20Upgradeable, PausableUpgradeable { function __ERC20Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); __ERC20Pausable_init_unchained(); } function __ERC20Pausable_init_unchained() internal initializer { } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } uint256[50] private __gap; } // WBGLToken is ERC20 token that is intended to represent Bitgesell on Ethereum blockchain contract WBGLToken is Initializable, ContextUpgradeable, AccessControlEnumerableUpgradeable, ERC20CappedUpgradeable, ERC20BurnableUpgradeable, ERC20PausableUpgradeable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); function initialize(uint256 totalSupply, address owner) public virtual initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); __ERC20_init_unchained("Wrapped BGL", "WBGL"); __ERC20Capped_init_unchained(totalSupply); __ERC20Burnable_init_unchained(); __Pausable_init_unchained(); __ERC20Pausable_init_unchained(); _setupRole(DEFAULT_ADMIN_ROLE, owner); _setupRole(MINTER_ROLE, owner); _setupRole(PAUSER_ROLE, owner); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20PausableUpgradeable, ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); } function pause() public { require(hasRole(PAUSER_ROLE, _msgSender()), "Caller is not a pauser"); _pause(); } function unpause() public { require(hasRole(PAUSER_ROLE, _msgSender()), "Caller is not a pauser"); _unpause(); } function _mint(address to, uint256 amount) internal virtual override(ERC20CappedUpgradeable, ERC20Upgradeable) { super._mint(to, amount); } function mint(address to, uint256 amount) public { require(hasRole(MINTER_ROLE, _msgSender()), "Caller is not a minter"); _mint(to, amount); } uint256[50] private __gap; }
File: @openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol External interface of AccessControlEnumerable declared to support ERC165 detection./
interface IAccessControlEnumerableUpgradeable { function getRoleMember(bytes32 role, uint256 index) external view returns (address); function getRoleMemberCount(bytes32 role) external view returns (uint256); }
5,723,732
./full_match/1/0xa3a592a37803f48da9cA6c0558Ef1Fe96181c175/sources/lib/rain.math.fixedpoint/src/FixedPointDecimalScale.sol
Scales `a_` down by a specified number of decimals, rounding in the specified direction. Used internally by several other functions in this lib. a_ The number to scale down. scaleDownBy_ Number of orders of magnitude to scale `a_` down by. Overflows if greater than 77. return c_ `a_` scaled down by `scaleDownBy_` and rounded.
function scaleDown(uint256 a_, uint256 scaleDownBy_) internal pure returns (uint256) { unchecked { return scaleDownBy_ >= OVERFLOW_RESCALE_OOMS ? 0 : a_ / (10 ** scaleDownBy_); } }
17,080,328
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { 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 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); } } } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } contract SheebaInu is Context,IERC20, Ownable{ using Address for address; string private _name = "Sheeba Inu"; string private _symbol = "SHEEB"; uint8 private _decimals = 18; uint256 totalFeeFortx = 0; uint256 maxWalletTreshold = 5; uint256 maxTxTreshold = 5; uint256 private swapTreshold =2; uint256 private currentThreshold = 20; //Once the token value goes up this number can be decreased (To reduce price impact on asset) uint256 private _totalSupply = (100000000 * 10**4) * 10**_decimals; //1T supply uint256 public requiredTokensToSwap = _totalSupply * swapTreshold /1000; mapping (address => uint256) private _balances; mapping (address => bool) private _excludedFromFees; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) public automatedMarketMakerPairs; address _owner; address payable public marketingAddress = payable(0x910Ad70E105224f503067DAe10b518F73B07b5cD); address payable public prizePoolAddress = payable(0x0d5cC40d34243ae68519f6d10D0e0B61Cd297DFE); uint256 maxWalletAmount = _totalSupply*maxWalletTreshold/100; // starting 3% uint256 maxTxAmount = _totalSupply*maxTxTreshold/100; mapping (address => bool) botWallets; bool botTradeEnabled = false; bool checkWalletSize = true; //15% buy tax 20% sell tax uint256 private buyliqFee = 0; //10 uint256 private buyprevLiqFee = 10; uint256 private buymktFee = 0;//4 uint256 private buyPrevmktFee = 4; uint256 private buyprizePool = 0;//1 uint256 private buyprevPrizePool = 1; uint256 GoldenDaycooldown = 0; uint256 private sellliqFee = 13; uint256 private sellprevLiqFee = 13; uint256 private sellmktFee = 5; uint256 private sellPrevmktFee = 5; uint256 private sellprizePool = 2; uint256 private sellprevPrizePool = 2; bool public inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; address public immutable deadAddress = 0x000000000000000000000000000000000000dEaD; uint256 private mktTokens = 0; uint256 private prizepoolTokens = 0; uint256 private liqTokens = 0; event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event tokensSwappedDuringTokenomics(uint256 amount); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); // 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D IUniswapV2Router02 _router; address public uniswapV2Pair; //Balances tracker modifier lockTheSwap{ inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor(){ _balances[_msgSender()] = _totalSupply; //0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D mainnet and all networks IUniswapV2Router02 _uniRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniRouter.factory()) .createPair(address(this), _uniRouter.WETH()); _excludedFromFees[owner()] = true; _excludedFromFees[address(this)] = true;// exclude owner and contract instance from fees _router = _uniRouter; _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); emit Transfer(address(0),_msgSender(),_totalSupply); } receive() external payable{} //general token data and tracking of balances to be swapped. function getOwner()external view returns(address){ return owner(); } function currentmktTokens() external view returns (uint256){ return mktTokens; } function currentPZTokens() external view returns (uint256){ return prizepoolTokens; } function currentLiqTokens() external view returns (uint256){ return liqTokens; } function totalSupply() external view override returns (uint256){ return _totalSupply; } function balanceOf(address account) public view override returns (uint256){ return _balances[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) external override returns (bool){ _approve(_msgSender(),spender,amount); return true; } function decimals()external view returns(uint256){ return _decimals; } function name() external view returns (string memory) { return _name; } function symbol() external view returns (string memory){ return _symbol; } function updateMaxTxTreshold(uint256 newVal) public onlyOwner{ maxTxTreshold = newVal; maxTxAmount = _totalSupply*maxTxTreshold/100;// 1% } function updateMaxWalletTreshold(uint256 newVal) public onlyOwner{ maxWalletTreshold = newVal; maxWalletAmount = _totalSupply*maxWalletTreshold/100; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool){ require(amount <= _allowances[sender][_msgSender()], "BEP20: transfer amount exceeds allowance"); _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()] - amount); return true; } //Tokenomics related functions function goldenDay() public onlyOwner{ require(block.timestamp > GoldenDaycooldown, "You cant call golden Day more than once per day"); buyPrevmktFee = buymktFee; buyprevLiqFee = buyliqFee; buyprevPrizePool = buyprizePool; buyliqFee = 0; buymktFee = 0; buyprizePool = 0; } function goldenDayOver() public onlyOwner{ buyliqFee = buyprevLiqFee; buymktFee = buyPrevmktFee; buyprizePool = buyprevPrizePool; GoldenDaycooldown = block.timestamp + 86400; } function addBotWallet (address payable detectedBot, bool isBot) public onlyOwner{ botWallets[detectedBot] = isBot; } function currentbuyliqFee() public view returns (uint256){ return buyliqFee; } function currentbuymktfee() public view returns (uint256){ return buymktFee; } function currentbuyprizepoolfee() public view returns (uint256){ return buymktFee; } function currentsellLiqFee() public view returns (uint256){ return sellliqFee; } function currentsellmktfee() public view returns (uint256){ return sellmktFee; } function currentsellyprizepoolfee() public view returns (uint256){ return sellprizePool; } function currentThresholdInt()public view returns (uint256){ return currentThreshold; } function isExcluded(address toCheck)public view returns (bool){ return _excludedFromFees[toCheck]; } function _transfer(address from, address to, uint256 amount) internal{ require(from != address(0), "BEP20: transfer from the zero address"); require(to != address(0), "BEP20: transfer to the zero address"); require(amount > 0,"BEP20: transfered amount must be greater than zero"); uint256 senderBalance = _balances[from]; require(senderBalance >= amount, "BEP20: transfer amount exceeds balance"); if(from != owner() && to != owner()) require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(to != uniswapV2Pair || to !=owner()) { require(balanceOf(to) + amount < maxWalletAmount, "MCRON: Balance exceeds wallet size!"); } uint256 inContractBalance = balanceOf(address(this)); if(inContractBalance >=requiredTokensToSwap && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled){ if(inContractBalance >= requiredTokensToSwap ){ inContractBalance = requiredTokensToSwap; swapForTokenomics(inContractBalance); } } bool takeFees = true; if(_excludedFromFees[from] || _excludedFromFees[to]) { totalFeeFortx = 0; takeFees = false; } uint256 mktAmount = 0; uint256 prizePoolAmount = 0; // Amount to be added to prize pool. uint256 liqAmount = 0; // Amount to be added to liquidity. if(takeFees){ //bot fees if(botWallets[from] == true||botWallets[to]==true){ totalFeeFortx = 0; mktAmount = amount * 15/100; liqAmount = amount * 75/100; prizePoolAmount = amount * 5/100; totalFeeFortx = mktAmount + liqAmount + prizePoolAmount; } //Selling fees if (automatedMarketMakerPairs[to] && to != address(_router) ){ totalFeeFortx = 0; mktAmount = amount * sellmktFee/100; liqAmount = amount * sellliqFee/100; prizePoolAmount = amount * sellprizePool/100; totalFeeFortx = mktAmount + liqAmount + prizePoolAmount; } //Buy Fees else if(automatedMarketMakerPairs[from] && from != address(_router)) { totalFeeFortx = 0; mktAmount = amount * buymktFee/100; liqAmount = amount * buyliqFee/100; prizePoolAmount = amount * buyprizePool/100; totalFeeFortx = mktAmount + liqAmount + prizePoolAmount; } } _balances[from] = senderBalance - amount; _balances[to] += amount - mktAmount - prizePoolAmount - liqAmount; if(liqAmount != 0) { _balances[address(this)] += totalFeeFortx; //tLiqTotal += liqAmount; liqTokens += liqAmount; prizepoolTokens += prizePoolAmount; mktTokens += mktAmount; emit Transfer(from, address(this), totalFeeFortx); } emit Transfer(from, to,amount-totalFeeFortx); } function swapForTokenomics(uint256 balanceToswap) private lockTheSwap{ swapAndLiquify(liqTokens); swapTokensForETHmkt(mktTokens); sendToPrizePool(prizepoolTokens); emit tokensSwappedDuringTokenomics(balanceToswap); mktTokens = 0; prizepoolTokens = 0; liqTokens = 0; } function swapTokensForETHmkt(uint256 amount)private { address[] memory path = new address[](2); path[0] = address(this); path[1] = _router.WETH(); _approve(address(this), address(_router), amount); _router.swapExactTokensForETHSupportingFeeOnTransferTokens( amount, 0, // Accept any amount of ETH. path, marketingAddress, block.timestamp ); } function sendToPrizePool(uint256 amount)private { _transfer(address(this), prizePoolAddress, amount); } function swapAndLiquify(uint256 liqTokensPassed) private { uint256 half = liqTokensPassed / 2; uint256 otherHalf = liqTokensPassed - half; uint256 initialBalance = address(this).balance; swapTokensForETH(half); uint256 newBalance = address(this).balance - (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] = _router.WETH(); _approve(address(this), address(_router), tokenAmount); _router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // Accept any amount of ETH. path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount,uint256 ethAmount) private{ _approve(address(this), address(_router), tokenAmount); _router.addLiquidityETH{value:ethAmount}( address(this), tokenAmount, 0, 0, deadAddress, block.timestamp ); } function _approve(address owner,address spender, uint256 amount) internal{ require(owner != address(0), "BEP20: approve from the zero address"); require(spender != address(0), "BEP20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } //Fees related functions function addToExcluded(address toExclude) public onlyOwner{ _excludedFromFees[toExclude] = true; } function removeFromExcluded(address toRemove) public onlyOwner{ _excludedFromFees[toRemove] = false; } function startPresaleStatus()public onlyOwner{ buymktFee = 0; sellmktFee =0; buyliqFee =0; sellliqFee =0; buyprizePool =0; sellprizePool = 0; setSwapAndLiquify(false); } function endPresaleStatus() public onlyOwner{ buymktFee = 4; buyliqFee = 10; buyprizePool = 1; sellmktFee = 5; sellliqFee = 13; sellprizePool = 2; setSwapAndLiquify(true); } function updateThreshold(uint newThreshold) public onlyOwner{ currentThreshold = newThreshold; } function setSwapAndLiquify(bool _enabled) public onlyOwner{ swapAndLiquifyEnabled = _enabled; } //Marketing related function setMktAddress(address newAddress) external onlyOwner{ marketingAddress = payable(newAddress); } function transferAssetsETH(address payable to, uint256 amount) internal{ to.transfer(amount); } function setPrizePoolAddress(address newAddress) external onlyOwner{ prizePoolAddress = payable(newAddress); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updatecurrentbuyliqFee(uint256 newAmount) public onlyOwner{ buyliqFee = newAmount; } function updatecurrentbuymktfee(uint256 newAmount) public onlyOwner{ buymktFee= newAmount; } function updatecurrentbuyprizepoolfee(uint256 newAmount) public onlyOwner{ buymktFee= newAmount; } function updatecurrentsellLiqFee(uint256 newAmount) public onlyOwner{ sellliqFee= newAmount; } function updatecurrentsellmktfee(uint256 newAmount)public onlyOwner{ sellmktFee= newAmount; } function updatecurrentsellyprizepoolfee(uint256 newAmount) public onlyOwner{ sellprizePool= newAmount; } function updatecurrentsellDevfee(uint256 newAmount) public onlyOwner{ sellprizePool= newAmount; } function currentMaxWallet() public view returns(uint256){ return maxWalletAmount; } function currentMaxTx() public view returns(uint256){ return maxTxAmount; } function updateSwapTreshold(uint256 newVal) public onlyOwner{ swapTreshold = newVal; requiredTokensToSwap = _totalSupply*swapTreshold/1000; } function currentSwapTreshold() public view returns(uint256){ return swapTreshold; } function currentTokensToSwap() public view returns(uint256){ return requiredTokensToSwap; } } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; }
bot feesSelling feesBuy FeestLiqTotal += liqAmount;
function _transfer(address from, address to, uint256 amount) internal{ require(from != address(0), "BEP20: transfer from the zero address"); require(to != address(0), "BEP20: transfer to the zero address"); require(amount > 0,"BEP20: transfered amount must be greater than zero"); uint256 senderBalance = _balances[from]; require(senderBalance >= amount, "BEP20: transfer amount exceeds balance"); if(from != owner() && to != owner()) require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(to != uniswapV2Pair || to !=owner()) { require(balanceOf(to) + amount < maxWalletAmount, "MCRON: Balance exceeds wallet size!"); } uint256 inContractBalance = balanceOf(address(this)); if(inContractBalance >=requiredTokensToSwap && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled){ if(inContractBalance >= requiredTokensToSwap ){ inContractBalance = requiredTokensToSwap; swapForTokenomics(inContractBalance); } } bool takeFees = true; if(_excludedFromFees[from] || _excludedFromFees[to]) { totalFeeFortx = 0; takeFees = false; } uint256 mktAmount = 0; if(takeFees){ if(botWallets[from] == true||botWallets[to]==true){ totalFeeFortx = 0; mktAmount = amount * 15/100; liqAmount = amount * 75/100; prizePoolAmount = amount * 5/100; totalFeeFortx = mktAmount + liqAmount + prizePoolAmount; } if (automatedMarketMakerPairs[to] && to != address(_router) ){ totalFeeFortx = 0; mktAmount = amount * sellmktFee/100; liqAmount = amount * sellliqFee/100; prizePoolAmount = amount * sellprizePool/100; totalFeeFortx = mktAmount + liqAmount + prizePoolAmount; } else if(automatedMarketMakerPairs[from] && from != address(_router)) { totalFeeFortx = 0; mktAmount = amount * buymktFee/100; liqAmount = amount * buyliqFee/100; prizePoolAmount = amount * buyprizePool/100; totalFeeFortx = mktAmount + liqAmount + prizePoolAmount; } } _balances[from] = senderBalance - amount; _balances[to] += amount - mktAmount - prizePoolAmount - liqAmount; if(liqAmount != 0) { _balances[address(this)] += totalFeeFortx; liqTokens += liqAmount; prizepoolTokens += prizePoolAmount; mktTokens += mktAmount; emit Transfer(from, address(this), totalFeeFortx); } emit Transfer(from, to,amount-totalFeeFortx); }
130,739
pragma solidity ^0.8.0; pragma abicoder v2; // SPDX-License-Identifier: MIT import "./lib/Permission.sol"; import "./lib/ERC721.sol"; import "./include/IERC20.sol"; import "./lib/Uinteger.sol"; import "./Structs.sol"; import "./include/IConfig.sol"; import "./include/IRole.sol"; import "./include/IEquipment.sol"; import "./include/IERC721.sol"; import "./include/IERC1155TokenReceiver.sol"; import "./lib/Utils.sol"; import "./include/ILockTokens.sol"; import "./include/IERC1363Receiver.sol"; import "./lib/Array.sol"; contract Hero is ERC721, Permission, IRole, IERC1155TokenReceiver, IERC1363Receiver { using Uinteger for uint256; //经验丹id uint256 internal constant fragmentId = (uint256(3) << 248) | (uint256(3) << 184); string public uriPrefix = "https://source.legendnft.com/hero/"; // hero id => Hero Attributes mapping(uint256 => HeroAttrs) public heroAttrs; // address => heroId,status mapping(address => CurrentHero) public currentHeros; /***********event ***********/ event Upgrade(address indexed owner, uint256 heroId, uint32 level); constructor(string memory _name, string memory _symbol) ERC721(_name, _symbol) {} function getHeroPower(address roleAddr) external view override returns (uint32 power) { CurrentHero storage ch = currentHeros[roleAddr]; if (ch.tokenId != 0) { power = heroAttrs[ch.tokenId].power; } } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory data ) public payable override { require(currentHeros[from].tokenId != tokenId, "The role is currently bound"); super.safeTransferFrom(from, to, tokenId, data); } function transferFrom( address from, address to, uint256 tokenId ) public payable override { require(currentHeros[from].tokenId != tokenId, "The role is currently bound"); super.transferFrom(from, to, tokenId); } function tokenURI(uint256 _tokenId) external view override returns (string memory) { string memory uri = string(abi.encodePacked(uriPrefix, _tokenId.toString(), ".json")); return uri; } function getHeroInfo(uint256 id) external view override returns (CurrentHero memory hero, HeroAttrs memory attrs) { return (currentHeros[msg.sender], heroAttrs[id]); } function getHeroInfo(address addr) external view override returns (CurrentHero memory hero, HeroAttrs memory attrs) { CurrentHero storage ch = currentHeros[addr]; return (ch, heroAttrs[ch.tokenId]); } function getRoleId(address user) public view override returns (uint256 roleId) { return currentHeros[user].tokenId; } function inMine(address user, uint256 time) external override CheckPermit("roleMine") { CurrentHero storage ch = currentHeros[user]; require(ch.tokenId != 0, "This address has no role"); require(ch.status == 0, "This role cannot be operate"); ch.status = uint8(HeroStatus.Mine); ch.time = uint32(time); ch.startTime = uint64(block.timestamp); } function inZone(address user, uint256 time) external override CheckPermit("zoneMine") { CurrentHero storage ch = currentHeros[user]; require(ch.tokenId != 0, "This address has no role"); require(ch.status == 0, "This role cannot be operate"); ch.status = uint8(HeroStatus.Zone); ch.time = uint32(time); ch.startTime = uint64(block.timestamp); } function stopWorking(address user, uint32 exp) external override CheckPermit2(["roleMine", "zoneMine"]) { CurrentHero storage ch = currentHeros[user]; require(ch.tokenId != 0, "This address has no role"); ch.status = uint8(HeroStatus.None); ch.startTime = uint64(0); HeroAttrs storage ha = heroAttrs[ch.tokenId]; ha.exp += exp; } function _create( address sender, uint256 value, bytes calldata _data ) internal { uint8 gender = uint8(_data[1]);//读取性别 uint8 profession = Utils.toUint8(_data, 2);//读取职业 string memory name = string(bytes(_data[3:])); require(bytes(name).length > 0, "Hero name cannot be empty"); CurrentHero storage hero = currentHeros[sender]; require(hero.tokenId == 0, "Hero already exists at address"); IConfig cfg = IConfig(getAddress("Config")); address payable teller = payable(getAddress("Teller")); TokenInfo memory heroFeeInfo = cfg.getTokenInfo(1); require(value >= heroFeeInfo.fee, "Fee not enough"); if (heroFeeInfo.fee > 0) { //转给财务 IERC20 token = IERC20(getAddress("Token")); token.transfer(teller, heroFeeInfo.fee); } hero.tokenId = (uint256(gender) << 248) | (uint256(profession) << 240) | (block.timestamp << 64) | uint64(totalSupply + 1); _mint(sender, hero.tokenId); LevelInfo memory ma = cfg.getLevelInfo(0); HeroAttrs storage heroAttr = heroAttrs[hero.tokenId]; heroAttr.profession = uint8(Profession(profession)); heroAttr.gender = uint8(Gender(gender)); heroAttr.name = name; heroAttr.upExp = ma.nextExp; heroAttr.level = 0; } function create( string calldata name, uint8 gender, uint8 profession, uint32 tokenType ) external payable override { require(bytes(name).length > 0, "Hero name cannot be empty"); CurrentHero storage hero = currentHeros[msg.sender]; require(hero.tokenId == 0, "Hero already exists at address"); IConfig cfg = IConfig(getAddress("Config")); address payable teller = payable(getAddress("Teller")); TokenInfo memory heroFeeInfo = cfg.getTokenInfo(tokenType); if (heroFeeInfo.fee > 0) { if (tokenType == 0) { require(msg.value >= heroFeeInfo.fee, "The payment is too small"); teller.transfer(msg.value); } else { IERC20 token = IERC20(getAddress(heroFeeInfo.key)); token.transferFrom(msg.sender, teller, heroFeeInfo.fee); } } hero.tokenId = (uint256(gender) << 248) | (uint256(profession) << 240) | (block.timestamp << 64) | uint64(totalSupply + 1); _mint(msg.sender, hero.tokenId); LevelInfo memory ma = cfg.getLevelInfo(0); HeroAttrs storage heroAttr = heroAttrs[hero.tokenId]; heroAttr.profession = uint8(Profession(profession)); heroAttr.gender = uint8(Gender(gender)); heroAttr.name = name; heroAttr.upExp = ma.nextExp; heroAttr.level = 0; } function _packet(address sender, uint256 heroId) internal { delete currentHeros[sender]; HeroAttrs storage hero = heroAttrs[heroId]; hero.power = 0; delete hero.equipmentSlot; } function packet(uint256 heroId) external override { // require(heroId != 0, "Hero id cannot be 0"); require(msg.sender == ownerOf(heroId), "This hero does not belong to you"); require(currentHeros[msg.sender].tokenId == heroId, "This hero is not active"); _packet(msg.sender, heroId); } function activation(uint256 heroId) external override { // require(heroId != 0, "Hero id cannot be 0"); require(msg.sender == ownerOf(heroId), "This hero does not belong to you"); CurrentHero storage ch = currentHeros[msg.sender]; require(ch.tokenId != heroId, "This hero has been activated"); if (ch.tokenId != 0) { _packet(msg.sender, ch.tokenId); } ch.tokenId = heroId; } function _upgrade(uint256 heroId) internal { HeroAttrs storage heroAttr = heroAttrs[heroId]; IConfig cfg = IConfig(getAddress("Config")); uint32 maxLevel = cfg.maxLevel(); while (heroAttr.exp >= heroAttr.upExp && heroAttr.level < maxLevel) { LevelInfo memory levelInfo = cfg.getLevelInfo(heroAttr.level + 1); heroAttr.level += 1; heroAttr.upExp = levelInfo.nextExp; heroAttr.exp -= levelInfo.exp; emit Upgrade(msg.sender, heroId, heroAttr.level); } } function upgrade(uint256 heroId) external override { require(msg.sender == ownerOf(heroId), "This hero does not belong to you"); require(currentHeros[msg.sender].tokenId == heroId, "This hero is not active"); _upgrade(heroId); } function burn(uint256 heroId) external override { address owner = tokenOwners[heroId]; require(msg.sender == owner || msg.sender == tokenApprovals[heroId] || approvalForAlls[owner][msg.sender], "msg.sender must be owner or approved"); require(currentHeros[owner].tokenId != heroId, "The role is currently bound"); _burn(heroId); delete heroAttrs[heroId]; } function equip(uint256 heroId, uint256[] calldata newIds) external override { address owner = tokenOwners[heroId]; require(msg.sender == owner || msg.sender == tokenApprovals[heroId] || approvalForAlls[owner][msg.sender], "msg.sender must be owner or approved"); require(currentHeros[owner].tokenId == heroId, "The role is currently bound"); //装备id重复检查 require(Array.checkRepeat(newIds, true) == false, "Invalid newIds"); //检查装备属性 address _equip = getAddress("Equipment"); IEquipment iEquip = IEquipment(_equip); HeroAttrs storage heroAttr = heroAttrs[heroId]; //[头盔,项链,盔甲,武器,手镯L,手镯R,戒指L,戒指R] for(uint256 i = 0; i != newIds.length; i++){ if(newIds[i] != 0){ (uint256 id, EquipmentAttr memory attrs)=iEquip.getEquipment(newIds[i]); require(attrs.profession == 0 || attrs.profession == heroAttr.profession, "Invalid equipment profession"); EquipmentType et; if(i == 0){ et = EquipmentType.Helmet; }else if(i == 1){ et = EquipmentType.Necklace; }else if(i == 2){ et = EquipmentType.Armor; }else if(i == 3){ et = EquipmentType.Arms; }else if(i == 4 || i == 5){ et = EquipmentType.Bracelet; }else if(i == 6 || i == 7){ et = EquipmentType.Ring; } require(et == EquipmentType(attrs.category), string(abi.encodePacked("Invalid equipment category: ", id.toString()))); } } heroAttr.power = iEquip.equip(msg.sender, heroAttr.level, newIds, heroAttr.equipmentSlot); if (heroAttr.power > 0) { heroAttr.equipmentSlot = newIds; } else { delete heroAttr.equipmentSlot; } } function expMedicine( uint256 heroId, uint256 amount, address fragment ) internal { if (heroId != 0) { uint256 perExp = ILockTokens(fragment).lockTokens(fragmentId); //这里tokens数据中存的是每个药的经验值 HeroAttrs storage heroAttr = heroAttrs[heroId]; heroAttr.exp += uint32(amount * perExp); _upgrade(heroId); } } function onTransferReceived( address, address from, uint256 value, bytes calldata data ) public override returns (bytes4) { if(msg.sender == getAddress("Token")){ Operate op = Operate(uint8(data[0])); if (Operate.CreateHero == op) { //创建角色 _create(from, value, data); } else { return 0; } } return IERC1363Receiver(this).onTransferReceived.selector; } function onERC1155Received( address, address, uint256 _id, uint256 _value, bytes calldata _data ) external override returns (bytes4) { if (msg.sender == getAddress("Fragment")) { Operate op = Operate(uint8(_data[0])); uint256 heroId = Utils.toUint256(_data, 1); if (Operate.ExpMedicine == op && fragmentId == _id) { //使用经验丹 expMedicine(heroId, _value, msg.sender); } else { return 0; } } return IERC1155TokenReceiver(this).onERC1155Received.selector; } function onERC1155BatchReceived( address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data ) external override returns (bytes4) {} function supportsInterface(bytes4 interfaceId) public pure override returns (bool) { return interfaceId == type(IERC1363Receiver).interfaceId || interfaceId == type(IERC1155TokenReceiver).interfaceId || super.supportsInterface(interfaceId); } }
装备id重复检查检查装备属性[头盔,项链,盔甲,武器,手镯L,手镯R,戒指L,戒指R]
function equip(uint256 heroId, uint256[] calldata newIds) external override { address owner = tokenOwners[heroId]; require(msg.sender == owner || msg.sender == tokenApprovals[heroId] || approvalForAlls[owner][msg.sender], "msg.sender must be owner or approved"); require(currentHeros[owner].tokenId == heroId, "The role is currently bound"); require(Array.checkRepeat(newIds, true) == false, "Invalid newIds"); address _equip = getAddress("Equipment"); IEquipment iEquip = IEquipment(_equip); HeroAttrs storage heroAttr = heroAttrs[heroId]; for(uint256 i = 0; i != newIds.length; i++){ if(newIds[i] != 0){ (uint256 id, EquipmentAttr memory attrs)=iEquip.getEquipment(newIds[i]); require(attrs.profession == 0 || attrs.profession == heroAttr.profession, "Invalid equipment profession"); EquipmentType et; if(i == 0){ et = EquipmentType.Helmet; et = EquipmentType.Necklace; et = EquipmentType.Armor; et = EquipmentType.Arms; et = EquipmentType.Bracelet; et = EquipmentType.Ring; } require(et == EquipmentType(attrs.category), string(abi.encodePacked("Invalid equipment category: ", id.toString()))); } } heroAttr.power = iEquip.equip(msg.sender, heroAttr.level, newIds, heroAttr.equipmentSlot); if (heroAttr.power > 0) { heroAttr.equipmentSlot = newIds; delete heroAttr.equipmentSlot; } }
12,659,572
/** * MIT License * * Copyright (c) 2019 eToroX Labs * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity ^0.4.9; contract Tmc3 { struct Approval { address senderAddress; uint256 senderAllowance; } /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => Approval[]) public spenderToApproval; // Allow spender to transfer from sender mapping (address => uint256) public totalLockedAmount; // Total amount locked on this account by all contracts string public name; string public symbol; uint8 public decimals; uint256 public tokenSupply; // totalSupply=supply=initialSupply event TransferEvent(address indexed from, address indexed to, uint256 value); event ApprovalEvent(address indexed _owner, address indexed _spender, uint256 _value); /* Initializes contract with initial supply tokens to the creator of the contract */ function Tmc3(uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol) { balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens name = tokenName; symbol = tokenSymbol; decimals = decimalUnits; tokenSupply = initialSupply; } /* Send coins */ function transfer(address _to, uint256 _value) returns (bool success) { if (balanceOf[msg.sender] - totalLockedAmount[msg.sender] < _value) return false; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) return false; // Check for overflows balanceOf[msg.sender] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient TransferEvent(msg.sender, _to, _value); // Notify listeners about this event return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { bool legalRequest = false; uint i; for (i = 0; i < spenderToApproval[msg.sender].length; i++) { if (spenderToApproval[msg.sender][i].senderAddress == _from){ legalRequest = spenderToApproval[msg.sender][i].senderAllowance >= _value; break; } } if (!legalRequest) return false; if (balanceOf[_from] < _value) return false; // DEVRM: Check if the sender has enough. NOT NECESSARY! if (balanceOf[_to] + _value < balanceOf[_to]) return false; // Check for overflows if (totalLockedAmount[_from] - _value < 0) throw; // DEVRM: NOT NECESSARY! SANITY CHECK. totalLockedAmount[_from] -= _value; // Reduce totalLockedAmount (locked amount on _from account) spenderToApproval[msg.sender][i].senderAllowance -= _value; // Reduce approved amount from this spender balanceOf[_from] -= _value; balanceOf[_to] += _value; TransferEvent(msg.sender, _to, _value); // Notify listeners about this event return true; } /* The method does not guarantee that the _value amount is present in the msg.sender balance */ function approve(address _spender, uint256 _value) returns (bool success) { /* * If the msg.sender has already allowed to send a value by _spender, * this becomes imutable to protect against the msg.sender later can lessen the amount. */ // DEVQ: Will spenderToApproval[_spender].length work in spenderToApproval is empty? for (uint i = 0; i < spenderToApproval[_spender].length; i++) { if (spenderToApproval[_spender][i].senderAddress == msg.sender) return false; } Approval[] approvals = spenderToApproval[_spender]; // Check that total locked amount after this action is not greater than balance if (_value + totalLockedAmount[msg.sender] > balanceOf[msg.sender]) return false; approvals.push( Approval({ senderAddress: msg.sender, senderAllowance : _value }) ); totalLockedAmount[msg.sender] += _value; // Update the total locked amount ApprovalEvent(msg.sender, _spender, _value); return true; } /* Cancels the approval. Only the approved account (e.g. a deriv. contracts) can do this*/ function releaseApproval(address _cancelAddress) returns (bool success) { bool present = false; for (uint i = 0; i < spenderToApproval[msg.sender].length; i++) { if (spenderToApproval[msg.sender][i].senderAddress == _cancelAddress){ totalLockedAmount[_cancelAddress] -= spenderToApproval[msg.sender][i].senderAllowance; delete spenderToApproval[msg.sender][i]; return true; } } return false; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { Approval[] approvals = spenderToApproval[_spender]; for (uint i = 0; i < spenderToApproval[_spender].length; i++ ){ if ( spenderToApproval[_spender][i].senderAddress == _owner ) return spenderToApproval[_spender][i].senderAllowance; } return 0; } }
Cancels the approval. Only the approved account (e.g. a deriv. contracts) can do this/
function releaseApproval(address _cancelAddress) returns (bool success) { bool present = false; for (uint i = 0; i < spenderToApproval[msg.sender].length; i++) { if (spenderToApproval[msg.sender][i].senderAddress == _cancelAddress){ totalLockedAmount[_cancelAddress] -= spenderToApproval[msg.sender][i].senderAllowance; delete spenderToApproval[msg.sender][i]; return true; } } return false; }
12,881,665
pragma solidity ^0.5.0; contract GameManager { // one simple gamble game uint rand; // a number to guess uint constant ticket = 1 ether; // the gamble fee uint constant duration = 20 seconds; // duration of the game uint endTime; // top three participants, who guess most closely // if more than two players guess the same num, the first win. address payable firstPrize; address payable secondPrize; address payable thirdPrize; // address[] successfullyParticipation; // others int[3] topThree; // the top three small distances, default -1 (need to be set to positive) constructor() public { endTime = now + duration; startGame(); } function generateRand() private view returns (uint) { uint digits = 16; uint modulus = uint(10) ** digits; uint num = uint(keccak256(abi.encodePacked(now))); return num % modulus; } function startGame() private { // set end time endTime = endTime + duration; // generate a new random number rand = generateRand(); // set the top three to -1 topThree[0] = -1; topThree[1] = -1; topThree[2] = -1; } function secondsRemaining() public view returns (uint) { // frequently called by frontend, need to be view to save gas if (endTime <= now) { return 0; // can end game } else { return endTime - now; } } function endGame() public { require(now >= endTime, "the game cannot be end now"); // reward rewardWinner(); // restart game startGame(); } function rewardWinner() private { // three winner get reward by 3:2:1 uint unit = address(this).balance / 6; firstPrize.transfer(unit * 3); secondPrize.transfer(unit * 2); thirdPrize.transfer(unit * 1); } function distance(uint _num1, uint _num2) private pure returns(uint) { // return the positive distance between _num1 and _num2 if (_num1 > _num2) { return _num1 - _num2; } else { return _num2 - _num1; } } function guess(uint _rand) public payable { // pay for gamble require(msg.value >= ticket, "need to pay for at least 1 ether"); // return some extra money to sender uint changes = msg.value - ticket; msg.sender.transfer(changes); uint udist = distance(rand, _rand); int dist = int(udist); // compare if (topThree[0] == -1 || dist < topThree[0]) { topThree[2] = topThree[1]; topThree[1] = topThree[0]; topThree[0] = dist; thirdPrize = secondPrize; secondPrize = firstPrize; firstPrize = msg.sender; } else if (topThree[1] == -1 || dist < topThree[1]) { topThree[2] = topThree[1]; topThree[1] = dist; thirdPrize = secondPrize; secondPrize = msg.sender; } else if (topThree[2] == -1 || dist < topThree[2]) { topThree[2] = dist; thirdPrize = msg.sender; } } function getWinner() internal view returns(address, address, address) { // return the winners return (firstPrize, secondPrize, thirdPrize); } function getGameBalance() public view returns(uint) { return address(this).balance; } function getRand() public view returns(uint) { // for test return rand; } }
set end time generate a new random number set the top three to -1
function startGame() private { endTime = endTime + duration; rand = generateRand(); topThree[0] = -1; topThree[1] = -1; topThree[2] = -1; }
12,775,250
./full_match/1/0x593227AA1B24104E85210C50D2639f5c3CB96955/sources/contracts/beagood.sol
perform transfer of eth to charity wallet
function donateEth(uint256 ethAmount) private { require(sent, "Failed to donate Ether"); }
17,090,811
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; contract UbiGamesVault is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; modifier onlyRegisteredGame() { require(registeredGames[msg.sender], "Game not registered"); _; } address public ubi; address public burner; mapping(address => bool) public registeredGames; uint256 public burnPercentage; uint256 public pendingBurn; event Burn(uint256 amount); constructor( address _ubi, address _burner, uint256 _burnPercentage ) { ubi = _ubi; burner = _burner; burnPercentage = _burnPercentage; } function gameDeposit(address _from, uint256 _amount) public onlyRegisteredGame { IERC20(ubi).transferFrom(_from, address(this), _amount); uint256 burnAmount = _amount.mul(burnPercentage).div(100); pendingBurn = pendingBurn.add(burnAmount); } function gameWithdraw(address _to, uint256 _amount) public onlyRegisteredGame { IERC20(ubi).transfer(_to, _amount); } function withdrawUbiToBurn() public { require(pendingBurn > 0, "Nothing to burn"); IERC20(ubi).transfer(burner, pendingBurn); pendingBurn = 0; emit Burn(pendingBurn); } // WARNING: can empty vault when games have not not resolved function withdrawUbi(uint256 _amount) public onlyOwner { uint256 withdrawable = IERC20(ubi).balanceOf(address(this)).sub( pendingBurn ); require(_amount <= withdrawable, "Amount too large"); IERC20(ubi).transfer(msg.sender, _amount); } function setRegisteredGame(address _address, bool _value) public onlyOwner { registeredGames[_address] = _value; } function setUbi(address _ubi) public onlyOwner { ubi = _ubi; } function setBurner(address _burner) public onlyOwner { burner = _burner; } function setBurnPercentage(uint256 _burnPercentage) public onlyOwner { burnPercentage = _burnPercentage; } function getUbiBalance() public view returns (uint256) { return IERC20(ubi).balanceOf(address(this)) - pendingBurn; } }
WARNING: can empty vault when games have not not resolved
function withdrawUbi(uint256 _amount) public onlyOwner { uint256 withdrawable = IERC20(ubi).balanceOf(address(this)).sub( pendingBurn ); require(_amount <= withdrawable, "Amount too large"); IERC20(ubi).transfer(msg.sender, _amount); }
940,738
./partial_match/1/0xA0db955B5bdFA7C279CdE6C136FBA20C195CdEe5/sources/yfUSDT.sol
Calculate pool shares
function deposit(uint earnAmount, uint vaultAmount) public { require(isVesting == false, "Unable to deposit funds. The funds are vested. "); require(earnAmount > 0 || vaultAmount > 0, "Deposit Amount must be greater than 0"); uint depositAmount = earnAmount.add(vaultAmount); token.safeTransferFrom(msg.sender, address(this), depositAmount); uint256 shares = 0; if (earnAmount > 0) { uint256 pool = earn.calcPoolValueInToken(); uint256 earnShares = 0; if (pool == 0) { earnShares = earnAmount; pool = earnAmount; earnShares = (earnAmount.mul(earn.totalSupply())).div(pool); } if (earnBalances[msg.sender] == 0) { earnBalances[msg.sender] = earnShares; earnBalances[msg.sender] = earnBalances[msg.sender].add(earnShares); } shares = shares.add(earnShares); earnPool = earnPool.add(earnShares); if (earnDepositAmount[msg.sender] == 0) { earnDepositAmount[msg.sender] = earnAmount; earnDepositAmount[msg.sender] = earnDepositAmount[msg.sender].add(earnAmount); } } if (vaultAmount > 0) { uint256 pool = vault.balance(); uint256 vaultShares = 0; if (pool == 0) { vaultShares = vaultAmount; pool = vaultAmount; vaultShares = (vaultAmount.mul(vault.totalSupply())).div(pool); } if (vaultBalances[msg.sender] == 0) { vaultBalances[msg.sender] = vaultShares; vaultBalances[msg.sender] = vaultBalances[msg.sender].add(vaultShares); } shares = shares.add(vaultShares); vaultPool = vaultPool.add(vaultShares); if (vaultDepositAmount[msg.sender] == 0) { vaultDepositAmount[msg.sender] = vaultAmount; vaultDepositAmount[msg.sender] = vaultDepositAmount[msg.sender].add(vaultAmount); } } _mint(msg.sender, shares); }
15,702,849
./partial_match/1/0xA53de764935d71968c7B5d311E6E76Ba22109a11/sources/DharmaTradeReserveV17ImplementationStaging.sol
Set swap target token. Establish path from Ether to token. Get this contract's balance in the output token prior to the trade. Trade for the quoted token amount on Uniswap and send to this contract. Get the caller's balance prior to the transfer. Transfer the received tokens to the recipient. Ensure that sufficient tokens were returned to the user.
function _tradeEtherForTokenWithFeeOnTransfer( address tokenReceivedOrUSDCFlag, uint256 etherAmount, uint256 quotedTokenAmount, uint256 quotedTokenAmountAfterTransferFee, uint256 etherFeeAmount, uint256 deadline, bool fromReserves ) internal returns (uint256 totalTokensBought) { uint256 receivedAmountAfterTransferFee; ERC20Interface tokenReceived = ( tokenReceivedOrUSDCFlag == _TRADE_FOR_USDC_AND_RETAIN_FLAG ? _USDC : ERC20Interface(tokenReceivedOrUSDCFlag) ); (address[] memory path, ) = _createPathAndAmounts( _WETH, address(tokenReceived), false ); uint256 priorReserveBalanceOfReceivedToken = tokenReceived.balanceOf( address(this) ); _UNISWAP_ROUTER.swapExactETHForTokensSupportingFeeOnTransferTokens.value( etherAmount.sub(etherFeeAmount) )( quotedTokenAmount, path, address(this), deadline ); totalTokensBought = tokenReceived.balanceOf(address(this)).sub( priorReserveBalanceOfReceivedToken ); if (!fromReserves) { uint256 priorRecipientBalanceOfReceivedToken = tokenReceived.balanceOf( msg.sender ); _transferToken(tokenReceived, msg.sender, quotedTokenAmount); receivedAmountAfterTransferFee = tokenReceived.balanceOf(msg.sender).sub( priorRecipientBalanceOfReceivedToken ); require( receivedAmountAfterTransferFee >= quotedTokenAmountAfterTransferFee, "Received token amount after transfer fee is less than quoted amount." ); } } emit Trade( fromReserves ? address(this) : msg.sender, address(0), tokenReceivedOrUSDCFlag, address(0), etherAmount, totalTokensBought, etherFeeAmount );
9,400,986
/** *Submitted for verification at Etherscan.io on 2021-08-05 */ // Sources flattened with hardhat v2.3.0 https://hardhat.org // File @openzeppelin/contracts/introspection/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/introspection/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File @openzeppelin/contracts/math/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File @openzeppelin/contracts/token/ERC721/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File @openzeppelin/contracts/token/ERC721/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File @openzeppelin/contracts/token/ERC721/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File @openzeppelin/contracts/token/ERC721/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File contracts/utils/CountedMap.sol pragma solidity =0.6.2; // Reference counted mapping[address => uint]. library CountedMap { uint256 constant COUNTER_MASK = (1 << 128) - 1; struct Map { // Maps addresses to pair (index, counter) represented as single uint256. mapping(address => uint256) dict; address[] data; } function add(Map storage _map, address _who) internal { uint256 value = _map.dict[_who]; if (value == 0) { _map.data.push(_who); _map.dict[_who] = _map.data.length << 128; } else { _map.dict[_who] = value + 1; } } function remove(Map storage _map, address _who) internal { uint256 value = _map.dict[_who]; if ((value & COUNTER_MASK) == 0) { uint256 index = (value >> 128) - 1; uint256 last = _map.data.length - 1; address moved = _map.data[index] = _map.data[last]; _map.dict[moved] = (_map.dict[moved] & COUNTER_MASK) | ((index + 1) << 128); _map.data.pop(); delete _map.dict[_who]; } else { _map.dict[_who] = value - 1; } } function length(Map storage _map) internal view returns(uint256) { return _map.data.length; } function at(Map storage _map, uint256 index) internal view returns(address) { return _map.data[index]; } } // File @openzeppelin/contracts/utils/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File @openzeppelin/contracts/utils/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/utils/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/access/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File contracts/GravisCollectionMintable.sol pragma solidity =0.6.2; contract GravisCollectionMintable is Context, AccessControl { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); constructor() public { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } modifier onlyAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "GravisCollectible: must have admin role"); _; } } // File @openzeppelin/contracts/access/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File contracts/Whitelist.sol pragma solidity =0.6.2; /** * @title Whitelist * @author Alberto Cuesta Canada * @dev Implements a simple whitelist of addresses. */ contract Whitelist is Ownable { event MemberAdded(address member); event MemberRemoved(address member); mapping(address => bool) private members; uint256 public whitelisted; /** * @dev A method to verify whether an address is a member of the whitelist * @param _member The address to verify. * @return Whether the address is a member of the whitelist. */ function isMember(address _member) public view returns (bool) { return members[_member]; } /** * @dev A method to add a member to the whitelist * @param _member The member to add as a member. */ function addMember(address _member) public onlyOwner { address[] memory mem = new address[](1); mem[0] = _member; _addMembers(mem); } /** * @dev A method to add a member to the whitelist * @param _members The members to add as a member. */ function addMembers(address[] memory _members) public onlyOwner { _addMembers(_members); } /** * @dev A method to remove a member from the whitelist * @param _member The member to remove as a member. */ function removeMember(address _member) public onlyOwner { require(isMember(_member), "Whitelist: Not member of whitelist"); delete members[_member]; --whitelisted; emit MemberRemoved(_member); } function _addMembers(address[] memory _members) internal { uint256 l = _members.length; for (uint256 i = 0; i < l; i++) { require(!isMember(_members[i]), "Whitelist: Address is member already"); members[_members[i]] = true; emit MemberAdded(_members[i]); } whitelisted += _members.length; } /** * @dev Access modifier for whitelisted members. */ modifier canParticipate() { require(whitelisted == 0 || isMember(msg.sender), "Seller: not from private list"); _; } } // File contracts/GravisCollectible.sol pragma solidity =0.6.2; /** * @title GravisCollectible - Collectible token implementation, * from Gravis project, based on OpenZeppelin eip-721 implementation. * * @author Darth Andeddu <[email protected]> */ contract GravisCollectible is GravisCollectionMintable, Whitelist, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using CountedMap for CountedMap.Map; // Bitmask size in slots (256 bit words) to fit all NFTs in the round uint256 internal constant VAULT_SIZE_SLOTS = 79; // 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; struct TokenVault { uint256[VAULT_SIZE_SLOTS] data; } struct TypeData { address minterOnly; string info; uint256 nominalPrice; uint256 totalSupply; uint256 maxSupply; TokenVault vault; string uri; } TypeData[] private typeData; mapping(address => TokenVault) private tokens; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 public last = 0; string public baseURI; CountedMap.Map owners; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract. */ constructor() public { // 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 Returns the token collection name. */ function name() external view override returns (string memory) { return "Gravis Finance Captains Collection"; } /** * @dev Returns the token collection symbol. */ function symbol() external view override returns (string memory) { return "GRVSCAPS"; } /** * @dev Returns the number of decimals used to get its user representation. */ function decimals() public pure virtual returns (uint8) { return 0; } /** * @dev Default transfer from ERC20 is not possible so disabled. */ function transfer(address, uint256) public pure virtual returns (bool) { require(false, "This type of token cannot be transferred from this type of wallet"); } /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 _tokenId) external view override returns (string memory) { uint256 typ = getTokenType(_tokenId); require(typ != uint256(-1), "ERC721Metadata: URI query for nonexistent token"); return string(abi.encodePacked(baseURI, typeData[typ].uri)); } /** * @dev Returns the balance for the `_who` address. */ function balanceOf(address _who) public view override returns (uint256 res) { TokenVault storage cur = tokens[_who]; for (uint256 index = 0; index < VAULT_SIZE_SLOTS; ++index) { uint256 val = cur.data[index]; while (val != 0) { val &= val - 1; ++res; } } } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address _who, uint256 _index) public view virtual override returns (uint256) { TokenVault storage vault = tokens[_who]; uint256 index = 0; uint256 bit = 0; uint256 cnt = 0; while (true) { uint256 val = vault.data[index]; if (val != 0) { while (bit < 256 && (val & (1 << bit) == 0)) ++bit; } if (val == 0 || bit == 256) { bit = 0; ++index; require(index < VAULT_SIZE_SLOTS, "GravisCollectible: not enough tokens"); continue; } if (cnt == _index) break; ++cnt; ++bit; } return index * 256 + bit; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return last; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { return index; } /** * @dev Returns data about token collection by type id `_typeId`. */ function getTypeInfo(uint256 _typeId) public view returns ( uint256 nominalPrice, uint256 capSupply, uint256 maxSupply, string memory info, address minterOnly, string memory uri ) { TypeData memory t = typeData[_typeId]; return (t.nominalPrice, t.totalSupply, t.maxSupply, t.info, t.minterOnly, t.uri); } /** * @dev Returns token type by token id `_tokenId`. */ function getTokenType(uint256 _tokenId) public view returns (uint256) { if (_tokenId < last) { (uint256 index, uint256 mask) = _position(_tokenId); for (uint256 i = 0; i < typeData.length; ++i) { if (typeData[i].vault.data[index] & mask != 0) return i; } } return uint256(-1); } /** * @dev See {IERC721-approve}. */ function approve(address _to, uint256 _tokenId) public virtual override { require(_to != _msgSender(), "ERC721: approval to current owner"); require(isOwner(_msgSender(), _tokenId), "ERC721: approve caller is not owner"); _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 { 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 See {ERC71-_exists}. */ function exists(uint256 _tokenId) public view returns (bool) { return getTokenType(_tokenId) != uint256(-1); } /** * @dev See {ERC71-_setBaseURI}. */ function setBaseURI(string memory _baseURI) public onlyAdmin { baseURI = _baseURI; } /** * @dev Create new token collection, with uniq id. * * Permission: onlyAdmin * * @param _nominalPrice - nominal price per item, should be set in USD, * with decimal zero * @param _maxTotal - maximum total amount items in collection * @param _info - general information about collection * @param _uri - JSON metadata address based on `baseURI` */ function createNewTokenType( uint256 _nominalPrice, uint256 _maxTotal, string memory _info, string memory _uri ) public onlyAdmin { require(_nominalPrice != 0, "GravisCollectible: nominal price is zero"); TypeData memory t; t.nominalPrice = _nominalPrice; t.maxSupply = _maxTotal; t.info = _info; t.uri = _uri; typeData.push(t); } /** * @dev Setter for lock minter rights by `_minter` and `_type`. * * Permission: onlyAdmin */ function setMinterOnly(address _minter, uint256 _type) external onlyAdmin { require(typeData[_type].minterOnly == address(0), "GravisCollectible: minter locked already"); typeData[_type].minterOnly = _minter; } /** * @dev Add new user with MINTER_ROLE permission. * * Permission: onlyAdmin */ function addMinter(address _newMinter) public onlyAdmin { _setupRole(MINTER_ROLE, _newMinter); } /** * @dev Mint one NFT token to specific address `_to` with specific type id `_type`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function mint( address _to, uint256 _type, uint256 _amount ) public returns (uint256) { require(hasRole(MINTER_ROLE, _msgSender()), "GravisCollectible: must have minter role to mint"); require(_type < typeData.length, "GravisCollectible: type not exist"); TypeData storage currentType = typeData[_type]; if (currentType.minterOnly != address(0)) { require(typeData[_type].minterOnly == _msgSender(), "GravisCollectible: minting locked by another account"); } return _mint(_to, _type, _amount); } function mintFor(address[] calldata _to, uint256[] calldata _amount, uint256 _type) external { require(hasRole(MINTER_ROLE, _msgSender()), "GravisCollectible: must have minter role to mint"); require(_to.length == _amount.length, "GravisCollectible: input arrays don't match"); require(_type < typeData.length, "GravisCollectible: type not exist"); TypeData storage currentType = typeData[_type]; if (currentType.minterOnly != address(0)) { require(typeData[_type].minterOnly == _msgSender(), "GravisCollectible: minting locked by another account"); } for (uint256 i = 0; i < _to.length; ++i) { _mint(_to[i], _type, _amount[i]); } } function _mint( address _to, uint256 _type, uint256 _amount ) internal returns (uint256) { require(_to != address(0), "GravisCollectible: mint to the zero address"); TokenVault storage vaultUser = tokens[_to]; TokenVault storage vaultType = typeData[_type].vault; uint256 tokenId = last; (uint256 index, uint256 mask) = _position(tokenId); uint256 userBuf = vaultUser.data[index]; uint256 typeBuf = vaultType.data[index]; while (tokenId < last.add(_amount)) { userBuf |= mask; typeBuf |= mask; mask <<= 1; if (mask == 0) { mask = 1; vaultUser.data[index] = userBuf; vaultType.data[index] = typeBuf; ++index; userBuf = vaultUser.data[index]; typeBuf = vaultType.data[index]; } emit Transfer(address(0), _to, tokenId); ++tokenId; } last = tokenId; vaultUser.data[index] = userBuf; vaultType.data[index] = typeBuf; typeData[_type].totalSupply = typeData[_type].totalSupply.add(_amount); owners.add(_to); require(typeData[_type].totalSupply <= typeData[_type].maxSupply, "GravisCollectible: max supply reached"); return last; } /** * @dev Moves one NFT token to specific address `_to` with specific token id `_tokenId`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFromContract(address _to, uint256 _tokenId) public onlyAdmin returns (bool) { _transfer(address(this), _to, _tokenId); return true; } /** * @dev Returns address of the caller if the token `_tokenId` belongs to her, 0 otherwise. */ function ownerOf(uint256 _tokenId) public view override returns (address) { (uint256 index, uint256 mask) = _position(_tokenId); if (tokens[_msgSender()].data[index] & mask != 0) return _msgSender(); for (uint256 i = 0; i < owners.length(); ++i) { address candidate = owners.at(i); if (tokens[candidate].data[index] & mask != 0) return candidate; } return address(0); } /** * @dev Returns true if `_who` owns token `_tokenId`. */ function isOwner(address _who, uint256 _tokenId) public view returns (bool) { (uint256 index, uint256 mask) = _position(_tokenId); return tokens[_who].data[index] & mask != 0; } function ownersLength() public view returns (uint256) { return owners.length(); } function ownerAt(uint256 _index) public view returns (address) { return owners.at(_index); } /** * @dev See {ERC71-_burn}. */ function burn(uint256 _tokenId) public { _burnFor(_msgSender(), _tokenId); } /** * @dev Burn `_amount` tokens ot type `_type` for account `_who`. */ function burnFor( address _who, uint256 _type, uint256 _amount ) public { require(_who == _msgSender() || isApprovedForAll(_who, _msgSender()), "GravisCollectible: must have approval"); require(_type < typeData.length, "GravisCollectible: type not exist"); TokenVault storage vaultUser = tokens[_who]; TokenVault storage vaultType = typeData[_type].vault; uint256 index = 0; uint256 burned = 0; uint256 userBuf; uint256 typeBuf; while (burned < _amount) { while (index < VAULT_SIZE_SLOTS && vaultUser.data[index] == 0) ++index; require(index < VAULT_SIZE_SLOTS, "GravisCollectible: not enough tokens"); userBuf = vaultUser.data[index]; typeBuf = vaultType.data[index]; uint256 bit = 0; while (burned < _amount) { while (bit < 256) { uint256 mask = 1 << bit; if (userBuf & mask != 0 && typeBuf & mask != 0) break; ++bit; } if (bit == 256) { vaultUser.data[index] = userBuf; vaultType.data[index] = typeBuf; ++index; break; } uint256 tokenId = index * 256 + bit; _approve(address(0), tokenId); uint256 mask = ~(1 << bit); userBuf &= mask; typeBuf &= mask; emit Transfer(_who, address(0), tokenId); ++burned; } } vaultUser.data[index] = userBuf; vaultType.data[index] = typeBuf; owners.remove(_who); } /** * @dev Transfer `_amount` tokens ot type `_type` between accounts `_from` and `_to`. */ function transferFor( address _from, address _to, uint256 _type, uint256 _amount ) public { require(_from == _msgSender() || isApprovedForAll(_from, _msgSender()), "GravisCollectible: must have approval"); require(_type < typeData.length, "GravisCollectible: type not exist"); TokenVault storage vaultFrom = tokens[_from]; TokenVault storage vaultTo = tokens[_to]; TokenVault storage vaultType = typeData[_type].vault; uint256 index = 0; uint256 transfered = 0; uint256 fromBuf; uint256 toBuf; while (transfered < _amount) { while (index < VAULT_SIZE_SLOTS && vaultFrom.data[index] == 0) ++index; require(index < VAULT_SIZE_SLOTS, "GravisCollectible: not enough tokens"); fromBuf = vaultFrom.data[index]; toBuf = vaultTo.data[index]; uint256 bit = 0; while (transfered < _amount) { while (bit < 256) { uint256 mask = 1 << bit; if (fromBuf & mask != 0 && vaultType.data[index] & mask != 0) break; ++bit; } if (bit == 256) { vaultFrom.data[index] = fromBuf; vaultTo.data[index] = toBuf; ++index; break; } uint256 tokenId = index * 256 + bit; _approve(address(0), tokenId); uint256 mask = 1 << bit; toBuf |= mask; fromBuf &= ~mask; emit Transfer(_from, _to, tokenId); ++transfered; } } vaultFrom.data[index] = fromBuf; vaultTo.data[index] = toBuf; owners.add(_to); owners.remove(_from); } /** * @dev Approve `_to` to operate on `_tokenId` * * Emits an {Approval} event. */ function _approve(address _to, uint256 _tokenId) internal virtual { if (_tokenApprovals[_tokenId] != _to) { _tokenApprovals[_tokenId] = _to; emit Approval(_msgSender(), _to, _tokenId); // internal owner } } /** * @dev Burn a single token `_tokenId` for address `_who`. */ function _burnFor(address _who, uint256 _tokenId) internal virtual { (uint256 index, uint256 mask) = _position(_tokenId); require(tokens[_who].data[index] & mask != 0, "not owner"); _approve(address(0), _tokenId); mask = ~mask; tokens[_who].data[index] &= mask; for (uint256 i = 0; i < typeData.length; ++i) { typeData[i].vault.data[index] &= mask; } owners.remove(_who); emit Transfer(_who, address(0), _tokenId); } /** * @dev Transfers `_tokenId` from `_from` to `_to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Emits a {Transfer} event. */ function _transfer( address _from, address _to, uint256 _tokenId ) internal virtual { require(isOwner(_from, _tokenId), "ERC721: transfer of token that is not own"); // internal owner require(_to != address(0), "ERC721: transfer to the zero address"); // Clear approvals from the previous owner _approve(address(0), _tokenId); (uint256 index, uint256 mask) = _position(_tokenId); tokens[_from].data[index] &= ~mask; tokens[_to].data[index] |= mask; owners.add(_to); owners.remove(_from); emit Transfer(_from, _to, _tokenId); } /** * @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`. * * 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 Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address _from, address _to, uint256 _tokenId, bytes memory _data ) private returns (bool) { if (!_to.isContract()) { return true; } bytes memory returndata = _to.functionCall( abi.encodeWithSelector( IERC721Receiver(_to).onERC721Received.selector, _msgSender(), _from, _tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer" ); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Returns whether `_spender` is allowed to manage `_tokenId`. */ function _isApprovedOrOwner(address _spender, uint256 _tokenId) internal view virtual returns (bool) { if (isOwner(_spender, _tokenId)) return true; return (getApproved(_tokenId) == _spender || isApprovedForAll(ownerOf(_tokenId), _spender)); } function _position(uint256 _tokenId) internal pure returns (uint256 index, uint256 mask) { index = _tokenId / 256; require(index < VAULT_SIZE_SLOTS, "GravisCollectible: OOB"); mask = uint256(1 << (_tokenId % 256)); } }
See {IERC721Enumerable-tokenOfOwnerByIndex}./
function tokenOfOwnerByIndex(address _who, uint256 _index) public view virtual override returns (uint256) { TokenVault storage vault = tokens[_who]; uint256 index = 0; uint256 bit = 0; uint256 cnt = 0; while (true) { uint256 val = vault.data[index]; if (val != 0) { while (bit < 256 && (val & (1 << bit) == 0)) ++bit; } if (val == 0 || bit == 256) { bit = 0; ++index; require(index < VAULT_SIZE_SLOTS, "GravisCollectible: not enough tokens"); continue; } if (cnt == _index) break; ++cnt; ++bit; } return index * 256 + bit; }
10,668,553
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; // interface AggregatorV3Interface { // function decimals() external view returns (uint8); // function description() external view returns (string memory); // function version() external view returns (uint256); // // getRoundData and latestRoundData should both raise "No data present" // // if they do not have data to report, instead of returning unset values // // which could be misinterpreted as actual reported values. // function getRoundData(uint80 _roundId) // external // view // returns ( // uint80 roundId, // int256 answer, // uint256 startedAt, // uint256 updatedAt, // uint80 answeredInRound // ); // function latestRoundData() // external // view // returns ( // uint80 roundId, // int256 answer, // uint256 startedAt, // uint256 updatedAt, // uint80 answeredInRound // ); // } contract FundMe { using SafeMath for uint256; mapping(address => uint256) public addressToAmountFunded; address[] public funders; address public owner; constructor() { owner = msg.sender; } function fund() public payable { uint256 mimiumUSD = 50 * 10 ** 18; require(getConversionRate(msg.value) >= mimiumUSD, "You neet to speend mor ETH!"); addressToAmountFunded[msg.sender] += msg.value; funders.push(msg.sender); // what the EHT -> USD conversion rate? } function getVersion() public view returns (uint256) { AggregatorV3Interface priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331); return priceFeed.version(); } function getPrice() public view returns (uint256) { AggregatorV3Interface priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331); (,int256 answer,,,) = priceFeed.latestRoundData(); return uint256(answer * (10**10)); // 3,062.16329944 } function getConversionRate(uint256 ethAmount) public view returns (uint256) { uint256 ethPrice = getPrice(); uint256 ethAmountInUsd = (ethPrice * ethAmount) / (10**18); return ethAmountInUsd; } modifier onlyOwner { require(msg.sender == owner); _; } function withdraw() payable onlyOwner public { // only wang the contract admin/owner // require msg.sender = owner payable(msg.sender).transfer(address(this).balance); for (uint256 funderIndex=0; funderIndex < funders.length; funderIndex++) { address funder = funders[funderIndex]; addressToAmountFunded[funder] = 0; } funders = new address[](0); } }
only wang the contract admin/owner require msg.sender = owner
function withdraw() payable onlyOwner public { payable(msg.sender).transfer(address(this).balance); for (uint256 funderIndex=0; funderIndex < funders.length; funderIndex++) { address funder = funders[funderIndex]; addressToAmountFunded[funder] = 0; } funders = new address[](0); }
13,122,773
./full_match/3/0xD7508365Db62f825EeafA0b1615C02cB0E4F1DFB/sources/browser/bzxliquidate.sol
send token 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE if you want to withdraw ether20% of profit will be sent to the DeFiEducationProject for creation and publication of more code like thisfor etherfor tokens
function withdraw(address token) public onlyOwner returns(bool) { if (address(token) == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { uint256 amount = address(this).balance; defiEducationProject.transfer((amount / 10)); uint256 rest = address(this).balance; msg.sender.transfer(rest); } else { ERC20 tokenToken = ERC20(token); uint256 tokenBalance = tokenToken.balanceOf(address(this)); require(tokenToken.transfer(defiEducationProject, (tokenBalance / 10))); uint256 newTokenBalance = tokenToken.balanceOf(address(this)); require(tokenToken.transfer(msg.sender, (newTokenBalance))); } return true; }
8,254,523
./full_match/43113/0x29FB6CA56d7F4485eCBaf0AEd941d52E7A662307/sources/contracts/protocol/SetToken.sol
Takes a virtual unit and multiplies by the position multiplier to return the real unit/
function _convertVirtualToRealUnit(int256 _virtualUnit) internal view returns (int256) { return _virtualUnit.conservativePreciseMul(positionMultiplier); }
7,191,759
// SPDX-License-Identifier: MIT pragma solidity >=0.6.11; pragma experimental ABIEncoderV2; import "../StakingRewardsDualV3.sol"; contract StakingRewardsDualV3_FRAX_IQ is StakingRewardsDualV3 { constructor( address _owner, address _rewardsToken0, address _rewardsToken1, address _stakingToken, address _frax_address, address _timelock_address, address _veFXS_address ) StakingRewardsDualV3(_owner, _rewardsToken0, _rewardsToken1, _stakingToken, _frax_address, _timelock_address, _veFXS_address ) {} } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; pragma experimental ABIEncoderV2; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ======================= StakingRewardsDualV3 ======================= // ==================================================================== // Includes veFXS boost logic // Unlocked deposits are removed to free up space // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Reviewer(s) / Contributor(s) // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Sam Sun: https://github.com/samczsun // Modified originally from Synthetixio // https://raw.githubusercontent.com/Synthetixio/synthetix/develop/contracts/StakingRewards.sol import "../Math/Math.sol"; import "../Math/SafeMath.sol"; import "../Curve/IveFXS.sol"; import "../ERC20/ERC20.sol"; import '../Uniswap/TransferHelper.sol'; import "../ERC20/SafeERC20.sol"; import "../Frax/Frax.sol"; import "../Uniswap/Interfaces/IUniswapV2Pair.sol"; import "../Utils/ReentrancyGuard.sol"; // Inheritance import "./Owned.sol"; contract StakingRewardsDualV3 is Owned, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for ERC20; /* ========== STATE VARIABLES ========== */ // Instances IveFXS private veFXS; ERC20 private rewardsToken0; ERC20 private rewardsToken1; IUniswapV2Pair private stakingToken; // Constant for various precisions uint256 private constant MULTIPLIER_PRECISION = 1e18; // Admin addresses address public timelock_address; // Governance timelock address // Time tracking uint256 public periodFinish; uint256 public lastUpdateTime; // Lock time and multiplier settings uint256 public lock_max_multiplier = uint256(3e18); // E18. 1x = e18 uint256 public lock_time_for_max_multiplier = 3 * 365 * 86400; // 3 years uint256 public lock_time_min = 86400; // 1 * 86400 (1 day) // veFXS related uint256 public vefxs_per_frax_for_max_boost = uint256(4e18); // E18. 4e18 means 4 veFXS must be held by the staker per 1 FRAX uint256 public vefxs_max_multiplier = uint256(25e17); // E18. 1x = 1e18 // mapping(address => uint256) private _vefxsMultiplierStoredOld; mapping(address => uint256) private _vefxsMultiplierStored; // Max reward per second uint256 public rewardRate0; uint256 public rewardRate1; // Reward period uint256 public rewardsDuration = 604800; // 7 * 86400 (7 days) // Reward tracking uint256 public rewardPerTokenStored0 = 0; uint256 public rewardPerTokenStored1 = 0; mapping(address => uint256) public userRewardPerTokenPaid0; mapping(address => uint256) public userRewardPerTokenPaid1; mapping(address => uint256) public rewards0; mapping(address => uint256) public rewards1; // Balance tracking uint256 private _total_liquidity_locked = 0; uint256 private _total_combined_weight = 0; mapping(address => uint256) private _locked_liquidity; mapping(address => uint256) private _combined_weights; // Uniswap related bool frax_is_token0; // Stake tracking mapping(address => LockedStake[]) private lockedStakes; // List of valid migrators (set by governance) mapping(address => bool) public valid_migrators; address[] public valid_migrators_array; // Stakers set which migrator(s) they want to use mapping(address => mapping(address => bool)) public staker_allowed_migrators; // Greylisting of bad addresses mapping(address => bool) public greylist; // Administrative booleans bool public token1_rewards_on = true; bool public migrationsOn = false; // Used for migrations. Prevents new stakes, but allows LP and reward withdrawals bool public stakesUnlocked = false; // Release locked stakes in case of system migration or emergency bool public withdrawalsPaused = false; // For emergencies bool public rewardsCollectionPaused = false; // For emergencies bool public stakingPaused = false; // For emergencies /* ========== STRUCTS ========== */ struct LockedStake { bytes32 kek_id; uint256 start_timestamp; uint256 liquidity; uint256 ending_timestamp; uint256 lock_multiplier; // 6 decimals of precision. 1x = 1000000 } /* ========== MODIFIERS ========== */ modifier onlyByOwnerOrGovernance() { require(msg.sender == owner || msg.sender == timelock_address, "You are not the owner or the governance timelock"); _; } modifier onlyByOwnerOrGovernanceOrMigrator() { require(msg.sender == owner || msg.sender == timelock_address || valid_migrators[msg.sender] == true, "You are not the owner, governance timelock, or a migrator"); _; } modifier isMigrating() { require(migrationsOn == true, "Contract is not in migration"); _; } modifier notStakingPaused() { require(stakingPaused == false, "Staking is paused"); _; } modifier notWithdrawalsPaused() { require(withdrawalsPaused == false, "Withdrawals are paused"); _; } modifier notRewardsCollectionPaused() { require(rewardsCollectionPaused == false, "Rewards collection is paused"); _; } modifier updateRewardAndBalance(address account, bool sync_too) { _updateRewardAndBalance(account, sync_too); _; } /* ========== CONSTRUCTOR ========== */ constructor( address _owner, address _rewardsToken0, address _rewardsToken1, address _stakingToken, address _frax_address, address _timelock_address, address _veFXS_address ) Owned(_owner){ rewardsToken0 = ERC20(_rewardsToken0); rewardsToken1 = ERC20(_rewardsToken1); stakingToken = IUniswapV2Pair(_stakingToken); veFXS = IveFXS(_veFXS_address); lastUpdateTime = block.timestamp; timelock_address = _timelock_address; // 10 FXS a day rewardRate0 = (uint256(3650e18)).div(365 * 86400); // 1 token1 a day rewardRate1 = (uint256(365e18)).div(365 * 86400); // Uniswap related. Need to know which token frax is (0 or 1) address token0 = stakingToken.token0(); if (token0 == _frax_address) frax_is_token0 = true; else frax_is_token0 = false; // Other booleans migrationsOn = false; stakesUnlocked = false; } /* ========== VIEWS ========== */ function totalLiquidityLocked() external view returns (uint256) { return _total_liquidity_locked; } function totalCombinedWeight() external view returns (uint256) { return _total_combined_weight; } function lockMultiplier(uint256 secs) public view returns (uint256) { uint256 lock_multiplier = uint256(MULTIPLIER_PRECISION).add( secs .mul(lock_max_multiplier.sub(MULTIPLIER_PRECISION)) .div(lock_time_for_max_multiplier) ); if (lock_multiplier > lock_max_multiplier) lock_multiplier = lock_max_multiplier; return lock_multiplier; } // Total locked liquidity tokens function lockedLiquidityOf(address account) public view returns (uint256) { return _locked_liquidity[account]; } // Total 'balance' used for calculating the percent of the pool the account owns // Takes into account the locked stake time multiplier and veFXS multiplier function combinedWeightOf(address account) external view returns (uint256) { return _combined_weights[account]; } function lockedStakesOf(address account) external view returns (LockedStake[] memory) { return lockedStakes[account]; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function fraxPerLPToken() public view returns (uint256) { // Get the amount of FRAX 'inside' of the lp tokens uint256 frax_per_lp_token; { uint256 total_frax_reserves; (uint256 reserve0, uint256 reserve1, ) = (stakingToken.getReserves()); if (frax_is_token0) total_frax_reserves = reserve0; else total_frax_reserves = reserve1; frax_per_lp_token = total_frax_reserves.mul(1e18).div(stakingToken.totalSupply()); } return frax_per_lp_token; } function userStakedFrax(address account) public view returns (uint256) { return (fraxPerLPToken()).mul(_locked_liquidity[account]).div(1e18); } function minVeFXSForMaxBoost(address account) public view returns (uint256) { return (userStakedFrax(account)).mul(vefxs_per_frax_for_max_boost).div(MULTIPLIER_PRECISION); } function veFXSMultiplier(address account) public view returns (uint256) { // The claimer gets a boost depending on amount of veFXS they have relative to the amount of FRAX 'inside' // of their locked LP tokens uint256 veFXS_needed_for_max_boost = minVeFXSForMaxBoost(account); if (veFXS_needed_for_max_boost > 0){ uint256 user_vefxs_fraction = (veFXS.balanceOf(account)).mul(MULTIPLIER_PRECISION).div(veFXS_needed_for_max_boost); uint256 vefxs_multiplier = uint256(MULTIPLIER_PRECISION).add( (user_vefxs_fraction) .mul(vefxs_max_multiplier.sub(MULTIPLIER_PRECISION)) .div(MULTIPLIER_PRECISION) ); // Cap the boost to the vefxs_max_multiplier if (vefxs_multiplier > vefxs_max_multiplier) vefxs_multiplier = vefxs_max_multiplier; return vefxs_multiplier; } else return MULTIPLIER_PRECISION; // This will happen with the first stake, when user_staked_frax is 0 } function calcCurCombinedWeight(address account) public view returns ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) { // Get the old combined weight old_combined_weight = _combined_weights[account]; // Get the veFXS multipliers // For the calculations, use the midpoint (analogous to midpoint Riemann sum) new_vefxs_multiplier = veFXSMultiplier(account); uint256 midpoint_vefxs_multiplier = ((new_vefxs_multiplier).add(_vefxsMultiplierStored[account])).div(2); // Loop through the locked stakes, first by getting the liquidity * lock_multiplier portion new_combined_weight = 0; for (uint256 i = 0; i < lockedStakes[account].length; i++) { LockedStake memory thisStake = lockedStakes[account][i]; uint256 lock_multiplier = thisStake.lock_multiplier; // If the lock period is over, drop the lock multiplier to 1x for the weight calculations if (thisStake.ending_timestamp <= block.timestamp){ lock_multiplier = MULTIPLIER_PRECISION; } uint256 liquidity = thisStake.liquidity; uint256 extra_vefxs_boost = midpoint_vefxs_multiplier.sub(MULTIPLIER_PRECISION); // Multiplier - 1, because it is additive uint256 combined_boosted_amount = liquidity.mul(lock_multiplier.add(extra_vefxs_boost)).div(MULTIPLIER_PRECISION); new_combined_weight = new_combined_weight.add(combined_boosted_amount); } } function rewardPerToken() public view returns (uint256, uint256) { if (_total_liquidity_locked == 0 || _total_combined_weight == 0) { return (rewardPerTokenStored0, rewardPerTokenStored1); } else { return ( rewardPerTokenStored0.add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate0).mul(1e18).div(_total_combined_weight) ), rewardPerTokenStored1.add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate1).mul(1e18).div(_total_combined_weight) ) ); } } function earned(address account) public view returns (uint256, uint256) { (uint256 reward0, uint256 reward1) = rewardPerToken(); if (_combined_weights[account] == 0){ return (0, 0); } return ( (_combined_weights[account].mul(reward0.sub(userRewardPerTokenPaid0[account]))).div(1e18).add(rewards0[account]), (_combined_weights[account].mul(reward1.sub(userRewardPerTokenPaid1[account]))).div(1e18).add(rewards1[account]) ); } function getRewardForDuration() external view returns (uint256, uint256) { return ( rewardRate0.mul(rewardsDuration), rewardRate1.mul(rewardsDuration) ); } function migratorApprovedForStaker(address staker_address, address migrator_address) public view returns (bool) { // Migrator is not a valid one if (valid_migrators[migrator_address] == false) return false; // Staker has to have approved this particular migrator if (staker_allowed_migrators[staker_address][migrator_address] == true) return true; // Otherwise, return false return false; } /* ========== MUTATIVE FUNCTIONS ========== */ function _updateRewardAndBalance(address account, bool sync_too) internal { // Need to retro-adjust some things if the period hasn't been renewed, then start a new one if (sync_too){ sync(); } if (account != address(0)) { // To keep the math correct, the user's combined weight must be recomputed to account for their // ever-changing veFXS balance. ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) = calcCurCombinedWeight(account); // Calculate the earnings first _syncEarned(account); // Update the user's stored veFXS multipliers _vefxsMultiplierStored[account] = new_vefxs_multiplier; // Update the user's and the global combined weights if (new_combined_weight >= old_combined_weight) { uint256 weight_diff = new_combined_weight.sub(old_combined_weight); _total_combined_weight = _total_combined_weight.add(weight_diff); _combined_weights[account] = old_combined_weight.add(weight_diff); } else { uint256 weight_diff = old_combined_weight.sub(new_combined_weight); _total_combined_weight = _total_combined_weight.sub(weight_diff); _combined_weights[account] = old_combined_weight.sub(weight_diff); } } } function _syncEarned(address account) internal { if (account != address(0)) { // Calculate the earnings (uint256 earned0, uint256 earned1) = earned(account); rewards0[account] = earned0; rewards1[account] = earned1; userRewardPerTokenPaid0[account] = rewardPerTokenStored0; userRewardPerTokenPaid1[account] = rewardPerTokenStored1; } } // Staker can allow a migrator function stakerAllowMigrator(address migrator_address) public { require(staker_allowed_migrators[msg.sender][migrator_address] == false, "Address already exists"); require(valid_migrators[migrator_address], "Invalid migrator address"); staker_allowed_migrators[msg.sender][migrator_address] = true; } // Staker can disallow a previously-allowed migrator function stakerDisallowMigrator(address migrator_address) public { require(staker_allowed_migrators[msg.sender][migrator_address] == true, "Address doesn't exist already"); // Delete from the mapping delete staker_allowed_migrators[msg.sender][migrator_address]; } // Two different stake functions are needed because of delegateCall and msg.sender issues (important for migration) function stakeLocked(uint256 liquidity, uint256 secs) public { _stakeLocked(msg.sender, msg.sender, liquidity, secs); } // If this were not internal, and source_address had an infinite approve, this could be exploitable // (pull funds from source_address and stake for an arbitrary staker_address) function _stakeLocked(address staker_address, address source_address, uint256 liquidity, uint256 secs) internal nonReentrant updateRewardAndBalance(staker_address, true) { require((!stakingPaused && migrationsOn == false) || valid_migrators[msg.sender] == true, "Staking is paused, or migration is happening"); require(liquidity > 0, "Must stake more than zero"); require(greylist[staker_address] == false, "Address has been greylisted"); require(secs >= lock_time_min, "Minimum stake time not met"); require(secs <= lock_time_for_max_multiplier,"You are trying to lock for too long"); uint256 lock_multiplier = lockMultiplier(secs); bytes32 kek_id = keccak256(abi.encodePacked(staker_address, block.timestamp, liquidity)); lockedStakes[staker_address].push(LockedStake( kek_id, block.timestamp, liquidity, block.timestamp.add(secs), lock_multiplier )); // Pull the tokens from the source_address TransferHelper.safeTransferFrom(address(stakingToken), source_address, address(this), liquidity); // Update liquidities _total_liquidity_locked = _total_liquidity_locked.add(liquidity); _locked_liquidity[staker_address] = _locked_liquidity[staker_address].add(liquidity); // Need to call to update the combined weights _updateRewardAndBalance(staker_address, false); emit StakeLocked(staker_address, liquidity, secs, kek_id, source_address); } // Two different withdrawLocked functions are needed because of delegateCall and msg.sender issues (important for migration) function withdrawLocked(bytes32 kek_id) public { _withdrawLocked(msg.sender, msg.sender, kek_id); } // No withdrawer == msg.sender check needed since this is only internally callable and the checks are done in the wrapper // functions like withdraw(), migrator_withdraw_unlocked() and migrator_withdraw_locked() function _withdrawLocked(address staker_address, address destination_address, bytes32 kek_id) internal nonReentrant notWithdrawalsPaused updateRewardAndBalance(staker_address, true) { LockedStake memory thisStake; thisStake.liquidity = 0; uint theArrayIndex; for (uint i = 0; i < lockedStakes[staker_address].length; i++){ if (kek_id == lockedStakes[staker_address][i].kek_id){ thisStake = lockedStakes[staker_address][i]; theArrayIndex = i; break; } } require(thisStake.kek_id == kek_id, "Stake not found"); require(block.timestamp >= thisStake.ending_timestamp || stakesUnlocked == true || valid_migrators[msg.sender] == true, "Stake is still locked!"); uint256 liquidity = thisStake.liquidity; if (liquidity > 0) { // Update liquidities _total_liquidity_locked = _total_liquidity_locked.sub(liquidity); _locked_liquidity[staker_address] = _locked_liquidity[staker_address].sub(liquidity); // Remove the stake from the array delete lockedStakes[staker_address][theArrayIndex]; // Need to call to update the combined weights _updateRewardAndBalance(staker_address, false); // Give the tokens to the destination_address // Should throw if insufficient balance stakingToken.transfer(destination_address, liquidity); emit WithdrawLocked(staker_address, liquidity, kek_id, destination_address); } } // Two different getReward functions are needed because of delegateCall and msg.sender issues (important for migration) function getReward() external returns (uint256, uint256) { return _getReward(msg.sender, msg.sender); } // No withdrawer == msg.sender check needed since this is only internally callable // This distinction is important for the migrator function _getReward(address rewardee, address destination_address) internal nonReentrant notRewardsCollectionPaused updateRewardAndBalance(rewardee, true) returns (uint256 reward0, uint256 reward1) { reward0 = rewards0[rewardee]; reward1 = rewards1[rewardee]; if (reward0 > 0) { rewards0[rewardee] = 0; rewardsToken0.transfer(destination_address, reward0); emit RewardPaid(rewardee, reward0, address(rewardsToken0), destination_address); } // if (token1_rewards_on){ if (reward1 > 0) { rewards1[rewardee] = 0; rewardsToken1.transfer(destination_address, reward1); emit RewardPaid(rewardee, reward1, address(rewardsToken1), destination_address); } // } } function renewIfApplicable() external { if (block.timestamp > periodFinish) { retroCatchUp(); } } // If the period expired, renew it function retroCatchUp() internal { // Failsafe check require(block.timestamp > periodFinish, "Period has not expired yet!"); // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint256 num_periods_elapsed = uint256(block.timestamp.sub(periodFinish)) / rewardsDuration; // Floor division to the nearest period uint balance0 = rewardsToken0.balanceOf(address(this)); uint balance1 = rewardsToken1.balanceOf(address(this)); require(rewardRate0.mul(rewardsDuration).mul(num_periods_elapsed + 1) <= balance0, "Not enough FXS available for rewards!"); if (token1_rewards_on){ require(rewardRate1.mul(rewardsDuration).mul(num_periods_elapsed + 1) <= balance1, "Not enough token1 available for rewards!"); } // uint256 old_lastUpdateTime = lastUpdateTime; // uint256 new_lastUpdateTime = block.timestamp; // lastUpdateTime = periodFinish; periodFinish = periodFinish.add((num_periods_elapsed.add(1)).mul(rewardsDuration)); (uint256 reward0, uint256 reward1) = rewardPerToken(); rewardPerTokenStored0 = reward0; rewardPerTokenStored1 = reward1; lastUpdateTime = lastTimeRewardApplicable(); emit RewardsPeriodRenewed(address(stakingToken)); } function sync() public { if (block.timestamp > periodFinish) { retroCatchUp(); } else { (uint256 reward0, uint256 reward1) = rewardPerToken(); rewardPerTokenStored0 = reward0; rewardPerTokenStored1 = reward1; lastUpdateTime = lastTimeRewardApplicable(); } } /* ========== RESTRICTED FUNCTIONS ========== */ // Migrator can stake for someone else (they won't be able to withdraw it back though, only staker_address can). function migrator_stakeLocked_for(address staker_address, uint256 amount, uint256 secs) external isMigrating { require(migratorApprovedForStaker(staker_address, msg.sender), "msg.sender is either an invalid migrator or the staker has not approved them"); _stakeLocked(staker_address, msg.sender, amount, secs); } // Used for migrations function migrator_withdraw_locked(address staker_address, bytes32 kek_id) external isMigrating { require(migratorApprovedForStaker(staker_address, msg.sender), "msg.sender is either an invalid migrator or the staker has not approved them"); _withdrawLocked(staker_address, msg.sender, kek_id); } // Adds supported migrator address function addMigrator(address migrator_address) public onlyByOwnerOrGovernance { require(valid_migrators[migrator_address] == false, "address already exists"); valid_migrators[migrator_address] = true; valid_migrators_array.push(migrator_address); } // Remove a migrator address function removeMigrator(address migrator_address) public onlyByOwnerOrGovernance { require(valid_migrators[migrator_address] == true, "address doesn't exist already"); // Delete from the mapping delete valid_migrators[migrator_address]; // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < valid_migrators_array.length; i++){ if (valid_migrators_array[i] == migrator_address) { valid_migrators_array[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } } // Added to support recovering LP Rewards and other mistaken tokens from other systems to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance { // Admin cannot withdraw the staking token from the contract unless currently migrating if(!migrationsOn){ require(tokenAddress != address(stakingToken), "Cannot withdraw staking tokens unless migration is on"); // Only Governance / Timelock can trigger a migration } // Only the owner address can ever receive the recovery withdrawal ERC20(tokenAddress).transfer(owner, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } function setRewardsDuration(uint256 _rewardsDuration) external onlyByOwnerOrGovernance { require( periodFinish == 0 || block.timestamp > periodFinish, "Previous rewards period must be complete before changing the duration for the new period" ); rewardsDuration = _rewardsDuration; emit RewardsDurationUpdated(rewardsDuration); } function setMultipliers(uint256 _lock_max_multiplier, uint256 _vefxs_max_multiplier, uint256 _vefxs_per_frax_for_max_boost) external onlyByOwnerOrGovernance { require(_lock_max_multiplier >= uint256(1e6), "Multiplier must be greater than or equal to 1e6"); require(_vefxs_max_multiplier >= uint256(1e18), "Max veFXS multiplier must be greater than or equal to 1e18"); require(_vefxs_per_frax_for_max_boost > 0, "veFXS per FRAX must be greater than 0"); lock_max_multiplier = _lock_max_multiplier; vefxs_max_multiplier = _vefxs_max_multiplier; vefxs_per_frax_for_max_boost = _vefxs_per_frax_for_max_boost; emit MaxVeFXSMultiplier(vefxs_max_multiplier); emit LockedStakeMaxMultiplierUpdated(lock_max_multiplier); emit veFXSPerFraxForMaxBoostUpdated(vefxs_per_frax_for_max_boost); } function setLockedStakeTimeForMinAndMaxMultiplier(uint256 _lock_time_for_max_multiplier, uint256 _lock_time_min) external onlyByOwnerOrGovernance { require(_lock_time_for_max_multiplier >= 1, "Multiplier Max Time must be greater than or equal to 1"); require(_lock_time_min >= 1, "Multiplier Min Time must be greater than or equal to 1"); lock_time_for_max_multiplier = _lock_time_for_max_multiplier; lock_time_min = _lock_time_min; emit LockedStakeTimeForMaxMultiplier(lock_time_for_max_multiplier); emit LockedStakeMinTime(_lock_time_min); } function initializeDefault() external onlyByOwnerOrGovernance { lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); emit DefaultInitialization(); } function greylistAddress(address _address) external onlyByOwnerOrGovernance { greylist[_address] = !(greylist[_address]); } function unlockStakes() external onlyByOwnerOrGovernance { stakesUnlocked = !stakesUnlocked; } function toggleMigrations() external onlyByOwnerOrGovernance { migrationsOn = !migrationsOn; } function toggleStaking() external onlyByOwnerOrGovernance { stakingPaused = !stakingPaused; } function toggleWithdrawals() external onlyByOwnerOrGovernance { withdrawalsPaused = !withdrawalsPaused; } function toggleRewardsCollection() external onlyByOwnerOrGovernance { rewardsCollectionPaused = !rewardsCollectionPaused; } function setRewardRates(uint256 _new_rate0, uint256 _new_rate1, bool sync_too) external onlyByOwnerOrGovernance { rewardRate0 = _new_rate0; rewardRate1 = _new_rate1; if (sync_too){ sync(); } } function toggleToken1Rewards() external onlyByOwnerOrGovernance { if (token1_rewards_on) { rewardRate1 = 0; } token1_rewards_on = !token1_rewards_on; } function setTimelock(address _new_timelock) external onlyByOwnerOrGovernance { timelock_address = _new_timelock; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event StakeLocked(address indexed user, uint256 amount, uint256 secs, bytes32 kek_id, address source_address); event WithdrawLocked(address indexed user, uint256 amount, bytes32 kek_id, address destination_address); event RewardPaid(address indexed user, uint256 reward, address token_address, address destination_address); event RewardsDurationUpdated(uint256 newDuration); event Recovered(address token, uint256 amount); event RewardsPeriodRenewed(address token); event DefaultInitialization(); event LockedStakeMaxMultiplierUpdated(uint256 multiplier); event LockedStakeTimeForMaxMultiplier(uint256 secs); event LockedStakeMinTime(uint256 secs); event MaxVeFXSMultiplier(uint256 multiplier); event veFXSPerFraxForMaxBoostUpdated(uint256 scale_factor); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; /** * @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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; interface IveFXS { struct LockedBalance { int128 amount; uint256 end; } /* ========== VIEWS ========== */ function balanceOf(address addr) external view returns (uint256); function balanceOf(address addr, uint256 _t) external view returns (uint256); function balanceOfAt(address addr, uint256 _block) external returns (uint256); function totalSupply() external view returns (uint256); function totalSupply(uint256 t) external view returns (uint256); function totalSupplyAt(uint256 _block) external returns (uint256); function totalFXSSupply() external view returns (uint256); function totalFXSSupplyAt(uint256 _block) external view returns (uint256); function locked(address addr) external view returns (LockedBalance memory); /* ========== PUBLIC FUNCTIONS ========== */ function checkpoint() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "../Common/Context.sol"; import "./IERC20.sol"; import "../Math/SafeMath.sol"; import "../Utils/Address.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 Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory __name, string memory __symbol) public { _name = __name; _symbol = __symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address.approve(address spender, uint256 amount) */ 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 the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for `accounts`'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } /** * @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 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 virtual { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } /** * @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:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "./IERC20.sol"; import "../Math/SafeMath.sol"; import "../Utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ======================= FRAXStablecoin (FRAX) ====================== // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Reviewer(s) / Contributor(s) // Sam Sun: https://github.com/samczsun import "../Common/Context.sol"; import "../ERC20/IERC20.sol"; import "../ERC20/ERC20Custom.sol"; import "../ERC20/ERC20.sol"; import "../Math/SafeMath.sol"; import "../Staking/Owned.sol"; import "../FXS/FXS.sol"; import "./Pools/FraxPool.sol"; import "../Oracle/UniswapPairOracle.sol"; import "../Oracle/ChainlinkETHUSDPriceConsumer.sol"; import "../Governance/AccessControl.sol"; contract FRAXStablecoin is ERC20Custom, AccessControl, Owned { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ enum PriceChoice { FRAX, FXS } ChainlinkETHUSDPriceConsumer private eth_usd_pricer; uint8 private eth_usd_pricer_decimals; UniswapPairOracle private fraxEthOracle; UniswapPairOracle private fxsEthOracle; string public symbol; string public name; uint8 public constant decimals = 18; address public creator_address; address public timelock_address; // Governance timelock address address public controller_address; // Controller contract to dynamically adjust system parameters automatically address public fxs_address; address public frax_eth_oracle_address; address public fxs_eth_oracle_address; address public weth_address; address public eth_usd_consumer_address; uint256 public constant genesis_supply = 2000000e18; // 2M FRAX (only for testing, genesis supply will be 5k on Mainnet). This is to help with establishing the Uniswap pools, as they need liquidity // The addresses in this array are added by the oracle and these contracts are able to mint frax address[] public frax_pools_array; // Mapping is also used for faster verification mapping(address => bool) public frax_pools; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; uint256 public global_collateral_ratio; // 6 decimals of precision, e.g. 924102 = 0.924102 uint256 public redemption_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee uint256 public minting_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee uint256 public frax_step; // Amount to change the collateralization ratio by upon refreshCollateralRatio() uint256 public refresh_cooldown; // Seconds to wait before being able to run refreshCollateralRatio() again uint256 public price_target; // The price of FRAX at which the collateral ratio will respond to; this value is only used for the collateral ratio mechanism and not for minting and redeeming which are hardcoded at $1 uint256 public price_band; // The bound above and below the price target at which the refreshCollateralRatio() will not change the collateral ratio address public DEFAULT_ADMIN_ADDRESS; bytes32 public constant COLLATERAL_RATIO_PAUSER = keccak256("COLLATERAL_RATIO_PAUSER"); bool public collateral_ratio_paused = false; /* ========== MODIFIERS ========== */ modifier onlyCollateralRatioPauser() { require(hasRole(COLLATERAL_RATIO_PAUSER, msg.sender)); _; } modifier onlyPools() { require(frax_pools[msg.sender] == true, "Only frax pools can call this function"); _; } modifier onlyByOwnerOrGovernance() { require(msg.sender == owner || msg.sender == timelock_address || msg.sender == controller_address, "You are not the owner, controller, or the governance timelock"); _; } modifier onlyByOwnerGovernanceOrPool() { require( msg.sender == owner || msg.sender == timelock_address || frax_pools[msg.sender] == true, "You are not the owner, the governance timelock, or a pool"); _; } /* ========== CONSTRUCTOR ========== */ constructor( string memory _name, string memory _symbol, address _creator_address, address _timelock_address ) public Owned(_creator_address){ require(_timelock_address != address(0), "Zero address detected"); name = _name; symbol = _symbol; creator_address = _creator_address; timelock_address = _timelock_address; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); DEFAULT_ADMIN_ADDRESS = _msgSender(); _mint(creator_address, genesis_supply); grantRole(COLLATERAL_RATIO_PAUSER, creator_address); grantRole(COLLATERAL_RATIO_PAUSER, timelock_address); frax_step = 2500; // 6 decimals of precision, equal to 0.25% global_collateral_ratio = 1000000; // Frax system starts off fully collateralized (6 decimals of precision) refresh_cooldown = 3600; // Refresh cooldown period is set to 1 hour (3600 seconds) at genesis price_target = 1000000; // Collateral ratio will adjust according to the $1 price target at genesis price_band = 5000; // Collateral ratio will not adjust if between $0.995 and $1.005 at genesis } /* ========== VIEWS ========== */ // Choice = 'FRAX' or 'FXS' for now function oracle_price(PriceChoice choice) internal view returns (uint256) { // Get the ETH / USD price first, and cut it down to 1e6 precision uint256 __eth_usd_price = uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals); uint256 price_vs_eth = 0; if (choice == PriceChoice.FRAX) { price_vs_eth = uint256(fraxEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FRAX if you put in PRICE_PRECISION WETH } else if (choice == PriceChoice.FXS) { price_vs_eth = uint256(fxsEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FXS if you put in PRICE_PRECISION WETH } else revert("INVALID PRICE CHOICE. Needs to be either 0 (FRAX) or 1 (FXS)"); // Will be in 1e6 format return __eth_usd_price.mul(PRICE_PRECISION).div(price_vs_eth); } // Returns X FRAX = 1 USD function frax_price() public view returns (uint256) { return oracle_price(PriceChoice.FRAX); } // Returns X FXS = 1 USD function fxs_price() public view returns (uint256) { return oracle_price(PriceChoice.FXS); } function eth_usd_price() public view returns (uint256) { return uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals); } // This is needed to avoid costly repeat calls to different getter functions // It is cheaper gas-wise to just dump everything and only use some of the info function frax_info() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) { return ( oracle_price(PriceChoice.FRAX), // frax_price() oracle_price(PriceChoice.FXS), // fxs_price() totalSupply(), // totalSupply() global_collateral_ratio, // global_collateral_ratio() globalCollateralValue(), // globalCollateralValue minting_fee, // minting_fee() redemption_fee, // redemption_fee() uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals) //eth_usd_price ); } // Iterate through all frax pools and calculate all value of collateral in all pools globally function globalCollateralValue() public view returns (uint256) { uint256 total_collateral_value_d18 = 0; for (uint i = 0; i < frax_pools_array.length; i++){ // Exclude null addresses if (frax_pools_array[i] != address(0)){ total_collateral_value_d18 = total_collateral_value_d18.add(FraxPool(frax_pools_array[i]).collatDollarBalance()); } } return total_collateral_value_d18; } /* ========== PUBLIC FUNCTIONS ========== */ // There needs to be a time interval that this can be called. Otherwise it can be called multiple times per expansion. uint256 public last_call_time; // Last time the refreshCollateralRatio function was called function refreshCollateralRatio() public { require(collateral_ratio_paused == false, "Collateral Ratio has been paused"); uint256 frax_price_cur = frax_price(); require(block.timestamp - last_call_time >= refresh_cooldown, "Must wait for the refresh cooldown since last refresh"); // Step increments are 0.25% (upon genesis, changable by setFraxStep()) if (frax_price_cur > price_target.add(price_band)) { //decrease collateral ratio if(global_collateral_ratio <= frax_step){ //if within a step of 0, go to 0 global_collateral_ratio = 0; } else { global_collateral_ratio = global_collateral_ratio.sub(frax_step); } } else if (frax_price_cur < price_target.sub(price_band)) { //increase collateral ratio if(global_collateral_ratio.add(frax_step) >= 1000000){ global_collateral_ratio = 1000000; // cap collateral ratio at 1.000000 } else { global_collateral_ratio = global_collateral_ratio.add(frax_step); } } last_call_time = block.timestamp; // Set the time of the last expansion emit CollateralRatioRefreshed(global_collateral_ratio); } /* ========== RESTRICTED FUNCTIONS ========== */ // Used by pools when user redeems function pool_burn_from(address b_address, uint256 b_amount) public onlyPools { super._burnFrom(b_address, b_amount); emit FRAXBurned(b_address, msg.sender, b_amount); } // This function is what other frax pools will call to mint new FRAX function pool_mint(address m_address, uint256 m_amount) public onlyPools { super._mint(m_address, m_amount); emit FRAXMinted(msg.sender, m_address, m_amount); } // Adds collateral addresses supported, such as tether and busd, must be ERC20 function addPool(address pool_address) public onlyByOwnerOrGovernance { require(pool_address != address(0), "Zero address detected"); require(frax_pools[pool_address] == false, "address already exists"); frax_pools[pool_address] = true; frax_pools_array.push(pool_address); emit PoolAdded(pool_address); } // Remove a pool function removePool(address pool_address) public onlyByOwnerOrGovernance { require(pool_address != address(0), "Zero address detected"); require(frax_pools[pool_address] == true, "address doesn't exist already"); // Delete from the mapping delete frax_pools[pool_address]; // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < frax_pools_array.length; i++){ if (frax_pools_array[i] == pool_address) { frax_pools_array[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } emit PoolRemoved(pool_address); } function setRedemptionFee(uint256 red_fee) public onlyByOwnerOrGovernance { redemption_fee = red_fee; emit RedemptionFeeSet(red_fee); } function setMintingFee(uint256 min_fee) public onlyByOwnerOrGovernance { minting_fee = min_fee; emit MintingFeeSet(min_fee); } function setFraxStep(uint256 _new_step) public onlyByOwnerOrGovernance { frax_step = _new_step; emit FraxStepSet(_new_step); } function setPriceTarget (uint256 _new_price_target) public onlyByOwnerOrGovernance { price_target = _new_price_target; emit PriceTargetSet(_new_price_target); } function setRefreshCooldown(uint256 _new_cooldown) public onlyByOwnerOrGovernance { refresh_cooldown = _new_cooldown; emit RefreshCooldownSet(_new_cooldown); } function setFXSAddress(address _fxs_address) public onlyByOwnerOrGovernance { require(_fxs_address != address(0), "Zero address detected"); fxs_address = _fxs_address; emit FXSAddressSet(_fxs_address); } function setETHUSDOracle(address _eth_usd_consumer_address) public onlyByOwnerOrGovernance { require(_eth_usd_consumer_address != address(0), "Zero address detected"); eth_usd_consumer_address = _eth_usd_consumer_address; eth_usd_pricer = ChainlinkETHUSDPriceConsumer(eth_usd_consumer_address); eth_usd_pricer_decimals = eth_usd_pricer.getDecimals(); emit ETHUSDOracleSet(_eth_usd_consumer_address); } function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { require(new_timelock != address(0), "Zero address detected"); timelock_address = new_timelock; emit TimelockSet(new_timelock); } function setController(address _controller_address) external onlyByOwnerOrGovernance { require(_controller_address != address(0), "Zero address detected"); controller_address = _controller_address; emit ControllerSet(_controller_address); } function setPriceBand(uint256 _price_band) external onlyByOwnerOrGovernance { price_band = _price_band; emit PriceBandSet(_price_band); } // Sets the FRAX_ETH Uniswap oracle address function setFRAXEthOracle(address _frax_oracle_addr, address _weth_address) public onlyByOwnerOrGovernance { require((_frax_oracle_addr != address(0)) && (_weth_address != address(0)), "Zero address detected"); frax_eth_oracle_address = _frax_oracle_addr; fraxEthOracle = UniswapPairOracle(_frax_oracle_addr); weth_address = _weth_address; emit FRAXETHOracleSet(_frax_oracle_addr, _weth_address); } // Sets the FXS_ETH Uniswap oracle address function setFXSEthOracle(address _fxs_oracle_addr, address _weth_address) public onlyByOwnerOrGovernance { require((_fxs_oracle_addr != address(0)) && (_weth_address != address(0)), "Zero address detected"); fxs_eth_oracle_address = _fxs_oracle_addr; fxsEthOracle = UniswapPairOracle(_fxs_oracle_addr); weth_address = _weth_address; emit FXSEthOracleSet(_fxs_oracle_addr, _weth_address); } function toggleCollateralRatio() public onlyCollateralRatioPauser { collateral_ratio_paused = !collateral_ratio_paused; emit CollateralRatioToggled(collateral_ratio_paused); } /* ========== EVENTS ========== */ // Track FRAX burned event FRAXBurned(address indexed from, address indexed to, uint256 amount); // Track FRAX minted event FRAXMinted(address indexed from, address indexed to, uint256 amount); event CollateralRatioRefreshed(uint256 global_collateral_ratio); event PoolAdded(address pool_address); event PoolRemoved(address pool_address); event RedemptionFeeSet(uint256 red_fee); event MintingFeeSet(uint256 min_fee); event FraxStepSet(uint256 new_step); event PriceTargetSet(uint256 new_price_target); event RefreshCooldownSet(uint256 new_cooldown); event FXSAddressSet(address _fxs_address); event ETHUSDOracleSet(address eth_usd_consumer_address); event TimelockSet(address new_timelock); event ControllerSet(address controller_address); event PriceBandSet(uint256 price_band); event FRAXETHOracleSet(address frax_oracle_addr, address weth_address); event FXSEthOracleSet(address fxs_oracle_addr, address weth_address); event CollateralRatioToggled(bool collateral_ratio_paused); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; 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; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; // https://docs.synthetix.io/contracts/Owned contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "../Common/Context.sol"; import "../Math/SafeMath.sol"; /** * @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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11 <0.9.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "../Common/Context.sol"; import "./IERC20.sol"; import "../Math/SafeMath.sol"; import "../Utils/Address.sol"; // Due to compiling issues, _name, _symbol, and _decimals were removed /** * @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 ERC20Custom is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 private _totalSupply; /** * @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.approve(address spender, uint256 amount) */ 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 the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for `accounts`'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } /** * @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 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 virtual { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } /** * @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:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ========================= FRAXShares (FXS) ========================= // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Reviewer(s) / Contributor(s) // Sam Sun: https://github.com/samczsun import "../Common/Context.sol"; import "../ERC20/ERC20Custom.sol"; import "../ERC20/IERC20.sol"; import "../Frax/Frax.sol"; import "../Staking/Owned.sol"; import "../Math/SafeMath.sol"; import "../Governance/AccessControl.sol"; contract FRAXShares is ERC20Custom, AccessControl, Owned { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ string public symbol; string public name; uint8 public constant decimals = 18; address public FRAXStablecoinAdd; uint256 public constant genesis_supply = 100000000e18; // 100M is printed upon genesis address public oracle_address; address public timelock_address; // Governance timelock address FRAXStablecoin private FRAX; bool public trackingVotes = true; // Tracking votes (only change if need to disable votes) // A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } // A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; // The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /* ========== MODIFIERS ========== */ modifier onlyPools() { require(FRAX.frax_pools(msg.sender) == true, "Only frax pools can mint new FRAX"); _; } modifier onlyByOwnerOrGovernance() { require(msg.sender == owner || msg.sender == timelock_address, "You are not an owner or the governance timelock"); _; } /* ========== CONSTRUCTOR ========== */ constructor( string memory _name, string memory _symbol, address _oracle_address, address _creator_address, address _timelock_address ) public Owned(_creator_address){ require((_oracle_address != address(0)) && (_timelock_address != address(0)), "Zero address detected"); name = _name; symbol = _symbol; oracle_address = _oracle_address; timelock_address = _timelock_address; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _mint(_creator_address, genesis_supply); // Do a checkpoint for the owner _writeCheckpoint(_creator_address, 0, 0, uint96(genesis_supply)); } /* ========== RESTRICTED FUNCTIONS ========== */ function setOracle(address new_oracle) external onlyByOwnerOrGovernance { require(new_oracle != address(0), "Zero address detected"); oracle_address = new_oracle; } function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { require(new_timelock != address(0), "Timelock address cannot be 0"); timelock_address = new_timelock; } function setFRAXAddress(address frax_contract_address) external onlyByOwnerOrGovernance { require(frax_contract_address != address(0), "Zero address detected"); FRAX = FRAXStablecoin(frax_contract_address); emit FRAXAddressSet(frax_contract_address); } function mint(address to, uint256 amount) public onlyPools { _mint(to, amount); } // This function is what other frax pools will call to mint new FXS (similar to the FRAX mint) function pool_mint(address m_address, uint256 m_amount) external onlyPools { if(trackingVotes){ uint32 srcRepNum = numCheckpoints[address(this)]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0; uint96 srcRepNew = add96(srcRepOld, uint96(m_amount), "pool_mint new votes overflows"); _writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // mint new votes trackVotes(address(this), m_address, uint96(m_amount)); } super._mint(m_address, m_amount); emit FXSMinted(address(this), m_address, m_amount); } // This function is what other frax pools will call to burn FXS function pool_burn_from(address b_address, uint256 b_amount) external onlyPools { if(trackingVotes){ trackVotes(b_address, address(this), uint96(b_amount)); uint32 srcRepNum = numCheckpoints[address(this)]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, uint96(b_amount), "pool_burn_from new votes underflows"); _writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // burn votes } super._burnFrom(b_address, b_amount); emit FXSBurned(b_address, address(this), b_amount); } function toggleVotes() external onlyByOwnerOrGovernance { trackingVotes = !trackingVotes; } /* ========== OVERRIDDEN PUBLIC FUNCTIONS ========== */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { if(trackingVotes){ // Transfer votes trackVotes(_msgSender(), recipient, uint96(amount)); } _transfer(_msgSender(), recipient, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { if(trackingVotes){ // Transfer votes trackVotes(sender, recipient, uint96(amount)); } _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /* ========== PUBLIC FUNCTIONS ========== */ /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "FXS::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; } /* ========== INTERNAL FUNCTIONS ========== */ // From compound's _moveDelegates // Keep track of votes. "Delegates" is a misnomer here function trackVotes(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "FXS::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "FXS::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address voter, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "FXS::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[voter][nCheckpoints - 1].votes = newVotes; } else { checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[voter] = nCheckpoints + 1; } emit VoterVotesChanged(voter, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } /* ========== EVENTS ========== */ /// @notice An event thats emitted when a voters account's vote balance changes event VoterVotesChanged(address indexed voter, uint previousBalance, uint newBalance); // Track FXS burned event FXSBurned(address indexed from, address indexed to, uint256 amount); // Track FXS minted event FXSMinted(address indexed from, address indexed to, uint256 amount); event FRAXAddressSet(address addr); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ============================= FraxPool ============================= // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Reviewer(s) / Contributor(s) // Sam Sun: https://github.com/samczsun import "../../Math/SafeMath.sol"; import '../../Uniswap/TransferHelper.sol'; import "../../Staking/Owned.sol"; import "../../FXS/FXS.sol"; import "../../Frax/Frax.sol"; import "../../ERC20/ERC20.sol"; import "../../Oracle/UniswapPairOracle.sol"; import "../../Governance/AccessControl.sol"; import "./FraxPoolLibrary.sol"; contract FraxPool is AccessControl, Owned { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ ERC20 private collateral_token; address private collateral_address; address private frax_contract_address; address private fxs_contract_address; address private timelock_address; FRAXShares private FXS; FRAXStablecoin private FRAX; UniswapPairOracle private collatEthOracle; address public collat_eth_oracle_address; address private weth_address; uint256 public minting_fee; uint256 public redemption_fee; uint256 public buyback_fee; uint256 public recollat_fee; mapping (address => uint256) public redeemFXSBalances; mapping (address => uint256) public redeemCollateralBalances; uint256 public unclaimedPoolCollateral; uint256 public unclaimedPoolFXS; mapping (address => uint256) public lastRedeemed; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_MAX = 1e6; // Number of decimals needed to get to 18 uint256 private immutable missing_decimals; // Pool_ceiling is the total units of collateral that a pool contract can hold uint256 public pool_ceiling = 0; // Stores price of the collateral, if price is paused uint256 public pausedPrice = 0; // Bonus rate on FXS minted during recollateralizeFRAX(); 6 decimals of precision, set to 0.75% on genesis uint256 public bonus_rate = 7500; // Number of blocks to wait before being able to collectRedemption() uint256 public redemption_delay = 1; // AccessControl Roles bytes32 private constant MINT_PAUSER = keccak256("MINT_PAUSER"); bytes32 private constant REDEEM_PAUSER = keccak256("REDEEM_PAUSER"); bytes32 private constant BUYBACK_PAUSER = keccak256("BUYBACK_PAUSER"); bytes32 private constant RECOLLATERALIZE_PAUSER = keccak256("RECOLLATERALIZE_PAUSER"); bytes32 private constant COLLATERAL_PRICE_PAUSER = keccak256("COLLATERAL_PRICE_PAUSER"); // AccessControl state variables bool public mintPaused = false; bool public redeemPaused = false; bool public recollateralizePaused = false; bool public buyBackPaused = false; bool public collateralPricePaused = false; /* ========== MODIFIERS ========== */ modifier onlyByOwnerOrGovernance() { require(msg.sender == timelock_address || msg.sender == owner, "You are not the owner or the governance timelock"); _; } modifier notRedeemPaused() { require(redeemPaused == false, "Redeeming is paused"); _; } modifier notMintPaused() { require(mintPaused == false, "Minting is paused"); _; } /* ========== CONSTRUCTOR ========== */ constructor( address _frax_contract_address, address _fxs_contract_address, address _collateral_address, address _creator_address, address _timelock_address, uint256 _pool_ceiling ) public Owned(_creator_address){ require( (_frax_contract_address != address(0)) && (_fxs_contract_address != address(0)) && (_collateral_address != address(0)) && (_creator_address != address(0)) && (_timelock_address != address(0)) , "Zero address detected"); FRAX = FRAXStablecoin(_frax_contract_address); FXS = FRAXShares(_fxs_contract_address); frax_contract_address = _frax_contract_address; fxs_contract_address = _fxs_contract_address; collateral_address = _collateral_address; timelock_address = _timelock_address; collateral_token = ERC20(_collateral_address); pool_ceiling = _pool_ceiling; missing_decimals = uint(18).sub(collateral_token.decimals()); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); grantRole(MINT_PAUSER, timelock_address); grantRole(REDEEM_PAUSER, timelock_address); grantRole(RECOLLATERALIZE_PAUSER, timelock_address); grantRole(BUYBACK_PAUSER, timelock_address); grantRole(COLLATERAL_PRICE_PAUSER, timelock_address); } /* ========== VIEWS ========== */ // Returns dollar value of collateral held in this Frax pool function collatDollarBalance() public view returns (uint256) { if(collateralPricePaused == true){ return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(pausedPrice).div(PRICE_PRECISION); } else { uint256 eth_usd_price = FRAX.eth_usd_price(); uint256 eth_collat_price = collatEthOracle.consult(weth_address, (PRICE_PRECISION * (10 ** missing_decimals))); uint256 collat_usd_price = eth_usd_price.mul(PRICE_PRECISION).div(eth_collat_price); return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(collat_usd_price).div(PRICE_PRECISION); //.mul(getCollateralPrice()).div(1e6); } } // Returns the value of excess collateral held in this Frax pool, compared to what is needed to maintain the global collateral ratio function availableExcessCollatDV() public view returns (uint256) { uint256 total_supply = FRAX.totalSupply(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 global_collat_value = FRAX.globalCollateralValue(); if (global_collateral_ratio > COLLATERAL_RATIO_PRECISION) global_collateral_ratio = COLLATERAL_RATIO_PRECISION; // Handles an overcollateralized contract with CR > 1 uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(COLLATERAL_RATIO_PRECISION); // Calculates collateral needed to back each 1 FRAX with $1 of collateral at current collat ratio if (global_collat_value > required_collat_dollar_value_d18) return global_collat_value.sub(required_collat_dollar_value_d18); else return 0; } /* ========== PUBLIC FUNCTIONS ========== */ // Returns the price of the pool collateral in USD function getCollateralPrice() public view returns (uint256) { if(collateralPricePaused == true){ return pausedPrice; } else { uint256 eth_usd_price = FRAX.eth_usd_price(); return eth_usd_price.mul(PRICE_PRECISION).div(collatEthOracle.consult(weth_address, PRICE_PRECISION * (10 ** missing_decimals))); } } function setCollatETHOracle(address _collateral_weth_oracle_address, address _weth_address) external onlyByOwnerOrGovernance { collat_eth_oracle_address = _collateral_weth_oracle_address; collatEthOracle = UniswapPairOracle(_collateral_weth_oracle_address); weth_address = _weth_address; } // We separate out the 1t1, fractional and algorithmic minting functions for gas efficiency function mint1t1FRAX(uint256 collateral_amount, uint256 FRAX_out_min) external notMintPaused { uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); require(FRAX.global_collateral_ratio() >= COLLATERAL_RATIO_MAX, "Collateral ratio must be >= 1"); require((collateral_token.balanceOf(address(this))).sub(unclaimedPoolCollateral).add(collateral_amount) <= pool_ceiling, "[Pool's Closed]: Ceiling reached"); (uint256 frax_amount_d18) = FraxPoolLibrary.calcMint1t1FRAX( getCollateralPrice(), collateral_amount_d18 ); //1 FRAX for each $1 worth of collateral frax_amount_d18 = (frax_amount_d18.mul(uint(1e6).sub(minting_fee))).div(1e6); //remove precision at the end require(FRAX_out_min <= frax_amount_d18, "Slippage limit reached"); TransferHelper.safeTransferFrom(address(collateral_token), msg.sender, address(this), collateral_amount); FRAX.pool_mint(msg.sender, frax_amount_d18); } // 0% collateral-backed function mintAlgorithmicFRAX(uint256 fxs_amount_d18, uint256 FRAX_out_min) external notMintPaused { uint256 fxs_price = FRAX.fxs_price(); require(FRAX.global_collateral_ratio() == 0, "Collateral ratio must be 0"); (uint256 frax_amount_d18) = FraxPoolLibrary.calcMintAlgorithmicFRAX( fxs_price, // X FXS / 1 USD fxs_amount_d18 ); frax_amount_d18 = (frax_amount_d18.mul(uint(1e6).sub(minting_fee))).div(1e6); require(FRAX_out_min <= frax_amount_d18, "Slippage limit reached"); FXS.pool_burn_from(msg.sender, fxs_amount_d18); FRAX.pool_mint(msg.sender, frax_amount_d18); } // Will fail if fully collateralized or fully algorithmic // > 0% and < 100% collateral-backed function mintFractionalFRAX(uint256 collateral_amount, uint256 fxs_amount, uint256 FRAX_out_min) external notMintPaused { uint256 fxs_price = FRAX.fxs_price(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999"); require(collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral).add(collateral_amount) <= pool_ceiling, "Pool ceiling reached, no more FRAX can be minted with this collateral"); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); FraxPoolLibrary.MintFF_Params memory input_params = FraxPoolLibrary.MintFF_Params( fxs_price, getCollateralPrice(), fxs_amount, collateral_amount_d18, global_collateral_ratio ); (uint256 mint_amount, uint256 fxs_needed) = FraxPoolLibrary.calcMintFractionalFRAX(input_params); mint_amount = (mint_amount.mul(uint(1e6).sub(minting_fee))).div(1e6); require(FRAX_out_min <= mint_amount, "Slippage limit reached"); require(fxs_needed <= fxs_amount, "Not enough FXS inputted"); FXS.pool_burn_from(msg.sender, fxs_needed); TransferHelper.safeTransferFrom(address(collateral_token), msg.sender, address(this), collateral_amount); FRAX.pool_mint(msg.sender, mint_amount); } // Redeem collateral. 100% collateral-backed function redeem1t1FRAX(uint256 FRAX_amount, uint256 COLLATERAL_out_min) external notRedeemPaused { require(FRAX.global_collateral_ratio() == COLLATERAL_RATIO_MAX, "Collateral ratio must be == 1"); // Need to adjust for decimals of collateral uint256 FRAX_amount_precision = FRAX_amount.div(10 ** missing_decimals); (uint256 collateral_needed) = FraxPoolLibrary.calcRedeem1t1FRAX( getCollateralPrice(), FRAX_amount_precision ); collateral_needed = (collateral_needed.mul(uint(1e6).sub(redemption_fee))).div(1e6); require(collateral_needed <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), "Not enough collateral in pool"); require(COLLATERAL_out_min <= collateral_needed, "Slippage limit reached"); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_needed); unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_needed); lastRedeemed[msg.sender] = block.number; // Move all external functions to the end FRAX.pool_burn_from(msg.sender, FRAX_amount); } // Will fail if fully collateralized or algorithmic // Redeem FRAX for collateral and FXS. > 0% and < 100% collateral-backed function redeemFractionalFRAX(uint256 FRAX_amount, uint256 FXS_out_min, uint256 COLLATERAL_out_min) external notRedeemPaused { uint256 fxs_price = FRAX.fxs_price(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999"); uint256 col_price_usd = getCollateralPrice(); uint256 FRAX_amount_post_fee = (FRAX_amount.mul(uint(1e6).sub(redemption_fee))).div(PRICE_PRECISION); uint256 fxs_dollar_value_d18 = FRAX_amount_post_fee.sub(FRAX_amount_post_fee.mul(global_collateral_ratio).div(PRICE_PRECISION)); uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price); // Need to adjust for decimals of collateral uint256 FRAX_amount_precision = FRAX_amount_post_fee.div(10 ** missing_decimals); uint256 collateral_dollar_value = FRAX_amount_precision.mul(global_collateral_ratio).div(PRICE_PRECISION); uint256 collateral_amount = collateral_dollar_value.mul(PRICE_PRECISION).div(col_price_usd); require(collateral_amount <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), "Not enough collateral in pool"); require(COLLATERAL_out_min <= collateral_amount, "Slippage limit reached [collateral]"); require(FXS_out_min <= fxs_amount, "Slippage limit reached [FXS]"); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_amount); unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_amount); redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount); unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount); lastRedeemed[msg.sender] = block.number; // Move all external functions to the end FRAX.pool_burn_from(msg.sender, FRAX_amount); FXS.pool_mint(address(this), fxs_amount); } // Redeem FRAX for FXS. 0% collateral-backed function redeemAlgorithmicFRAX(uint256 FRAX_amount, uint256 FXS_out_min) external notRedeemPaused { uint256 fxs_price = FRAX.fxs_price(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); require(global_collateral_ratio == 0, "Collateral ratio must be 0"); uint256 fxs_dollar_value_d18 = FRAX_amount; fxs_dollar_value_d18 = (fxs_dollar_value_d18.mul(uint(1e6).sub(redemption_fee))).div(PRICE_PRECISION); //apply fees uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price); redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount); unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount); lastRedeemed[msg.sender] = block.number; require(FXS_out_min <= fxs_amount, "Slippage limit reached"); // Move all external functions to the end FRAX.pool_burn_from(msg.sender, FRAX_amount); FXS.pool_mint(address(this), fxs_amount); } // After a redemption happens, transfer the newly minted FXS and owed collateral from this pool // contract to the user. Redemption is split into two functions to prevent flash loans from being able // to take out FRAX/collateral from the system, use an AMM to trade the new price, and then mint back into the system. function collectRedemption() external { require((lastRedeemed[msg.sender].add(redemption_delay)) <= block.number, "Must wait for redemption_delay blocks before collecting redemption"); bool sendFXS = false; bool sendCollateral = false; uint FXSAmount = 0; uint CollateralAmount = 0; // Use Checks-Effects-Interactions pattern if(redeemFXSBalances[msg.sender] > 0){ FXSAmount = redeemFXSBalances[msg.sender]; redeemFXSBalances[msg.sender] = 0; unclaimedPoolFXS = unclaimedPoolFXS.sub(FXSAmount); sendFXS = true; } if(redeemCollateralBalances[msg.sender] > 0){ CollateralAmount = redeemCollateralBalances[msg.sender]; redeemCollateralBalances[msg.sender] = 0; unclaimedPoolCollateral = unclaimedPoolCollateral.sub(CollateralAmount); sendCollateral = true; } if(sendFXS){ TransferHelper.safeTransfer(address(FXS), msg.sender, FXSAmount); } if(sendCollateral){ TransferHelper.safeTransfer(address(collateral_token), msg.sender, CollateralAmount); } } // When the protocol is recollateralizing, we need to give a discount of FXS to hit the new CR target // Thus, if the target collateral ratio is higher than the actual value of collateral, minters get FXS for adding collateral // This function simply rewards anyone that sends collateral to a pool with the same amount of FXS + the bonus rate // Anyone can call this function to recollateralize the protocol and take the extra FXS value from the bonus rate as an arb opportunity function recollateralizeFRAX(uint256 collateral_amount, uint256 FXS_out_min) external { require(recollateralizePaused == false, "Recollateralize is paused"); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); uint256 fxs_price = FRAX.fxs_price(); uint256 frax_total_supply = FRAX.totalSupply(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 global_collat_value = FRAX.globalCollateralValue(); (uint256 collateral_units, uint256 amount_to_recollat) = FraxPoolLibrary.calcRecollateralizeFRAXInner( collateral_amount_d18, getCollateralPrice(), global_collat_value, frax_total_supply, global_collateral_ratio ); uint256 collateral_units_precision = collateral_units.div(10 ** missing_decimals); uint256 fxs_paid_back = amount_to_recollat.mul(uint(1e6).add(bonus_rate).sub(recollat_fee)).div(fxs_price); require(FXS_out_min <= fxs_paid_back, "Slippage limit reached"); TransferHelper.safeTransferFrom(address(collateral_token), msg.sender, address(this), collateral_units_precision); FXS.pool_mint(msg.sender, fxs_paid_back); } // Function can be called by an FXS holder to have the protocol buy back FXS with excess collateral value from a desired collateral pool // This can also happen if the collateral ratio > 1 function buyBackFXS(uint256 FXS_amount, uint256 COLLATERAL_out_min) external { require(buyBackPaused == false, "Buyback is paused"); uint256 fxs_price = FRAX.fxs_price(); FraxPoolLibrary.BuybackFXS_Params memory input_params = FraxPoolLibrary.BuybackFXS_Params( availableExcessCollatDV(), fxs_price, getCollateralPrice(), FXS_amount ); (uint256 collateral_equivalent_d18) = (FraxPoolLibrary.calcBuyBackFXS(input_params)).mul(uint(1e6).sub(buyback_fee)).div(1e6); uint256 collateral_precision = collateral_equivalent_d18.div(10 ** missing_decimals); require(COLLATERAL_out_min <= collateral_precision, "Slippage limit reached"); // Give the sender their desired collateral and burn the FXS FXS.pool_burn_from(msg.sender, FXS_amount); TransferHelper.safeTransfer(address(collateral_token), msg.sender, collateral_precision); } /* ========== RESTRICTED FUNCTIONS ========== */ function toggleMinting() external { require(hasRole(MINT_PAUSER, msg.sender)); mintPaused = !mintPaused; emit MintingToggled(mintPaused); } function toggleRedeeming() external { require(hasRole(REDEEM_PAUSER, msg.sender)); redeemPaused = !redeemPaused; emit RedeemingToggled(redeemPaused); } function toggleRecollateralize() external { require(hasRole(RECOLLATERALIZE_PAUSER, msg.sender)); recollateralizePaused = !recollateralizePaused; emit RecollateralizeToggled(recollateralizePaused); } function toggleBuyBack() external { require(hasRole(BUYBACK_PAUSER, msg.sender)); buyBackPaused = !buyBackPaused; emit BuybackToggled(buyBackPaused); } function toggleCollateralPrice(uint256 _new_price) external { require(hasRole(COLLATERAL_PRICE_PAUSER, msg.sender)); // If pausing, set paused price; else if unpausing, clear pausedPrice if(collateralPricePaused == false){ pausedPrice = _new_price; } else { pausedPrice = 0; } collateralPricePaused = !collateralPricePaused; emit CollateralPriceToggled(collateralPricePaused); } // Combined into one function due to 24KiB contract memory limit function setPoolParameters(uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee) external onlyByOwnerOrGovernance { pool_ceiling = new_ceiling; bonus_rate = new_bonus_rate; redemption_delay = new_redemption_delay; minting_fee = new_mint_fee; redemption_fee = new_redeem_fee; buyback_fee = new_buyback_fee; recollat_fee = new_recollat_fee; emit PoolParametersSet(new_ceiling, new_bonus_rate, new_redemption_delay, new_mint_fee, new_redeem_fee, new_buyback_fee, new_recollat_fee); } function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { timelock_address = new_timelock; emit TimelockSet(new_timelock); } /* ========== EVENTS ========== */ event PoolParametersSet(uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee); event TimelockSet(address new_timelock); event MintingToggled(bool toggled); event RedeemingToggled(bool toggled); event RecollateralizeToggled(bool toggled); event BuybackToggled(bool toggled); event CollateralPriceToggled(bool toggled); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import '../Uniswap/Interfaces/IUniswapV2Factory.sol'; import '../Uniswap/Interfaces/IUniswapV2Pair.sol'; import '../Math/FixedPoint.sol'; import '../Uniswap/UniswapV2OracleLibrary.sol'; import '../Uniswap/UniswapV2Library.sol'; import "../Staking/Owned.sol"; // Fixed window oracle that recomputes the average price for the entire period once every period // Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period contract UniswapPairOracle is Owned { using FixedPoint for *; address timelock_address; uint public PERIOD = 3600; // 1 hour TWAP (time-weighted average price) uint public CONSULT_LENIENCY = 120; // Used for being able to consult past the period end bool public ALLOW_STALE_CONSULTS = false; // If false, consult() will fail if the TWAP is stale IUniswapV2Pair public immutable pair; address public immutable token0; address public immutable token1; uint public price0CumulativeLast; uint public price1CumulativeLast; uint32 public blockTimestampLast; FixedPoint.uq112x112 public price0Average; FixedPoint.uq112x112 public price1Average; modifier onlyByOwnerOrGovernance() { require(msg.sender == owner || msg.sender == timelock_address, "You are not an owner or the governance timelock"); _; } constructor(address factory, address tokenA, address tokenB, address _owner_address, address _timelock_address) public Owned(_owner_address) { IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB)); pair = _pair; token0 = _pair.token0(); token1 = _pair.token1(); price0CumulativeLast = _pair.price0CumulativeLast(); // Fetch the current accumulated price value (1 / 0) price1CumulativeLast = _pair.price1CumulativeLast(); // Fetch the current accumulated price value (0 / 1) uint112 reserve0; uint112 reserve1; (reserve0, reserve1, blockTimestampLast) = _pair.getReserves(); require(reserve0 != 0 && reserve1 != 0, 'UniswapPairOracle: NO_RESERVES'); // Ensure that there's liquidity in the pair timelock_address = _timelock_address; } function setTimelock(address _timelock_address) external onlyByOwnerOrGovernance { timelock_address = _timelock_address; } function setPeriod(uint _period) external onlyByOwnerOrGovernance { PERIOD = _period; } function setConsultLeniency(uint _consult_leniency) external onlyByOwnerOrGovernance { CONSULT_LENIENCY = _consult_leniency; } function setAllowStaleConsults(bool _allow_stale_consults) external onlyByOwnerOrGovernance { ALLOW_STALE_CONSULTS = _allow_stale_consults; } // Check if update() can be called instead of wasting gas calling it function canUpdate() public view returns (bool) { uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp(); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired return (timeElapsed >= PERIOD); } function update() external { (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair)); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired // Ensure that at least one full period has passed since the last update require(timeElapsed >= PERIOD, 'UniswapPairOracle: PERIOD_NOT_ELAPSED'); // Overflow is desired, casting never truncates // Cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed)); price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed)); price0CumulativeLast = price0Cumulative; price1CumulativeLast = price1Cumulative; blockTimestampLast = blockTimestamp; } // Note this will always return 0 before update has been called successfully for the first time. function consult(address token, uint amountIn) external view returns (uint amountOut) { uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp(); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired // Ensure that the price is not stale require((timeElapsed < (PERIOD + CONSULT_LENIENCY)) || ALLOW_STALE_CONSULTS, 'UniswapPairOracle: PRICE_IS_STALE_NEED_TO_CALL_UPDATE'); if (token == token0) { amountOut = price0Average.mul(amountIn).decode144(); } else { require(token == token1, 'UniswapPairOracle: INVALID_TOKEN'); amountOut = price1Average.mul(amountIn).decode144(); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "./AggregatorV3Interface.sol"; contract ChainlinkETHUSDPriceConsumer { AggregatorV3Interface internal priceFeed; constructor() public { priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419); } /** * Returns the latest price */ function getLatestPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } function getDecimals() public view returns (uint8) { return priceFeed.decimals(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "../Utils/EnumerableSet.sol"; import "../Utils/Address.sol"; import "../Common/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; //bytes32(uint256(0x4B437D01b575618140442A4975db38850e3f8f5f) << 96); /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "../../Math/SafeMath.sol"; library FraxPoolLibrary { using SafeMath for uint256; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; // ================ Structs ================ // Needed to lower stack size struct MintFF_Params { uint256 fxs_price_usd; uint256 col_price_usd; uint256 fxs_amount; uint256 collateral_amount; uint256 col_ratio; } struct BuybackFXS_Params { uint256 excess_collateral_dollar_value_d18; uint256 fxs_price_usd; uint256 col_price_usd; uint256 FXS_amount; } // ================ Functions ================ function calcMint1t1FRAX(uint256 col_price, uint256 collateral_amount_d18) public pure returns (uint256) { return (collateral_amount_d18.mul(col_price)).div(1e6); } function calcMintAlgorithmicFRAX(uint256 fxs_price_usd, uint256 fxs_amount_d18) public pure returns (uint256) { return fxs_amount_d18.mul(fxs_price_usd).div(1e6); } // Must be internal because of the struct function calcMintFractionalFRAX(MintFF_Params memory params) internal pure returns (uint256, uint256) { // Since solidity truncates division, every division operation must be the last operation in the equation to ensure minimum error // The contract must check the proper ratio was sent to mint FRAX. We do this by seeing the minimum mintable FRAX based on each amount uint256 fxs_dollar_value_d18; uint256 c_dollar_value_d18; // Scoping for stack concerns { // USD amounts of the collateral and the FXS fxs_dollar_value_d18 = params.fxs_amount.mul(params.fxs_price_usd).div(1e6); c_dollar_value_d18 = params.collateral_amount.mul(params.col_price_usd).div(1e6); } uint calculated_fxs_dollar_value_d18 = (c_dollar_value_d18.mul(1e6).div(params.col_ratio)) .sub(c_dollar_value_d18); uint calculated_fxs_needed = calculated_fxs_dollar_value_d18.mul(1e6).div(params.fxs_price_usd); return ( c_dollar_value_d18.add(calculated_fxs_dollar_value_d18), calculated_fxs_needed ); } function calcRedeem1t1FRAX(uint256 col_price_usd, uint256 FRAX_amount) public pure returns (uint256) { return FRAX_amount.mul(1e6).div(col_price_usd); } // Must be internal because of the struct function calcBuyBackFXS(BuybackFXS_Params memory params) internal pure returns (uint256) { // If the total collateral value is higher than the amount required at the current collateral ratio then buy back up to the possible FXS with the desired collateral require(params.excess_collateral_dollar_value_d18 > 0, "No excess collateral to buy back!"); // Make sure not to take more than is available uint256 fxs_dollar_value_d18 = params.FXS_amount.mul(params.fxs_price_usd).div(1e6); require(fxs_dollar_value_d18 <= params.excess_collateral_dollar_value_d18, "You are trying to buy back more than the excess!"); // Get the equivalent amount of collateral based on the market value of FXS provided uint256 collateral_equivalent_d18 = fxs_dollar_value_d18.mul(1e6).div(params.col_price_usd); //collateral_equivalent_d18 = collateral_equivalent_d18.sub((collateral_equivalent_d18.mul(params.buyback_fee)).div(1e6)); return ( collateral_equivalent_d18 ); } // Returns value of collateral that must increase to reach recollateralization target (if 0 means no recollateralization) function recollateralizeAmount(uint256 total_supply, uint256 global_collateral_ratio, uint256 global_collat_value) public pure returns (uint256) { uint256 target_collat_value = total_supply.mul(global_collateral_ratio).div(1e6); // We want 18 decimals of precision so divide by 1e6; total_supply is 1e18 and global_collateral_ratio is 1e6 // Subtract the current value of collateral from the target value needed, if higher than 0 then system needs to recollateralize return target_collat_value.sub(global_collat_value); // If recollateralization is not needed, throws a subtraction underflow // return(recollateralization_left); } function calcRecollateralizeFRAXInner( uint256 collateral_amount, uint256 col_price, uint256 global_collat_value, uint256 frax_total_supply, uint256 global_collateral_ratio ) public pure returns (uint256, uint256) { uint256 collat_value_attempted = collateral_amount.mul(col_price).div(1e6); uint256 effective_collateral_ratio = global_collat_value.mul(1e6).div(frax_total_supply); //returns it in 1e6 uint256 recollat_possible = (global_collateral_ratio.mul(frax_total_supply).sub(frax_total_supply.mul(effective_collateral_ratio))).div(1e6); uint256 amount_to_recollat; if(collat_value_attempted <= recollat_possible){ amount_to_recollat = collat_value_attempted; } else { amount_to_recollat = recollat_possible; } return (amount_to_recollat.mul(1e6).div(col_price), amount_to_recollat); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; /** * @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(bytes20(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(bytes20(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(bytes20(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(bytes20(_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.11; 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; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import './Babylonian.sol'; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant RESOLUTION = 112; uint private constant Q112 = uint(1) << RESOLUTION; uint private constant Q224 = Q112 << RESOLUTION; // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << RESOLUTION) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // take the reciprocal of a UQ112x112 function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL'); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import '../Uniswap/Interfaces/IUniswapV2Pair.sol'; import '../Math/FixedPoint.sol'; // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import './Interfaces/IUniswapV2Pair.sol'; import './Interfaces/IUniswapV2Factory.sol'; import "../Math/SafeMath.sol"; library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // Less efficient than the CREATE2 method below function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = IUniswapV2Factory(factory).getPair(token0, token1); } // calculates the CREATE2 address for a pair without making any external calls function pairForCreate2(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint160(bytes20(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash ))))); // this matches the CREATE2 in UniswapV2Factory.createPair } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i = 0; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); }
If the period expired, renew it Failsafe check Ensure the provided reward amount is not more than the balance in the contract. This keeps the reward rate in the right range, preventing overflows due to very high values of rewardRate in the earned and rewardsPerToken functions; Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
function retroCatchUp() internal { require(block.timestamp > periodFinish, "Period has not expired yet!"); uint balance0 = rewardsToken0.balanceOf(address(this)); uint balance1 = rewardsToken1.balanceOf(address(this)); require(rewardRate0.mul(rewardsDuration).mul(num_periods_elapsed + 1) <= balance0, "Not enough FXS available for rewards!"); if (token1_rewards_on){ require(rewardRate1.mul(rewardsDuration).mul(num_periods_elapsed + 1) <= balance1, "Not enough token1 available for rewards!"); } (uint256 reward0, uint256 reward1) = rewardPerToken(); rewardPerTokenStored0 = reward0; rewardPerTokenStored1 = reward1; lastUpdateTime = lastTimeRewardApplicable(); emit RewardsPeriodRenewed(address(stakingToken)); }
1,275,976
pragma solidity ^0.5.7; // ------------------------------------------------------------------------ // Math library // ------------------------------------------------------------------------ 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); uint256 c = a / b; assert(a == b * 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; } } // ------------------------------------------------------------------------ // Basic token interface // ------------------------------------------------------------------------ contract IERC20 { uint256 public totalSupply; address public burnAddress = 0x0000000000000000000000000000000000000000; function balanceOf(address who) view public returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Minted(address target, uint256 mintedAmount); event Burned(address burner, uint256 burnedAmount); } // ------------------------------------------------------------------------ // Implementation of basic token interface // ------------------------------------------------------------------------ contract ERC20 is IERC20 { using SafeMath for uint256; mapping(address => uint256) public balances; // ------------------------------------------------------------------------ // Get balance of user // ------------------------------------------------------------------------ function balanceOf(address _owner) view public returns (uint256 balance) { return balances[_owner]; } // ------------------------------------------------------------------------ // Transfer tokens // ------------------------------------------------------------------------ function transfer(address _to, uint256 _value) public returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } // ------------------------------------------------------------------------ // Create tokens by adding to total supply and crediting the admin/owner // ------------------------------------------------------------------------ function mintToken(address _target, uint256 _mintedAmount) public returns(bool){ balances[_target] = balances[_target].add(_mintedAmount); totalSupply = totalSupply.add(_mintedAmount); emit Minted(_target, _mintedAmount); emit Transfer(address(0), address(this), _mintedAmount); emit Transfer(address(this), _target, _mintedAmount); return true; } // ------------------------------------------------------------------------ // Burn token by sending to to burn address & removing it from total supply // ------------------------------------------------------------------------ function burn(uint256 _burnAmount) public { address burner = msg.sender; balances[burner] = balances[burner].sub(_burnAmount); totalSupply = totalSupply.sub(_burnAmount); emit Burned(burner, _burnAmount); emit Transfer(burner, burnAddress, _burnAmount); } } // ------------------------------------------------------------------------ // Ownable contract definition // This is to allow for admin specific functions // ------------------------------------------------------------------------ contract Ownable { address payable public owner; address payable public potentialNewOwner; event OwnershipTransferred(address payable indexed _from, address payable indexed _to); // ------------------------------------------------------------------------ // Upon creation we set the creator as the owner // ------------------------------------------------------------------------ constructor() public { owner = msg.sender; } // ------------------------------------------------------------------------ // Set up the modifier to only allow the owner to pass through the condition // ------------------------------------------------------------------------ modifier onlyOwner() { require(msg.sender == owner); _; } // ------------------------------------------------------------------------ // Transfer ownership to another user // ------------------------------------------------------------------------ function transferOwnership(address payable _newOwner) public onlyOwner { potentialNewOwner = _newOwner; } // ------------------------------------------------------------------------ // To ensure correct transfer, the new owner has to confirm new ownership // ------------------------------------------------------------------------ function acceptOwnership() public { require(msg.sender == potentialNewOwner); emit OwnershipTransferred(owner, potentialNewOwner); owner = potentialNewOwner; } } // ------------------------------------------------------------------------ // Content moderatable contract definition // This is to allow for moderator specific functions // ------------------------------------------------------------------------ contract Moderatable is Ownable{ mapping(address => bool) public moderators; event ModeratorAdded(address indexed _moderator); event ModeratorRemoved(address indexed _moderator); // ------------------------------------------------------------------------ // Upon creation we set the first moderator as the owner // ------------------------------------------------------------------------ constructor() public { addModerator(owner); } // ------------------------------------------------------------------------ // Set up the modifier to only allow moderators to pass through the condition // ------------------------------------------------------------------------ modifier onlyModerators() { require(moderators[msg.sender] == true); _; } // ------------------------------------------------------------------------ // Add a moderator // ------------------------------------------------------------------------ function addModerator(address _newModerator) public onlyOwner { moderators[_newModerator] = true; emit ModeratorAdded(_newModerator); } // ------------------------------------------------------------------------ // Remove a moderator // ------------------------------------------------------------------------ function removeModerator(address _moderator) public onlyOwner { moderators[_moderator] = false; emit ModeratorRemoved(_moderator); } } // ------------------------------------------------------------------------ // Storage token definition // ------------------------------------------------------------------------ contract StorageToken is Moderatable{ using SafeMath for uint256; struct ContentMap{ uint256[] contentIds; mapping(uint256 => bool) containsContentId; bool exists; } uint256[] internal uniqueContentIds; mapping(uint256 => bool) internal contentIdExists; mapping(uint256 => ContentMap) internal articleContentIds; mapping(uint256 => ContentMap) internal subArticleContentIds; mapping(uint256 => string) internal contentById; uint256 public perPage = 7; event ContentAdded(address contentCreator, uint256 indexed articleId, uint256 indexed subArticleId, uint256 indexed contentId, uint256 timestamp); event ContentAddedViaEvent(address contentCreator, uint256 indexed articleId, uint256 indexed subArticleId, uint256 indexed contentId, uint256 timestamp, string data); // ------------------------------------------------------------------------ // Add content to event for content persistance. // By storing the content in an event (compared to the experiment contract) // we get very cheap storage // ------------------------------------------------------------------------ function addContentViaEvent(address contentCreator, uint256 articleId, uint256 subArticleId, uint256 contentId, uint256 timestamp, string memory data) onlyModerators public { emit ContentAddedViaEvent(contentCreator, articleId, subArticleId, contentId, timestamp, data); } // ------------------------------------------------------------------------ // Add content to struct for content persistance // ------------------------------------------------------------------------ function addContent(address contentCreator, uint256 articleId, uint256 subArticleId, uint256 contentId, uint256 timestamp, string memory data) onlyModerators public { //Add contentId to list of already added contents if(contentIdExists[contentId] == false){ uniqueContentIds.push(contentId); contentIdExists[contentId] = true; } //Add the data contentById[contentId] = data; //Map the articleId to the contentId if(articleContentIds[articleId].containsContentId[contentId] == false){ articleContentIds[articleId].exists = true; articleContentIds[articleId].contentIds.push(contentId); articleContentIds[articleId].containsContentId[contentId] = true; } //Map the subArticleId to the contentId if(subArticleContentIds[subArticleId].containsContentId[contentId] == false){ articleContentIds[articleId].exists = true; subArticleContentIds[subArticleId].contentIds.push(contentId); subArticleContentIds[subArticleId].containsContentId[contentId] = true; } //Add event (everything but content) emit ContentAdded(contentCreator, articleId, subArticleId, contentId, timestamp); } // ------------------------------------------------------------------------ // Get Content by contentId // ------------------------------------------------------------------------ function getContentById(uint256 contentId) public view returns(string memory) { return contentById[contentId]; } // ------------------------------------------------------------------------ // Get all content ids // ------------------------------------------------------------------------ function getAllContentIds() public view returns(uint256[] memory) { return uniqueContentIds; } // ------------------------------------------------------------------------ // Get all content count // ------------------------------------------------------------------------ function getAllContentCount() public view returns(uint256) { return uniqueContentIds.length; } // ------------------------------------------------------------------------ // Get all content ids for article // ------------------------------------------------------------------------ function getAllContentIdsForArticle(uint256 articleId) public view returns(uint256[] memory) { return articleContentIds[articleId].contentIds; } // ------------------------------------------------------------------------ // Count content for article // ------------------------------------------------------------------------ function countContentForArticle(uint256 articleId) public view returns(uint256) { return articleContentIds[articleId].contentIds.length; } // ------------------------------------------------------------------------ // Get all content ids for sub-article // ------------------------------------------------------------------------ function getAllContentIdsForSubArticle(uint256 subArticleId) public view returns(uint256[] memory) { return subArticleContentIds[subArticleId].contentIds; } // ------------------------------------------------------------------------ // Count content for sub-article // ------------------------------------------------------------------------ function countContentForSubArticle(uint256 subArticleId) public view returns(uint256 count) { return subArticleContentIds[subArticleId].contentIds.length; } // ------------------------------------------------------------------------ // Get page for sub article (page starts at 0) ~ all to avoid experimental // ------------------------------------------------------------------------ function getPageForSubArticle(uint256 subArticleId, uint256 page) public view returns(string memory pageItem1, string memory pageItem2, string memory pageItem3, string memory pageItem4, string memory pageItem5, string memory pageItem6, string memory pageItem7) { string[] memory contentToReturn = new string[](perPage); uint256[] memory contentIds = subArticleContentIds[subArticleId].contentIds; uint256 index = page.mul(perPage.sub(1)); for(uint256 i=0; i<perPage;i++){ contentToReturn[i] = contentById[contentIds[index.add(i)]]; } pageItem1 = contentToReturn[0]; pageItem2 = contentToReturn[1]; pageItem3 = contentToReturn[2]; pageItem4 = contentToReturn[3]; pageItem5 = contentToReturn[4]; pageItem6 = contentToReturn[5]; pageItem7 = contentToReturn[6]; } // ------------------------------------------------------------------------ // Get page for article (page starts at 0) ~ all to avoid experimental // ------------------------------------------------------------------------ function getPageForArticle(uint256 articleId, uint256 page) public view returns(string memory pageItem1, string memory pageItem2, string memory pageItem3, string memory pageItem4, string memory pageItem5, string memory pageItem6, string memory pageItem7) { string[] memory contentToReturn = new string[](perPage); uint256[] memory contentIds = articleContentIds[articleId].contentIds; uint256 index = page.mul(perPage.sub(1)); for(uint256 i=0; i<perPage;i++){ contentToReturn[i] = contentById[contentIds[index.add(i)]]; } pageItem1 = contentToReturn[0]; pageItem2 = contentToReturn[1]; pageItem3 = contentToReturn[2]; pageItem4 = contentToReturn[3]; pageItem5 = contentToReturn[4]; pageItem6 = contentToReturn[5]; pageItem7 = contentToReturn[6]; } } // ------------------------------------------------------------------------ // Morality token definition // ------------------------------------------------------------------------ contract Morality is ERC20, StorageToken { string public name; string public symbol; uint256 public decimals; address payable public creator; event LogFundsReceived(address sender, uint amount); event WithdrawLog(uint256 balanceBefore, uint256 amount, uint256 balanceAfter); event UpdatedTokenInformation(string newName, string newSymbol); // ------------------------------------------------------------------------ // Constructor to allow total tokens minted (upon creation) to be set // Name and Symbol can be changed via SetInfo (decided to remove from constructor) // ------------------------------------------------------------------------ constructor(uint256 _totalTokensToMint) payable public { name = "Morality"; symbol = "MO"; totalSupply = _totalTokensToMint; decimals = 18; balances[msg.sender] = totalSupply; creator = msg.sender; emit LogFundsReceived(msg.sender, msg.value); } // ------------------------------------------------------------------------ // Payable method allowing ether to be stored in the contract // ------------------------------------------------------------------------ function() payable external { emit LogFundsReceived(msg.sender, msg.value); } // ------------------------------------------------------------------------ // Transfer token (availabe to all) // ------------------------------------------------------------------------ function transfer(address _to, uint256 _value) public returns (bool success){ return super.transfer(_to, _value); } // ------------------------------------------------------------------------ // Add content via event to event for content persistance (cheap) // ------------------------------------------------------------------------ function addContentViaEvent(address contentCreator, uint256 articleId, uint256 subArticleId, uint256 contentId, uint256 timestamp, string memory data) onlyModerators public { super.addContentViaEvent(contentCreator, articleId, subArticleId, contentId, timestamp, data); } // ------------------------------------------------------------------------ // Add content for content persistance (expensive) // ------------------------------------------------------------------------ function addContent(address contentCreator, uint256 articleId, uint256 subArticleId, uint256 contentId, uint256 timestamp, string memory data) onlyModerators public { super.addContent(contentCreator, articleId, subArticleId, contentId, timestamp, data); } // ------------------------------------------------------------------------ // Update token information // ------------------------------------------------------------------------ function setTokenInformation(string memory _name, string memory _symbol) onlyOwner public { require(msg.sender != creator); name = _name; symbol = _symbol; emit UpdatedTokenInformation(name, symbol); } // ------------------------------------------------------------------------ // Withdraw ether from the contract // ------------------------------------------------------------------------ function withdraw(uint256 amount) onlyOwner public returns(bool){ require(amount <= address(this).balance); address(owner).transfer(amount); emit WithdrawLog(address(owner).balance.sub(amount), amount, address(owner).balance); return true; } // ------------------------------------------------------------------------ // Mint token // ------------------------------------------------------------------------ function mintToken(address target, uint256 mintedAmount) onlyOwner public returns (bool){ return super.mintToken(target, mintedAmount); } // ------------------------------------------------------------------------ // Burn token (send to burn address) // ------------------------------------------------------------------------ function burn(uint256 burnAmount) onlyOwner public{ return super.burn(burnAmount); } // ------------------------------------------------------------------------ // To remove contract from blockchain // ------------------------------------------------------------------------ function deprecateContract() onlyOwner public{ selfdestruct(creator); } }
------------------------------------------------------------------------ Create tokens by adding to total supply and crediting the admin/owner ------------------------------------------------------------------------
function mintToken(address _target, uint256 _mintedAmount) public returns(bool){ balances[_target] = balances[_target].add(_mintedAmount); totalSupply = totalSupply.add(_mintedAmount); emit Minted(_target, _mintedAmount); emit Transfer(address(0), address(this), _mintedAmount); emit Transfer(address(this), _target, _mintedAmount); return true; }
1,780,715
// SPDX-License-Identifier: MIT pragma solidity 0.5.6; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/SignedSafeMath.sol"; import "../libraries/SafeCast.sol"; import "../interfaces/IRewarder.sol"; import "../codes/Ownable.sol"; import "../CLA/ClaimToken.sol"; import "../interfaces/IMiningTreasury.sol"; /** * @title CLA MasterChef of CLS. * distribute CLA tokens to CLS holders * * * References: * * - https://github.com/sushiswap/sushiswap/blob/canary/contracts/MasterChefV2.sol */ contract ClaDistributor is Ownable { using SafeMath for uint256; using SignedSafeMath for int256; using SafeCast for uint256; using SafeCast for int256; using SafeERC20 for IERC20; struct PoolInfo { uint256 accClaPerShare; uint256 lastRewardBlock; } /// @notice Info of each user's rewardDebt. /// `rewardDebt` The amount of CLA entitled to the user. mapping(address => int256) public rewardDebt; /// @notice Address of CLS contract. address public cls; /// @notice Address of CLA contract. ClaimToken public cla; /// @notice treasury address of CLA tokens. IMiningTreasury public miningTreasury; /// @notice Address of `IRewarder` contract. IRewarder public rewarder; /// @notice Info of pool. PoolInfo public poolInfo; /// @notice Block at the start of CLA mining uint256 public startBlock; /// @notice Reward ratio between LP staker and CLA staker uint256 public clsRewardRatio; uint256 public bonusEndBlock; uint256 private constant BONUS_MULTIPLIER = 2; uint256 private constant CLA_REWARD_RATIO_DIVISOR = 1e12; uint256 private constant ACC_CLA_PRECISION = 1e12; uint256 private constant YEAR = 12 * 30 * 24 * 60 * 60; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event Harvest(address indexed user, uint256 amount, address indexed to); event UpdatePool(uint256 clsSupply, uint256 accClaPerShare); event UpdateClsRewardRatio(uint256 clsRewardRatio); event SetRewarder(address indexed rewarder); /// @param cls_ The CLS token contract address. /// @param cla_ The CLA token contract address. /// @param miningTreasury_ Contract address of CLA treasury. /// @param rewarder_ Contract address of Airdroper. /// @param startBlock_ Start block of masterChef. (must be same to masterChef's one) /// @param migrationEndBlock_ Migration end block of masterChef. (must be same to masterChef's one) constructor( address cls_, ClaimToken cla_, IMiningTreasury miningTreasury_, IRewarder rewarder_, uint256 startBlock_, uint256 migrationEndBlock_ ) public { cls = cls_; cla = cla_; miningTreasury = miningTreasury_; rewarder = rewarder_; poolInfo.lastRewardBlock = migrationEndBlock_; startBlock = startBlock_; bonusEndBlock = migrationEndBlock_.add( migrationEndBlock_.sub(startBlock_) ); } /// @notice Number of tokens created per block. function claPerBlock() public view returns (uint256) { return _claPerBlock(block.number); } /// @notice Number of tokens created per block. function _claPerBlock(uint256 blockNumber) internal view returns (uint256) { if (blockNumber < startBlock + 2 * YEAR) { return ((9e17 / CLA_REWARD_RATIO_DIVISOR) * clsRewardRatio); } else if (blockNumber < startBlock + 2 * 2 * YEAR) { return ((6e17 / CLA_REWARD_RATIO_DIVISOR) * clsRewardRatio); } else if (blockNumber < startBlock + 2 * 3 * YEAR) { return ((3e17 / CLA_REWARD_RATIO_DIVISOR) * clsRewardRatio); } else { return 0; } } /// @notice Number of tokens created between the given _from to _to blocks. function claPerBlocks(uint256 from, uint256 to) public view returns (uint256) { require(from <= to); if (from < bonusEndBlock) { uint256 claPerBlockFrom = _claPerBlock(from).mul(BONUS_MULTIPLIER); uint256 claPerBlockTo = _claPerBlock(to); if (to <= bonusEndBlock) { return to.sub(from).mul(claPerBlockFrom); } return claPerBlockFrom.mul(bonusEndBlock.sub(from)).add( claPerBlockTo.mul(to.sub(bonusEndBlock)) ); } else { uint256 claPerBlockFrom = _claPerBlock(from); uint256 claPerBlockTo = _claPerBlock(to); if (claPerBlockFrom == claPerBlockTo) return to.sub(from).mul(claPerBlockFrom); uint256 boundary = (to.sub(startBlock) / (2 * YEAR)).mul(2 * YEAR).add( startBlock ); return claPerBlockFrom.mul(boundary.sub(from)).add( claPerBlockTo.mul(to.sub(boundary)) ); } } /// @notice Set cls reward ratio. /// @param clsRewardRatio_ Cls reward ratio. /// @param withUpdate Update pool flag. function setClsRewardRatio(uint256 clsRewardRatio_, bool withUpdate) public { require(msg.sender == address(miningTreasury), "not mining treasury"); if (withUpdate) { updatePool(); } clsRewardRatio = clsRewardRatio_; emit UpdateClsRewardRatio(clsRewardRatio); } /// @notice View function to see pending CLA. /// @param user Address of user. /// @return Pending CLA reward for a given user. function pendingCla(address user) external view returns (uint256 pending) { uint256 accClaPerShare = poolInfo.accClaPerShare; uint256 clsSupply = IERC20(cls).totalSupply(); if (block.number > poolInfo.lastRewardBlock && clsSupply != 0) { uint256 claReward = claPerBlocks( poolInfo.lastRewardBlock, block.number ); if (claReward != 0) { accClaPerShare = accClaPerShare.add( (claReward.mul(ACC_CLA_PRECISION) / clsSupply) ); } } pending = int256( IERC20(cls).balanceOf(user).mul(accClaPerShare) / ACC_CLA_PRECISION ).sub(rewardDebt[user]).toUint256(); } /// @notice Update accumulated reward per block of the pool. function updatePool() public { if (block.number > poolInfo.lastRewardBlock) { uint256 clsSupply = IERC20(cls).totalSupply(); if (clsSupply > 0) { uint256 claReward = claPerBlocks( poolInfo.lastRewardBlock, block.number ); if (claReward != 0) { miningTreasury.transfer(claReward); poolInfo.accClaPerShare = poolInfo.accClaPerShare.add( (claReward.mul(ACC_CLA_PRECISION) / clsSupply) ); } } poolInfo.lastRewardBlock = block.number; emit UpdatePool(clsSupply, poolInfo.accClaPerShare); } } /// @notice Deposit CLS tokens. /// @param user The receiver of `amount` deposit benefit. /// @param amount CLS token amount to deposit. function deposit(address user, uint256 amount) public { require(msg.sender == cls); updatePool(); rewardDebt[user] = rewardDebt[user].add( int256(amount.mul(poolInfo.accClaPerShare) / ACC_CLA_PRECISION) ); IRewarder _rewarder = rewarder; if (address(_rewarder) != address(0)) { _rewarder.onClaReward(0, user, user, 0, IERC20(cls).balanceOf(user)); } emit Deposit(user, amount); } /// @notice Withdraw CLS tokens. /// @param user Receiver of the CLS tokens. /// @param amount CLS token amount to withdraw. function withdraw(address user, uint256 amount) public { require(msg.sender == cls); updatePool(); rewardDebt[user] = rewardDebt[user].sub( int256(amount.mul(poolInfo.accClaPerShare) / ACC_CLA_PRECISION) ); IRewarder _rewarder = rewarder; if (address(_rewarder) != address(0)) { _rewarder.onClaReward(0, user, user, 0, IERC20(cls).balanceOf(user)); } emit Withdraw(user, amount); } /// @dev Harvest proceeds for transaction sender to `to`. /// @param to Receiver of CLA rewards. function harvest(address to) public { updatePool(); PoolInfo memory pool = poolInfo; int256 accumulatedCla = int256( IERC20(cls).balanceOf(msg.sender).mul(pool.accClaPerShare) / ACC_CLA_PRECISION ); uint256 _pendingCla = accumulatedCla .sub(rewardDebt[msg.sender]) .toUint256(); rewardDebt[msg.sender] = accumulatedCla; if (_pendingCla != 0) { _safeClaTransfer(to, _pendingCla); } IRewarder _rewarder = rewarder; if (address(_rewarder) != address(0)) { _rewarder.onClaReward( 0, msg.sender, to, _pendingCla, IERC20(cls).balanceOf(msg.sender) ); } emit Harvest(msg.sender, _pendingCla, to); } /// @notice Safe CLA transfer function, just in case if rounding error causes pool to not have enough CLAs. /// @param to Address of cla reciever /// @param amount Amount of cla to transfer function _safeClaTransfer(address to, uint256 amount) internal { uint256 claBalance = cla.balanceOf(address(this)); if (amount > claBalance) { cla.transfer(to, claBalance); } else { cla.transfer(to, amount); } } /// @notice Set Rewarder (airdroper) function setRewarder(IRewarder rewarder_) public onlyOwner { rewarder = rewarder_; emit SetRewarder(address(rewarder)); } /// @notice Set MiningTreasury function setMiningTreasury(IMiningTreasury miningTreasury_) public onlyOwner { miningTreasury = miningTreasury_; } }
Number of tokens created per block.
function _claPerBlock(uint256 blockNumber) internal view returns (uint256) { if (blockNumber < startBlock + 2 * YEAR) { return ((9e17 / CLA_REWARD_RATIO_DIVISOR) * clsRewardRatio); return ((6e17 / CLA_REWARD_RATIO_DIVISOR) * clsRewardRatio); return ((3e17 / CLA_REWARD_RATIO_DIVISOR) * clsRewardRatio); return 0; } }
13,037,228
./full_match/1/0x7132c10A5fDeb8236Be65F451c1973E26E8515EF/sources/contracts/token/ERC721/extensions/ERC721zUpgradeable.sol
Initializes the contract. Created for future use./
function __ERC721z_init() internal onlyInitializing { }
3,072,474
/** Source code of Opium Protocol Web https://opium.network Telegram https://t.me/opium_network Twitter https://twitter.com/opium_network */ // File: LICENSE /** The software and documentation available in this repository (the "Software") is protected by copyright law and accessible pursuant to the license set forth below. Copyright © 2020 Blockeys BV. All rights reserved. Permission is hereby granted, free of charge, to any person or organization obtaining the Software (the “Licensee”) to privately study, review, and analyze the Software. Licensee shall not use the Software for any other purpose. Licensee shall not modify, transfer, assign, share, or sub-license the Software or any derivative works of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // File: contracts/Lib/LibDerivative.sol pragma solidity 0.5.16; pragma experimental ABIEncoderV2; /// @title Opium.Lib.LibDerivative contract should be inherited by contracts that use Derivative structure and calculate derivativeHash contract LibDerivative { // Opium derivative structure (ticker) definition struct Derivative { // Margin parameter for syntheticId uint256 margin; // Maturity of derivative uint256 endTime; // Additional parameters for syntheticId uint256[] params; // oracleId of derivative address oracleId; // Margin token address of derivative address token; // syntheticId of derivative address syntheticId; } /// @notice Calculates hash of provided Derivative /// @param _derivative Derivative Instance of derivative to hash /// @return derivativeHash bytes32 Derivative hash function getDerivativeHash(Derivative memory _derivative) public pure returns (bytes32 derivativeHash) { derivativeHash = keccak256(abi.encodePacked( _derivative.margin, _derivative.endTime, _derivative.params, _derivative.oracleId, _derivative.token, _derivative.syntheticId )); } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: openzeppelin-solidity/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * 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-solidity/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.5.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. */ contract ReentrancyGuard { // counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } // File: erc721o/contracts/Libs/LibPosition.sol pragma solidity ^0.5.4; library LibPosition { function getLongTokenId(bytes32 _hash) public pure returns (uint256 tokenId) { tokenId = uint256(keccak256(abi.encodePacked(_hash, "LONG"))); } function getShortTokenId(bytes32 _hash) public pure returns (uint256 tokenId) { tokenId = uint256(keccak256(abi.encodePacked(_hash, "SHORT"))); } } // File: contracts/Interface/IDerivativeLogic.sol pragma solidity 0.5.16; /// @title Opium.Interface.IDerivativeLogic contract is an interface that every syntheticId should implement contract IDerivativeLogic is LibDerivative { /// @notice Validates ticker /// @param _derivative Derivative Instance of derivative to validate /// @return Returns boolean whether ticker is valid function validateInput(Derivative memory _derivative) public view returns (bool); /// @notice Calculates margin required for derivative creation /// @param _derivative Derivative Instance of derivative /// @return buyerMargin uint256 Margin needed from buyer (LONG position) /// @return sellerMargin uint256 Margin needed from seller (SHORT position) function getMargin(Derivative memory _derivative) public view returns (uint256 buyerMargin, uint256 sellerMargin); /// @notice Calculates payout for derivative execution /// @param _derivative Derivative Instance of derivative /// @param _result uint256 Data retrieved from oracleId on the maturity /// @return buyerPayout uint256 Payout in ratio for buyer (LONG position holder) /// @return sellerPayout uint256 Payout in ratio for seller (SHORT position holder) function getExecutionPayout(Derivative memory _derivative, uint256 _result) public view returns (uint256 buyerPayout, uint256 sellerPayout); /// @notice Returns syntheticId author address for Opium commissions /// @return authorAddress address The address of syntheticId address function getAuthorAddress() public view returns (address authorAddress); /// @notice Returns syntheticId author commission in base of COMMISSION_BASE /// @return commission uint256 Author commission function getAuthorCommission() public view returns (uint256 commission); /// @notice Returns whether thirdparty could execute on derivative's owner's behalf /// @param _derivativeOwner address Derivative owner address /// @return Returns boolean whether _derivativeOwner allowed third party execution function thirdpartyExecutionAllowed(address _derivativeOwner) public view returns (bool); /// @notice Returns whether syntheticId implements pool logic /// @return Returns whether syntheticId implements pool logic function isPool() public view returns (bool); /// @notice Sets whether thirds parties are allowed or not to execute derivative's on msg.sender's behalf /// @param _allow bool Flag for execution allowance function allowThirdpartyExecution(bool _allow) public; // Event with syntheticId metadata JSON string (for DIB.ONE derivative explorer) event MetadataSet(string metadata); } // File: contracts/Errors/CoreErrors.sol pragma solidity 0.5.16; contract CoreErrors { string constant internal ERROR_CORE_NOT_POOL = "CORE:NOT_POOL"; string constant internal ERROR_CORE_CANT_BE_POOL = "CORE:CANT_BE_POOL"; string constant internal ERROR_CORE_TICKER_WAS_CANCELLED = "CORE:TICKER_WAS_CANCELLED"; string constant internal ERROR_CORE_SYNTHETIC_VALIDATION_ERROR = "CORE:SYNTHETIC_VALIDATION_ERROR"; string constant internal ERROR_CORE_NOT_ENOUGH_TOKEN_ALLOWANCE = "CORE:NOT_ENOUGH_TOKEN_ALLOWANCE"; string constant internal ERROR_CORE_TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH = "CORE:TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH"; string constant internal ERROR_CORE_TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH = "CORE:TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH"; string constant internal ERROR_CORE_EXECUTION_BEFORE_MATURITY_NOT_ALLOWED = "CORE:EXECUTION_BEFORE_MATURITY_NOT_ALLOWED"; string constant internal ERROR_CORE_SYNTHETIC_EXECUTION_WAS_NOT_ALLOWED = "CORE:SYNTHETIC_EXECUTION_WAS_NOT_ALLOWED"; string constant internal ERROR_CORE_INSUFFICIENT_POOL_BALANCE = "CORE:INSUFFICIENT_POOL_BALANCE"; string constant internal ERROR_CORE_CANT_CANCEL_DUMMY_ORACLE_ID = "CORE:CANT_CANCEL_DUMMY_ORACLE_ID"; string constant internal ERROR_CORE_CANCELLATION_IS_NOT_ALLOWED = "CORE:CANCELLATION_IS_NOT_ALLOWED"; string constant internal ERROR_CORE_UNKNOWN_POSITION_TYPE = "CORE:UNKNOWN_POSITION_TYPE"; } // File: contracts/Errors/RegistryErrors.sol pragma solidity 0.5.16; contract RegistryErrors { string constant internal ERROR_REGISTRY_ONLY_INITIALIZER = "REGISTRY:ONLY_INITIALIZER"; string constant internal ERROR_REGISTRY_ONLY_OPIUM_ADDRESS_ALLOWED = "REGISTRY:ONLY_OPIUM_ADDRESS_ALLOWED"; string constant internal ERROR_REGISTRY_CANT_BE_ZERO_ADDRESS = "REGISTRY:CANT_BE_ZERO_ADDRESS"; string constant internal ERROR_REGISTRY_ALREADY_SET = "REGISTRY:ALREADY_SET"; } // File: contracts/Registry.sol pragma solidity 0.5.16; /// @title Opium.Registry contract keeps addresses of deployed Opium contracts set to allow them route and communicate to each other contract Registry is RegistryErrors { // Address of Opium.TokenMinter contract address private minter; // Address of Opium.Core contract address private core; // Address of Opium.OracleAggregator contract address private oracleAggregator; // Address of Opium.SyntheticAggregator contract address private syntheticAggregator; // Address of Opium.TokenSpender contract address private tokenSpender; // Address of Opium commission receiver address private opiumAddress; // Address of Opium contract set deployer address public initializer; /// @notice This modifier restricts access to functions, which could be called only by initializer modifier onlyInitializer() { require(msg.sender == initializer, ERROR_REGISTRY_ONLY_INITIALIZER); _; } /// @notice Sets initializer constructor() public { initializer = msg.sender; } // SETTERS /// @notice Sets Opium.TokenMinter, Opium.Core, Opium.OracleAggregator, Opium.SyntheticAggregator, Opium.TokenSpender, Opium commission receiver addresses and allows to do it only once /// @param _minter address Address of Opium.TokenMinter /// @param _core address Address of Opium.Core /// @param _oracleAggregator address Address of Opium.OracleAggregator /// @param _syntheticAggregator address Address of Opium.SyntheticAggregator /// @param _tokenSpender address Address of Opium.TokenSpender /// @param _opiumAddress address Address of Opium commission receiver function init( address _minter, address _core, address _oracleAggregator, address _syntheticAggregator, address _tokenSpender, address _opiumAddress ) external onlyInitializer { require( minter == address(0) && core == address(0) && oracleAggregator == address(0) && syntheticAggregator == address(0) && tokenSpender == address(0) && opiumAddress == address(0), ERROR_REGISTRY_ALREADY_SET ); require( _minter != address(0) && _core != address(0) && _oracleAggregator != address(0) && _syntheticAggregator != address(0) && _tokenSpender != address(0) && _opiumAddress != address(0), ERROR_REGISTRY_CANT_BE_ZERO_ADDRESS ); minter = _minter; core = _core; oracleAggregator = _oracleAggregator; syntheticAggregator = _syntheticAggregator; tokenSpender = _tokenSpender; opiumAddress = _opiumAddress; } /// @notice Allows opium commission receiver address to change itself /// @param _opiumAddress address New opium commission receiver address function changeOpiumAddress(address _opiumAddress) external { require(opiumAddress == msg.sender, ERROR_REGISTRY_ONLY_OPIUM_ADDRESS_ALLOWED); require(_opiumAddress != address(0), ERROR_REGISTRY_CANT_BE_ZERO_ADDRESS); opiumAddress = _opiumAddress; } // GETTERS /// @notice Returns address of Opium.TokenMinter /// @param result address Address of Opium.TokenMinter function getMinter() external view returns (address result) { return minter; } /// @notice Returns address of Opium.Core /// @param result address Address of Opium.Core function getCore() external view returns (address result) { return core; } /// @notice Returns address of Opium.OracleAggregator /// @param result address Address of Opium.OracleAggregator function getOracleAggregator() external view returns (address result) { return oracleAggregator; } /// @notice Returns address of Opium.SyntheticAggregator /// @param result address Address of Opium.SyntheticAggregator function getSyntheticAggregator() external view returns (address result) { return syntheticAggregator; } /// @notice Returns address of Opium.TokenSpender /// @param result address Address of Opium.TokenSpender function getTokenSpender() external view returns (address result) { return tokenSpender; } /// @notice Returns address of Opium commission receiver /// @param result address Address of Opium commission receiver function getOpiumAddress() external view returns (address result) { return opiumAddress; } } // File: contracts/Errors/UsingRegistryErrors.sol pragma solidity 0.5.16; contract UsingRegistryErrors { string constant internal ERROR_USING_REGISTRY_ONLY_CORE_ALLOWED = "USING_REGISTRY:ONLY_CORE_ALLOWED"; } // File: contracts/Lib/UsingRegistry.sol pragma solidity 0.5.16; /// @title Opium.Lib.UsingRegistry contract should be inherited by contracts, that are going to use Opium.Registry contract UsingRegistry is UsingRegistryErrors { // Emitted when registry instance is set event RegistrySet(address registry); // Instance of Opium.Registry contract Registry internal registry; /// @notice This modifier restricts access to functions, which could be called only by Opium.Core modifier onlyCore() { require(msg.sender == registry.getCore(), ERROR_USING_REGISTRY_ONLY_CORE_ALLOWED); _; } /// @notice Defines registry instance and emits appropriate event constructor(address _registry) public { registry = Registry(_registry); emit RegistrySet(_registry); } /// @notice Getter for registry variable /// @return address Address of registry set in current contract function getRegistry() external view returns (address) { return address(registry); } } // File: contracts/Lib/LibCommission.sol pragma solidity 0.5.16; /// @title Opium.Lib.LibCommission contract defines constants for Opium commissions contract LibCommission { // Represents 100% base for commissions calculation uint256 constant public COMMISSION_BASE = 10000; // Represents 100% base for Opium commission uint256 constant public OPIUM_COMMISSION_BASE = 10; // Represents which part of `syntheticId` author commissions goes to opium uint256 constant public OPIUM_COMMISSION_PART = 1; } // File: openzeppelin-solidity/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: erc721o/contracts/Libs/UintArray.sol pragma solidity ^0.5.4; library UintArray { function indexOf(uint256[] memory A, uint256 a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (0, false); } function contains(uint256[] memory A, uint256 a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } function difference(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory, uint256[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 count = 0; // First count the new length because can't push for in-memory arrays for (uint256 i = 0; i < length; i++) { uint256 e = A[i]; if (!contains(B, e)) { includeMap[i] = true; count++; } } uint256[] memory newUints = new uint256[](count); uint256[] memory newUintsIdxs = new uint256[](count); uint256 j = 0; for (uint256 i = 0; i < length; i++) { if (includeMap[i]) { newUints[j] = A[i]; newUintsIdxs[j] = i; j++; } } return (newUints, newUintsIdxs); } function intersect(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory, uint256[] memory, uint256[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 newLength = 0; for (uint256 i = 0; i < length; i++) { if (contains(B, A[i])) { includeMap[i] = true; newLength++; } } uint256[] memory newUints = new uint256[](newLength); uint256[] memory newUintsAIdxs = new uint256[](newLength); uint256[] memory newUintsBIdxs = new uint256[](newLength); uint256 j = 0; for (uint256 i = 0; i < length; i++) { if (includeMap[i]) { newUints[j] = A[i]; newUintsAIdxs[j] = i; (newUintsBIdxs[j], ) = indexOf(B, A[i]); j++; } } return (newUints, newUintsAIdxs, newUintsBIdxs); } function isUnique(uint256[] memory A) internal pure returns (bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { (uint256 idx, bool isIn) = indexOf(A, A[i]); if (isIn && idx < i) { return false; } } return true; } } // File: openzeppelin-solidity/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-solidity/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-solidity/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: erc721o/contracts/Interfaces/IERC721O.sol pragma solidity ^0.5.4; contract IERC721O { // Token description function name() external view returns (string memory); function symbol() external view returns (string memory); function totalSupply() public view returns (uint256); function exists(uint256 _tokenId) public view returns (bool); function implementsERC721() public pure returns (bool); function tokenByIndex(uint256 _index) public view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId); function tokenURI(uint256 _tokenId) public view returns (string memory tokenUri); function getApproved(uint256 _tokenId) public view returns (address); function implementsERC721O() public pure returns (bool); function ownerOf(uint256 _tokenId) public view returns (address _owner); function balanceOf(address owner) public view returns (uint256); function balanceOf(address _owner, uint256 _tokenId) public view returns (uint256); function tokensOwned(address _owner) public view returns (uint256[] memory, uint256[] memory); // Non-Fungible Safe Transfer From function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public; // Non-Fungible Unsafe Transfer From function transferFrom(address _from, address _to, uint256 _tokenId) public; // Fungible Unsafe Transfer function transfer(address _to, uint256 _tokenId, uint256 _quantity) public; // Fungible Unsafe Transfer From function transferFrom(address _from, address _to, uint256 _tokenId, uint256 _quantity) public; // Fungible Safe Transfer From function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount, bytes memory _data) public; // Fungible Safe Batch Transfer From function safeBatchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts) public; function safeBatchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts, bytes memory _data) public; // Fungible Unsafe Batch Transfer From function batchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts) public; // Approvals function setApprovalForAll(address _operator, bool _approved) public; function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId, address _tokenOwner) public view returns (address); function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator); function isApprovedOrOwner(address _spender, address _owner, uint256 _tokenId) public view returns (bool); function permit(address _holder, address _spender, uint256 _nonce, uint256 _expiry, bool _allowed, bytes calldata _signature) external; // Composable function compose(uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public; function decompose(uint256 _portfolioId, uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public; function recompose(uint256 _portfolioId, uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity) public; // Required Events event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event TransferWithQuantity(address indexed from, address indexed to, uint256 indexed tokenId, uint256 quantity); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); event BatchTransfer(address indexed from, address indexed to, uint256[] tokenTypes, uint256[] amounts); event Composition(uint256 portfolioId, uint256[] tokenIds, uint256[] tokenRatio); } // File: erc721o/contracts/Interfaces/IERC721OReceiver.sol pragma solidity ^0.5.4; /** * @title ERC721O token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721O contracts. */ contract IERC721OReceiver { /** * @dev Magic value to be returned upon successful reception of an amount of ERC721O tokens * ERC721O_RECEIVED = `bytes4(keccak256("onERC721OReceived(address,address,uint256,uint256,bytes)"))` = 0xf891ffe0 * ERC721O_BATCH_RECEIVED = `bytes4(keccak256("onERC721OBatchReceived(address,address,uint256[],uint256[],bytes)"))` = 0xd0e17c0b */ bytes4 constant internal ERC721O_RECEIVED = 0xf891ffe0; bytes4 constant internal ERC721O_BATCH_RECEIVED = 0xd0e17c0b; function onERC721OReceived( address _operator, address _from, uint256 tokenId, uint256 amount, bytes memory data ) public returns(bytes4); function onERC721OBatchReceived( address _operator, address _from, uint256[] memory _types, uint256[] memory _amounts, bytes memory _data ) public returns (bytes4); } // File: erc721o/contracts/Libs/ObjectsLib.sol pragma solidity ^0.5.4; library ObjectLib { // Libraries using SafeMath for uint256; enum Operations { ADD, SUB, REPLACE } // Constants regarding bin or chunk sizes for balance packing uint256 constant TYPES_BITS_SIZE = 32; // Max size of each object uint256 constant TYPES_PER_UINT256 = 256 / TYPES_BITS_SIZE; // Number of types per uint256 // // Objects and Tokens Functions // /** * @dev Return the bin number and index within that bin where ID is * @param _tokenId Object type * @return (Bin number, ID's index within that bin) */ function getTokenBinIndex(uint256 _tokenId) internal pure returns (uint256 bin, uint256 index) { bin = _tokenId * TYPES_BITS_SIZE / 256; index = _tokenId % TYPES_PER_UINT256; return (bin, index); } /** * @dev update the balance of a type provided in _binBalances * @param _binBalances Uint256 containing the balances of objects * @param _index Index of the object in the provided bin * @param _amount Value to update the type balance * @param _operation Which operation to conduct : * Operations.REPLACE : Replace type balance with _amount * Operations.ADD : ADD _amount to type balance * Operations.SUB : Substract _amount from type balance */ function updateTokenBalance( uint256 _binBalances, uint256 _index, uint256 _amount, Operations _operation) internal pure returns (uint256 newBinBalance) { uint256 objectBalance; if (_operation == Operations.ADD) { objectBalance = getValueInBin(_binBalances, _index); newBinBalance = writeValueInBin(_binBalances, _index, objectBalance.add(_amount)); } else if (_operation == Operations.SUB) { objectBalance = getValueInBin(_binBalances, _index); newBinBalance = writeValueInBin(_binBalances, _index, objectBalance.sub(_amount)); } else if (_operation == Operations.REPLACE) { newBinBalance = writeValueInBin(_binBalances, _index, _amount); } else { revert("Invalid operation"); // Bad operation } return newBinBalance; } /* * @dev return value in _binValue at position _index * @param _binValue uint256 containing the balances of TYPES_PER_UINT256 types * @param _index index at which to retrieve value * @return Value at given _index in _bin */ function getValueInBin(uint256 _binValue, uint256 _index) internal pure returns (uint256) { // Mask to retrieve data for a given binData uint256 mask = (uint256(1) << TYPES_BITS_SIZE) - 1; // Shift amount uint256 rightShift = 256 - TYPES_BITS_SIZE * (_index + 1); return (_binValue >> rightShift) & mask; } /** * @dev return the updated _binValue after writing _amount at _index * @param _binValue uint256 containing the balances of TYPES_PER_UINT256 types * @param _index Index at which to retrieve value * @param _amount Value to store at _index in _bin * @return Value at given _index in _bin */ function writeValueInBin(uint256 _binValue, uint256 _index, uint256 _amount) internal pure returns (uint256) { require(_amount < 2**TYPES_BITS_SIZE, "Amount to write in bin is too large"); // Mask to retrieve data for a given binData uint256 mask = (uint256(1) << TYPES_BITS_SIZE) - 1; // Shift amount uint256 leftShift = 256 - TYPES_BITS_SIZE * (_index + 1); return (_binValue & ~(mask << leftShift) ) | (_amount << leftShift); } } // File: erc721o/contracts/ERC721OBase.sol pragma solidity ^0.5.4; contract ERC721OBase is IERC721O, ERC165, IERC721 { // Libraries using ObjectLib for ObjectLib.Operations; using ObjectLib for uint256; // Array with all tokenIds uint256[] internal allTokens; // Packed balances mapping(address => mapping(uint256 => uint256)) internal packedTokenBalance; // Operators mapping(address => mapping(address => bool)) internal operators; // Keeps aprovals for tokens from owner to approved address // tokenApprovals[tokenId][owner] = approved mapping (uint256 => mapping (address => address)) internal tokenApprovals; // Token Id state mapping(uint256 => uint256) internal tokenTypes; uint256 constant internal INVALID = 0; uint256 constant internal POSITION = 1; uint256 constant internal PORTFOLIO = 2; // Interface constants bytes4 internal constant INTERFACE_ID_ERC721O = 0x12345678; // EIP712 constants bytes32 public DOMAIN_SEPARATOR; bytes32 public PERMIT_TYPEHASH; // mapping holds nonces for approval permissions // nonces[holder] => nonce mapping (address => uint) public nonces; modifier isOperatorOrOwner(address _from) { require((msg.sender == _from) || operators[_from][msg.sender], "msg.sender is neither _from nor operator"); _; } constructor() public { _registerInterface(INTERFACE_ID_ERC721O); // Calculate EIP712 constants DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,address verifyingContract)"), keccak256(bytes("ERC721o")), keccak256(bytes("1")), address(this) )); PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)"); } function implementsERC721O() public pure returns (bool) { return true; } /** * @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) { return tokenTypes[_tokenId] != INVALID; } /** * @dev return the _tokenId type' balance of _address * @param _address Address to query balance of * @param _tokenId type to query balance of * @return Amount of objects of a given type ID */ function balanceOf(address _address, uint256 _tokenId) public view returns (uint256) { (uint256 bin, uint256 index) = _tokenId.getTokenBinIndex(); return packedTokenBalance[_address][bin].getValueInBin(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 Iterate through the list of existing tokens and return the indexes * and balances of the tokens owner by the user * @param _owner The adddress we are checking * @return indexes The tokenIds * @return balances The balances of each token */ function tokensOwned(address _owner) public view returns (uint256[] memory indexes, uint256[] memory balances) { uint256 numTokens = totalSupply(); uint256[] memory tokenIndexes = new uint256[](numTokens); uint256[] memory tempTokens = new uint256[](numTokens); uint256 count; for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = allTokens[i]; if (balanceOf(_owner, tokenId) > 0) { tempTokens[count] = balanceOf(_owner, tokenId); tokenIndexes[count] = tokenId; count++; } } // copy over the data to a correct size array uint256[] memory _ownedTokens = new uint256[](count); uint256[] memory _ownedTokensIndexes = new uint256[](count); for (uint256 i = 0; i < count; i++) { _ownedTokens[i] = tempTokens[i]; _ownedTokensIndexes[i] = tokenIndexes[i]; } return (_ownedTokensIndexes, _ownedTokens); } /** * @dev Will set _operator operator status to true or false * @param _operator Address to changes operator status. * @param _approved _operator's new operator status (true or false) */ function setApprovalForAll(address _operator, bool _approved) public { // Update operator status operators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /// @notice Approve for all by signature function permit(address _holder, address _spender, uint256 _nonce, uint256 _expiry, bool _allowed, bytes calldata _signature) external { // Calculate hash bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode( PERMIT_TYPEHASH, _holder, _spender, _nonce, _expiry, _allowed )) )); // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly bytes32 r; bytes32 s; uint8 v; bytes memory signature = _signature; assembly { r := mload(add(signature, 32)) s := mload(add(signature, 64)) v := byte(0, mload(add(signature, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } address recoveredAddress; // If the version is correct return the signer address if (v != 27 && v != 28) { recoveredAddress = address(0); } else { // solium-disable-next-line arg-overflow recoveredAddress = ecrecover(digest, v, r, s); } require(_holder != address(0), "Holder can't be zero address"); require(_holder == recoveredAddress, "Signer address is invalid"); require(_expiry == 0 || now <= _expiry, "Permission expired"); require(_nonce == nonces[_holder]++, "Nonce is invalid"); // Update operator status operators[_holder][_spender] = _allowed; emit ApprovalForAll(_holder, _spender, _allowed); } /** * @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 { require(_to != msg.sender, "Can't approve to yourself"); tokenApprovals[_tokenId][msg.sender] = _to; emit Approval(msg.sender, _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, address _tokenOwner) public view returns (address) { return tokenApprovals[_tokenId][_tokenOwner]; } /** * @dev Function that verifies whether _operator is an authorized operator of _tokenHolder. * @param _operator The address of the operator to query status of * @param _owner Address of the tokenHolder * @return A uint256 specifying the amount of tokens still available for the spender. */ function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator) { return operators[_owner][_operator]; } function isApprovedOrOwner( address _spender, address _owner, uint256 _tokenId ) public view returns (bool) { return ( _spender == _owner || getApproved(_tokenId, _owner) == _spender || isApprovedForAll(_owner, _spender) ); } function _updateTokenBalance( address _from, uint256 _tokenId, uint256 _amount, ObjectLib.Operations op ) internal { (uint256 bin, uint256 index) = _tokenId.getTokenBinIndex(); packedTokenBalance[_from][bin] = packedTokenBalance[_from][bin].updateTokenBalance( index, _amount, op ); } } // File: erc721o/contracts/ERC721OTransferable.sol pragma solidity ^0.5.4; contract ERC721OTransferable is ERC721OBase, ReentrancyGuard { // Libraries using Address for address; // safeTransfer constants bytes4 internal constant ERC721O_RECEIVED = 0xf891ffe0; bytes4 internal constant ERC721O_BATCH_RECEIVED = 0xd0e17c0b; function batchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts) public { // Batch Transfering _batchTransferFrom(_from, _to, _tokenIds, _amounts); } /** * @dev transfer objects from different tokenIds to specified address * @param _from The address to BatchTransfer objects from. * @param _to The address to batchTransfer objects to. * @param _tokenIds Array of tokenIds to update balance of * @param _amounts Array of amount of object per type to be transferred. * @param _data Data to pass to onERC721OReceived() function if recipient is contract * Note: Arrays should be sorted so that all tokenIds in a same bin are adjacent (more efficient). */ function safeBatchTransferFrom( address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts, bytes memory _data ) public nonReentrant { // Batch Transfering _batchTransferFrom(_from, _to, _tokenIds, _amounts); // Pass data if recipient is contract if (_to.isContract()) { bytes4 retval = IERC721OReceiver(_to).onERC721OBatchReceived( msg.sender, _from, _tokenIds, _amounts, _data ); require(retval == ERC721O_BATCH_RECEIVED); } } function safeBatchTransferFrom( address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts ) public { safeBatchTransferFrom(_from, _to, _tokenIds, _amounts, ""); } function transfer(address _to, uint256 _tokenId, uint256 _amount) public { _transferFrom(msg.sender, _to, _tokenId, _amount); } function transferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) public { _transferFrom(_from, _to, _tokenId, _amount); } function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) public { safeTransferFrom(_from, _to, _tokenId, _amount, ""); } function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount, bytes memory _data) public nonReentrant { _transferFrom(_from, _to, _tokenId, _amount); require( _checkAndCallSafeTransfer(_from, _to, _tokenId, _amount, _data), "Sent to a contract which is not an ERC721O receiver" ); } /** * @dev transfer objects from different tokenIds to specified address * @param _from The address to BatchTransfer objects from. * @param _to The address to batchTransfer objects to. * @param _tokenIds Array of tokenIds to update balance of * @param _amounts Array of amount of object per type to be transferred. * Note: Arrays should be sorted so that all tokenIds in a same bin are adjacent (more efficient). */ function _batchTransferFrom( address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts ) internal isOperatorOrOwner(_from) { // Requirements require(_tokenIds.length == _amounts.length, "Inconsistent array length between args"); require(_to != address(0), "Invalid to address"); // Number of transfers to execute uint256 nTransfer = _tokenIds.length; // Don't do useless calculations if (_from == _to) { for (uint256 i = 0; i < nTransfer; i++) { emit Transfer(_from, _to, _tokenIds[i]); emit TransferWithQuantity(_from, _to, _tokenIds[i], _amounts[i]); } return; } for (uint256 i = 0; i < nTransfer; i++) { require(_amounts[i] <= balanceOf(_from, _tokenIds[i]), "Quantity greater than from balance"); _updateTokenBalance(_from, _tokenIds[i], _amounts[i], ObjectLib.Operations.SUB); _updateTokenBalance(_to, _tokenIds[i], _amounts[i], ObjectLib.Operations.ADD); emit Transfer(_from, _to, _tokenIds[i]); emit TransferWithQuantity(_from, _to, _tokenIds[i], _amounts[i]); } // Emit batchTransfer event emit BatchTransfer(_from, _to, _tokenIds, _amounts); } function _transferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) internal { require(isApprovedOrOwner(msg.sender, _from, _tokenId), "Not approved"); require(_amount <= balanceOf(_from, _tokenId), "Quantity greater than from balance"); require(_to != address(0), "Invalid to address"); _updateTokenBalance(_from, _tokenId, _amount, ObjectLib.Operations.SUB); _updateTokenBalance(_to, _tokenId, _amount, ObjectLib.Operations.ADD); emit Transfer(_from, _to, _tokenId); emit TransferWithQuantity(_from, _to, _tokenId, _amount); } function _checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, uint256 _amount, bytes memory _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = IERC721OReceiver(_to).onERC721OReceived(msg.sender, _from, _tokenId, _amount, _data); return(retval == ERC721O_RECEIVED); } } // File: erc721o/contracts/ERC721OMintable.sol pragma solidity ^0.5.4; contract ERC721OMintable is ERC721OTransferable { // Libraries using LibPosition for bytes32; // Internal functions function _mint(uint256 _tokenId, address _to, uint256 _supply) internal { // If the token doesn't exist, add it to the tokens array if (!exists(_tokenId)) { tokenTypes[_tokenId] = POSITION; allTokens.push(_tokenId); } _updateTokenBalance(_to, _tokenId, _supply, ObjectLib.Operations.ADD); emit Transfer(address(0), _to, _tokenId); emit TransferWithQuantity(address(0), _to, _tokenId, _supply); } function _burn(address _tokenOwner, uint256 _tokenId, uint256 _quantity) internal { uint256 ownerBalance = balanceOf(_tokenOwner, _tokenId); require(ownerBalance >= _quantity, "TOKEN_MINTER:NOT_ENOUGH_POSITIONS"); _updateTokenBalance(_tokenOwner, _tokenId, _quantity, ObjectLib.Operations.SUB); emit Transfer(_tokenOwner, address(0), _tokenId); emit TransferWithQuantity(_tokenOwner, address(0), _tokenId, _quantity); } function _mint(address _buyer, address _seller, bytes32 _derivativeHash, uint256 _quantity) internal { _mintLong(_buyer, _derivativeHash, _quantity); _mintShort(_seller, _derivativeHash, _quantity); } function _mintLong(address _buyer, bytes32 _derivativeHash, uint256 _quantity) internal { uint256 longTokenId = _derivativeHash.getLongTokenId(); _mint(longTokenId, _buyer, _quantity); } function _mintShort(address _seller, bytes32 _derivativeHash, uint256 _quantity) internal { uint256 shortTokenId = _derivativeHash.getShortTokenId(); _mint(shortTokenId, _seller, _quantity); } function _registerPortfolio(uint256 _portfolioId, uint256[] memory _tokenIds, uint256[] memory _tokenRatio) internal { if (!exists(_portfolioId)) { tokenTypes[_portfolioId] = PORTFOLIO; emit Composition(_portfolioId, _tokenIds, _tokenRatio); } } } // File: erc721o/contracts/ERC721OComposable.sol pragma solidity ^0.5.4; contract ERC721OComposable is ERC721OMintable { // Libraries using UintArray for uint256[]; using SafeMath for uint256; function compose(uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public { require(_tokenIds.length == _tokenRatio.length, "TOKEN_MINTER:TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH"); require(_quantity > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_tokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_tokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE"); for (uint256 i = 0; i < _tokenIds.length; i++) { _burn(msg.sender, _tokenIds[i], _tokenRatio[i].mul(_quantity)); } uint256 portfolioId = uint256(keccak256(abi.encodePacked( _tokenIds, _tokenRatio ))); _registerPortfolio(portfolioId, _tokenIds, _tokenRatio); _mint(portfolioId, msg.sender, _quantity); } function decompose(uint256 _portfolioId, uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public { require(_tokenIds.length == _tokenRatio.length, "TOKEN_MINTER:TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH"); require(_quantity > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_tokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_tokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE"); uint256 portfolioId = uint256(keccak256(abi.encodePacked( _tokenIds, _tokenRatio ))); require(portfolioId == _portfolioId, "TOKEN_MINTER:WRONG_PORTFOLIO_ID"); _burn(msg.sender, _portfolioId, _quantity); for (uint256 i = 0; i < _tokenIds.length; i++) { _mint(_tokenIds[i], msg.sender, _tokenRatio[i].mul(_quantity)); } } function recompose( uint256 _portfolioId, uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity ) public { require(_initialTokenIds.length == _initialTokenRatio.length, "TOKEN_MINTER:INITIAL_TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH"); require(_finalTokenIds.length == _finalTokenRatio.length, "TOKEN_MINTER:FINAL_TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH"); require(_quantity > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_initialTokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_finalTokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_initialTokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE"); require(_finalTokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE"); uint256 oldPortfolioId = uint256(keccak256(abi.encodePacked( _initialTokenIds, _initialTokenRatio ))); require(oldPortfolioId == _portfolioId, "TOKEN_MINTER:WRONG_PORTFOLIO_ID"); _burn(msg.sender, _portfolioId, _quantity); _removedIds(_initialTokenIds, _initialTokenRatio, _finalTokenIds, _finalTokenRatio, _quantity); _addedIds(_initialTokenIds, _initialTokenRatio, _finalTokenIds, _finalTokenRatio, _quantity); _keptIds(_initialTokenIds, _initialTokenRatio, _finalTokenIds, _finalTokenRatio, _quantity); uint256 newPortfolioId = uint256(keccak256(abi.encodePacked( _finalTokenIds, _finalTokenRatio ))); _registerPortfolio(newPortfolioId, _finalTokenIds, _finalTokenRatio); _mint(newPortfolioId, msg.sender, _quantity); } function _removedIds( uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity ) private { (uint256[] memory removedIds, uint256[] memory removedIdsIdxs) = _initialTokenIds.difference(_finalTokenIds); for (uint256 i = 0; i < removedIds.length; i++) { uint256 index = removedIdsIdxs[i]; _mint(_initialTokenIds[index], msg.sender, _initialTokenRatio[index].mul(_quantity)); } _finalTokenRatio; } function _addedIds( uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity ) private { (uint256[] memory addedIds, uint256[] memory addedIdsIdxs) = _finalTokenIds.difference(_initialTokenIds); for (uint256 i = 0; i < addedIds.length; i++) { uint256 index = addedIdsIdxs[i]; _burn(msg.sender, _finalTokenIds[index], _finalTokenRatio[index].mul(_quantity)); } _initialTokenRatio; } function _keptIds( uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity ) private { (uint256[] memory keptIds, uint256[] memory keptInitialIdxs, uint256[] memory keptFinalIdxs) = _initialTokenIds.intersect(_finalTokenIds); for (uint256 i = 0; i < keptIds.length; i++) { uint256 initialIndex = keptInitialIdxs[i]; uint256 finalIndex = keptFinalIdxs[i]; if (_initialTokenRatio[initialIndex] > _finalTokenRatio[finalIndex]) { uint256 diff = _initialTokenRatio[initialIndex] - _finalTokenRatio[finalIndex]; _mint(_initialTokenIds[initialIndex], msg.sender, diff.mul(_quantity)); } else if (_initialTokenRatio[initialIndex] < _finalTokenRatio[finalIndex]) { uint256 diff = _finalTokenRatio[finalIndex] - _initialTokenRatio[initialIndex]; _burn(msg.sender, _initialTokenIds[initialIndex], diff.mul(_quantity)); } } } } // File: erc721o/contracts/Libs/UintsLib.sol pragma solidity ^0.5.4; library UintsLib { function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } } // File: erc721o/contracts/ERC721OBackwardCompatible.sol pragma solidity ^0.5.4; contract ERC721OBackwardCompatible is ERC721OComposable { using UintsLib for uint256; // Interface constants bytes4 internal constant INTERFACE_ID_ERC721 = 0x80ac58cd; bytes4 internal constant INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; bytes4 internal constant INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; // Reciever constants bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; // Metadata URI string internal baseTokenURI; constructor(string memory _baseTokenURI) public ERC721OBase() { baseTokenURI = _baseTokenURI; _registerInterface(INTERFACE_ID_ERC721); _registerInterface(INTERFACE_ID_ERC721_ENUMERABLE); _registerInterface(INTERFACE_ID_ERC721_METADATA); } // ERC721 compatibility function implementsERC721() public pure returns (bool) { return true; } /** * @dev Gets the owner of a given NFT * @param _tokenId uint256 representing the unique token identifier * @return address the owner of the token */ function ownerOf(uint256 _tokenId) public view returns (address) { if (exists(_tokenId)) { return address(this); } return address(0); } /** * @dev Gets the number of tokens owned by the address we are checking * @param _owner The adddress we are checking * @return balance The unique amount of tokens owned */ function balanceOf(address _owner) public view returns (uint256 balance) { (, uint256[] memory tokens) = tokensOwned(_owner); return tokens.length; } // ERC721 - Enumerable compatibility /** * @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]; } function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId) { (, uint256[] memory tokens) = tokensOwned(_owner); require(_index < tokens.length); return tokens[_index]; } // ERC721 - Metadata compatibility function tokenURI(uint256 _tokenId) public view returns (string memory tokenUri) { require(exists(_tokenId), "Token doesn't exist"); return string(abi.encodePacked( baseTokenURI, _tokenId.uint2str(), ".json" )); } /** * @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) { if (exists(_tokenId)) { return address(this); } return address(0); } function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { safeTransferFrom(_from, _to, _tokenId, ""); } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public nonReentrant { _transferFrom(_from, _to, _tokenId, 1); require( _checkAndCallSafeTransfer(_from, _to, _tokenId, _data), "Sent to a contract which is not an ERC721 receiver" ); } function transferFrom(address _from, address _to, uint256 _tokenId) public { _transferFrom(_from, _to, _tokenId, 1); } /** * @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 memory _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = IERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, _data ); return (retval == ERC721_RECEIVED); } } // File: contracts/TokenMinter.sol pragma solidity 0.5.16; /// @title Opium.TokenMinter contract implements ERC721O token standard for minting, burning and transferring position tokens contract TokenMinter is ERC721OBackwardCompatible, UsingRegistry { /// @notice Calls constructors of super-contracts /// @param _baseTokenURI string URI for token explorers /// @param _registry address Address of Opium.registry constructor(string memory _baseTokenURI, address _registry) public ERC721OBackwardCompatible(_baseTokenURI) UsingRegistry(_registry) {} /// @notice Mints LONG and SHORT position tokens /// @param _buyer address Address of LONG position receiver /// @param _seller address Address of SHORT position receiver /// @param _derivativeHash bytes32 Hash of derivative (ticker) of position /// @param _quantity uint256 Quantity of positions to mint function mint(address _buyer, address _seller, bytes32 _derivativeHash, uint256 _quantity) external onlyCore { _mint(_buyer, _seller, _derivativeHash, _quantity); } /// @notice Mints only LONG position tokens for "pooled" derivatives /// @param _buyer address Address of LONG position receiver /// @param _derivativeHash bytes32 Hash of derivative (ticker) of position /// @param _quantity uint256 Quantity of positions to mint function mint(address _buyer, bytes32 _derivativeHash, uint256 _quantity) external onlyCore { _mintLong(_buyer, _derivativeHash, _quantity); } /// @notice Burns position tokens /// @param _tokenOwner address Address of tokens owner /// @param _tokenId uint256 tokenId of positions to burn /// @param _quantity uint256 Quantity of positions to burn function burn(address _tokenOwner, uint256 _tokenId, uint256 _quantity) external onlyCore { _burn(_tokenOwner, _tokenId, _quantity); } /// @notice ERC721 interface compatible function for position token name retrieving /// @return Returns name of token function name() external view returns (string memory) { return "Opium Network Position Token"; } /// @notice ERC721 interface compatible function for position token symbol retrieving /// @return Returns symbol of token function symbol() external view returns (string memory) { return "ONP"; } /// VIEW FUNCTIONS /// @notice Checks whether _spender is approved to spend tokens on _owners behalf or owner itself /// @param _spender address Address of spender /// @param _owner address Address of owner /// @param _tokenId address tokenId of interest /// @return Returns whether _spender is approved to spend tokens function isApprovedOrOwner( address _spender, address _owner, uint256 _tokenId ) public view returns (bool) { return ( _spender == _owner || getApproved(_tokenId, _owner) == _spender || isApprovedForAll(_owner, _spender) || isOpiumSpender(_spender) ); } /// @notice Checks whether _spender is Opium.TokenSpender /// @return Returns whether _spender is Opium.TokenSpender function isOpiumSpender(address _spender) public view returns (bool) { return _spender == registry.getTokenSpender(); } } // File: contracts/Errors/OracleAggregatorErrors.sol pragma solidity 0.5.16; contract OracleAggregatorErrors { string constant internal ERROR_ORACLE_AGGREGATOR_NOT_ENOUGH_ETHER = "ORACLE_AGGREGATOR:NOT_ENOUGH_ETHER"; string constant internal ERROR_ORACLE_AGGREGATOR_QUERY_WAS_ALREADY_MADE = "ORACLE_AGGREGATOR:QUERY_WAS_ALREADY_MADE"; string constant internal ERROR_ORACLE_AGGREGATOR_DATA_DOESNT_EXIST = "ORACLE_AGGREGATOR:DATA_DOESNT_EXIST"; string constant internal ERROR_ORACLE_AGGREGATOR_DATA_ALREADY_EXIST = "ORACLE_AGGREGATOR:DATA_ALREADY_EXIST"; } // File: contracts/Interface/IOracleId.sol pragma solidity 0.5.16; /// @title Opium.Interface.IOracleId contract is an interface that every oracleId should implement interface IOracleId { /// @notice Requests data from `oracleId` one time /// @param timestamp uint256 Timestamp at which data are needed function fetchData(uint256 timestamp) external payable; /// @notice Requests data from `oracleId` multiple times /// @param timestamp uint256 Timestamp at which data are needed for the first time /// @param period uint256 Period in seconds between multiple timestamps /// @param times uint256 How many timestamps are requested function recursivelyFetchData(uint256 timestamp, uint256 period, uint256 times) external payable; /// @notice Requests and returns price in ETH for one request. This function could be called as `view` function. Oraclize API for price calculations restricts making this function as view. /// @return fetchPrice uint256 Price of one data request in ETH function calculateFetchPrice() external returns (uint256 fetchPrice); // Event with oracleId metadata JSON string (for DIB.ONE derivative explorer) event MetadataSet(string metadata); } // File: contracts/OracleAggregator.sol pragma solidity 0.5.16; /// @title Opium.OracleAggregator contract requests and caches the data from `oracleId`s and provides them to the Core for positions execution contract OracleAggregator is OracleAggregatorErrors, ReentrancyGuard { using SafeMath for uint256; // Storage for the `oracleId` results // dataCache[oracleId][timestamp] => data mapping (address => mapping(uint256 => uint256)) public dataCache; // Flags whether data were provided // dataExist[oracleId][timestamp] => bool mapping (address => mapping(uint256 => bool)) public dataExist; // Flags whether data were requested // dataRequested[oracleId][timestamp] => bool mapping (address => mapping(uint256 => bool)) public dataRequested; // MODIFIERS /// @notice Checks whether enough ETH were provided withing data request to proceed /// @param oracleId address Address of the `oracleId` smart contract /// @param times uint256 How many times the `oracleId` is being requested modifier enoughEtherProvided(address oracleId, uint256 times) { // Calling Opium.IOracleId function to get the data fetch price per one request uint256 oneTimePrice = calculateFetchPrice(oracleId); // Checking if enough ether was provided for `times` amount of requests require(msg.value >= oneTimePrice.mul(times), ERROR_ORACLE_AGGREGATOR_NOT_ENOUGH_ETHER); _; } // PUBLIC FUNCTIONS /// @notice Requests data from `oracleId` one time /// @param oracleId address Address of the `oracleId` smart contract /// @param timestamp uint256 Timestamp at which data are needed function fetchData(address oracleId, uint256 timestamp) public payable nonReentrant enoughEtherProvided(oracleId, 1) { // Check if was not requested before and mark as requested _registerQuery(oracleId, timestamp); // Call the `oracleId` contract and transfer ETH IOracleId(oracleId).fetchData.value(msg.value)(timestamp); } /// @notice Requests data from `oracleId` multiple times /// @param oracleId address Address of the `oracleId` smart contract /// @param timestamp uint256 Timestamp at which data are needed for the first time /// @param period uint256 Period in seconds between multiple timestamps /// @param times uint256 How many timestamps are requested function recursivelyFetchData(address oracleId, uint256 timestamp, uint256 period, uint256 times) public payable nonReentrant enoughEtherProvided(oracleId, times) { // Check if was not requested before and mark as requested in loop for each timestamp for (uint256 i = 0; i < times; i++) { _registerQuery(oracleId, timestamp + period * i); } // Call the `oracleId` contract and transfer ETH IOracleId(oracleId).recursivelyFetchData.value(msg.value)(timestamp, period, times); } /// @notice Receives and caches data from `msg.sender` /// @param timestamp uint256 Timestamp of data /// @param data uint256 Data itself function __callback(uint256 timestamp, uint256 data) public { // Don't allow to push data twice require(!dataExist[msg.sender][timestamp], ERROR_ORACLE_AGGREGATOR_DATA_ALREADY_EXIST); // Saving data dataCache[msg.sender][timestamp] = data; // Flagging that data were received dataExist[msg.sender][timestamp] = true; } /// @notice Requests and returns price in ETH for one request. This function could be called as `view` function. Oraclize API for price calculations restricts making this function as view. /// @param oracleId address Address of the `oracleId` smart contract /// @return fetchPrice uint256 Price of one data request in ETH function calculateFetchPrice(address oracleId) public returns(uint256 fetchPrice) { fetchPrice = IOracleId(oracleId).calculateFetchPrice(); } // PRIVATE FUNCTIONS /// @notice Checks if data was not requested and provided before and marks as requested /// @param oracleId address Address of the `oracleId` smart contract /// @param timestamp uint256 Timestamp at which data are requested function _registerQuery(address oracleId, uint256 timestamp) private { // Check if data was not requested and provided yet require(!dataRequested[oracleId][timestamp] && !dataExist[oracleId][timestamp], ERROR_ORACLE_AGGREGATOR_QUERY_WAS_ALREADY_MADE); // Mark as requested dataRequested[oracleId][timestamp] = true; } // VIEW FUNCTIONS /// @notice Returns cached data if they exist, or reverts with an error /// @param oracleId address Address of the `oracleId` smart contract /// @param timestamp uint256 Timestamp at which data were requested /// @return dataResult uint256 Cached data provided by `oracleId` function getData(address oracleId, uint256 timestamp) public view returns(uint256 dataResult) { // Check if Opium.OracleAggregator has data require(hasData(oracleId, timestamp), ERROR_ORACLE_AGGREGATOR_DATA_DOESNT_EXIST); // Return cached data dataResult = dataCache[oracleId][timestamp]; } /// @notice Getter for dataExist mapping /// @param oracleId address Address of the `oracleId` smart contract /// @param timestamp uint256 Timestamp at which data were requested /// @param result bool Returns whether data were provided already function hasData(address oracleId, uint256 timestamp) public view returns(bool result) { return dataExist[oracleId][timestamp]; } } // File: contracts/Errors/SyntheticAggregatorErrors.sol pragma solidity 0.5.16; contract SyntheticAggregatorErrors { string constant internal ERROR_SYNTHETIC_AGGREGATOR_DERIVATIVE_HASH_NOT_MATCH = "SYNTHETIC_AGGREGATOR:DERIVATIVE_HASH_NOT_MATCH"; string constant internal ERROR_SYNTHETIC_AGGREGATOR_WRONG_MARGIN = "SYNTHETIC_AGGREGATOR:WRONG_MARGIN"; string constant internal ERROR_SYNTHETIC_AGGREGATOR_COMMISSION_TOO_BIG = "SYNTHETIC_AGGREGATOR:COMMISSION_TOO_BIG"; } // File: contracts/SyntheticAggregator.sol pragma solidity 0.5.16; /// @notice Opium.SyntheticAggregator contract initialized, identifies and caches syntheticId sensitive data contract SyntheticAggregator is SyntheticAggregatorErrors, LibDerivative, LibCommission, ReentrancyGuard { // Emitted when new ticker is initialized event Create(Derivative derivative, bytes32 derivativeHash); // Enum for types of syntheticId // Invalid - syntheticId is not initialized yet // NotPool - syntheticId with p2p logic // Pool - syntheticId with pooled logic enum SyntheticTypes { Invalid, NotPool, Pool } // Cache of buyer margin by ticker // buyerMarginByHash[derivativeHash] = buyerMargin mapping (bytes32 => uint256) public buyerMarginByHash; // Cache of seller margin by ticker // sellerMarginByHash[derivativeHash] = sellerMargin mapping (bytes32 => uint256) public sellerMarginByHash; // Cache of type by ticker // typeByHash[derivativeHash] = type mapping (bytes32 => SyntheticTypes) public typeByHash; // Cache of commission by ticker // commissionByHash[derivativeHash] = commission mapping (bytes32 => uint256) public commissionByHash; // Cache of author addresses by ticker // authorAddressByHash[derivativeHash] = authorAddress mapping (bytes32 => address) public authorAddressByHash; // PUBLIC FUNCTIONS /// @notice Initializes ticker, if was not initialized and returns `syntheticId` author commission from cache /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself /// @return commission uint256 Synthetic author commission function getAuthorCommission(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (uint256 commission) { // Initialize derivative if wasn't initialized before _initDerivative(_derivativeHash, _derivative); commission = commissionByHash[_derivativeHash]; } /// @notice Initializes ticker, if was not initialized and returns `syntheticId` author address from cache /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself /// @return authorAddress address Synthetic author address function getAuthorAddress(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (address authorAddress) { // Initialize derivative if wasn't initialized before _initDerivative(_derivativeHash, _derivative); authorAddress = authorAddressByHash[_derivativeHash]; } /// @notice Initializes ticker, if was not initialized and returns buyer and seller margin from cache /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself /// @return buyerMargin uint256 Margin of buyer /// @return sellerMargin uint256 Margin of seller function getMargin(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (uint256 buyerMargin, uint256 sellerMargin) { // If it's a pool, just return margin from syntheticId contract if (_isPool(_derivativeHash, _derivative)) { return IDerivativeLogic(_derivative.syntheticId).getMargin(_derivative); } // Initialize derivative if wasn't initialized before _initDerivative(_derivativeHash, _derivative); // Check if margins for _derivativeHash were already cached buyerMargin = buyerMarginByHash[_derivativeHash]; sellerMargin = sellerMarginByHash[_derivativeHash]; } /// @notice Checks whether `syntheticId` implements pooled logic /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself /// @return result bool Returns whether synthetic implements pooled logic function isPool(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (bool result) { result = _isPool(_derivativeHash, _derivative); } // PRIVATE FUNCTIONS /// @notice Initializes ticker, if was not initialized and returns whether `syntheticId` implements pooled logic /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself /// @return result bool Returns whether synthetic implements pooled logic function _isPool(bytes32 _derivativeHash, Derivative memory _derivative) private returns (bool result) { // Initialize derivative if wasn't initialized before _initDerivative(_derivativeHash, _derivative); result = typeByHash[_derivativeHash] == SyntheticTypes.Pool; } /// @notice Initializes ticker: caches syntheticId type, margin, author address and commission /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself function _initDerivative(bytes32 _derivativeHash, Derivative memory _derivative) private { // Check if type for _derivativeHash was already cached SyntheticTypes syntheticType = typeByHash[_derivativeHash]; // Type could not be Invalid, thus this condition says us that type was not cached before if (syntheticType != SyntheticTypes.Invalid) { return; } // For security reasons we calculate hash of provided _derivative bytes32 derivativeHash = getDerivativeHash(_derivative); require(derivativeHash == _derivativeHash, ERROR_SYNTHETIC_AGGREGATOR_DERIVATIVE_HASH_NOT_MATCH); // POOL // Get isPool from SyntheticId bool result = IDerivativeLogic(_derivative.syntheticId).isPool(); // Cache type returned from synthetic typeByHash[derivativeHash] = result ? SyntheticTypes.Pool : SyntheticTypes.NotPool; // MARGIN // Get margin from SyntheticId (uint256 buyerMargin, uint256 sellerMargin) = IDerivativeLogic(_derivative.syntheticId).getMargin(_derivative); // We are not allowing both margins to be equal to 0 require(buyerMargin != 0 || sellerMargin != 0, ERROR_SYNTHETIC_AGGREGATOR_WRONG_MARGIN); // Cache margins returned from synthetic buyerMarginByHash[derivativeHash] = buyerMargin; sellerMarginByHash[derivativeHash] = sellerMargin; // AUTHOR ADDRESS // Cache author address returned from synthetic authorAddressByHash[derivativeHash] = IDerivativeLogic(_derivative.syntheticId).getAuthorAddress(); // AUTHOR COMMISSION // Get commission from syntheticId uint256 commission = IDerivativeLogic(_derivative.syntheticId).getAuthorCommission(); // Check if commission is not set > 100% require(commission <= COMMISSION_BASE, ERROR_SYNTHETIC_AGGREGATOR_COMMISSION_TOO_BIG); // Cache commission commissionByHash[derivativeHash] = commission; // If we are here, this basically means this ticker was not used before, so we emit an event for Dapps developers about new ticker (derivative) and it's hash emit Create(_derivative, derivativeHash); } } // File: contracts/Lib/Whitelisted.sol pragma solidity 0.5.16; /// @title Opium.Lib.Whitelisted contract implements whitelist with modifier to restrict access to only whitelisted addresses contract Whitelisted { // Whitelist array address[] internal whitelist; /// @notice This modifier restricts access to functions, which could be called only by whitelisted addresses modifier onlyWhitelisted() { // Allowance flag bool allowed = false; // Going through whitelisted addresses array uint256 whitelistLength = whitelist.length; for (uint256 i = 0; i < whitelistLength; i++) { // If `msg.sender` is met within whitelisted addresses, raise the flag and exit the loop if (whitelist[i] == msg.sender) { allowed = true; break; } } // Check if flag was raised require(allowed, "Only whitelisted allowed"); _; } /// @notice Getter for whitelisted addresses array /// @return Array of whitelisted addresses function getWhitelist() public view returns (address[] memory) { return whitelist; } } // File: contracts/Lib/WhitelistedWithGovernance.sol pragma solidity 0.5.16; /// @title Opium.Lib.WhitelistedWithGovernance contract implements Opium.Lib.Whitelisted and adds governance for whitelist controlling contract WhitelistedWithGovernance is Whitelisted { // Emitted when new governor is set event GovernorSet(address governor); // Emitted when new whitelist is proposed event Proposed(address[] whitelist); // Emitted when proposed whitelist is committed (set) event Committed(address[] whitelist); // Proposal life timelock interval uint256 public timeLockInterval; // Governor address address public governor; // Timestamp of last proposal uint256 public proposalTime; // Proposed whitelist address[] public proposedWhitelist; /// @notice This modifier restricts access to functions, which could be called only by governor modifier onlyGovernor() { require(msg.sender == governor, "Only governor allowed"); _; } /// @notice Contract constructor /// @param _timeLockInterval uint256 Initial value for timelock interval /// @param _governor address Initial value for governor constructor(uint256 _timeLockInterval, address _governor) public { timeLockInterval = _timeLockInterval; governor = _governor; emit GovernorSet(governor); } /// @notice Calling this function governor could propose new whitelist addresses array. Also it allows to initialize first whitelist if it was not initialized yet. function proposeWhitelist(address[] memory _whitelist) public onlyGovernor { // Restrict empty proposals require(_whitelist.length != 0, "Can't be empty"); // Consider empty whitelist as not initialized, as proposing of empty whitelists is not allowed // If whitelist has never been initialized, we set whitelist right away without proposal if (whitelist.length == 0) { whitelist = _whitelist; emit Committed(_whitelist); // Otherwise save current time as timestamp of proposal, save proposed whitelist and emit event } else { proposalTime = now; proposedWhitelist = _whitelist; emit Proposed(_whitelist); } } /// @notice Calling this function governor commits proposed whitelist if timelock interval of proposal was passed function commitWhitelist() public onlyGovernor { // Check if proposal was made require(proposalTime != 0, "Didn't proposed yet"); // Check if timelock interval was passed require((proposalTime + timeLockInterval) < now, "Can't commit yet"); // Set new whitelist and emit event whitelist = proposedWhitelist; emit Committed(whitelist); // Reset proposal time lock proposalTime = 0; } /// @notice This function allows governor to transfer governance to a new governor and emits event /// @param _governor address Address of new governor function setGovernor(address _governor) public onlyGovernor { require(_governor != address(0), "Can't set zero address"); governor = _governor; emit GovernorSet(governor); } } // File: contracts/Lib/WhitelistedWithGovernanceAndChangableTimelock.sol pragma solidity 0.5.16; /// @notice Opium.Lib.WhitelistedWithGovernanceAndChangableTimelock contract implements Opium.Lib.WhitelistedWithGovernance and adds possibility for governor to change timelock interval within timelock interval contract WhitelistedWithGovernanceAndChangableTimelock is WhitelistedWithGovernance { // Emitted when new timelock is proposed event Proposed(uint256 timelock); // Emitted when new timelock is committed (set) event Committed(uint256 timelock); // Timestamp of last timelock proposal uint256 public timeLockProposalTime; // Proposed timelock uint256 public proposedTimeLock; /// @notice Calling this function governor could propose new timelock /// @param _timelock uint256 New timelock value function proposeTimelock(uint256 _timelock) public onlyGovernor { timeLockProposalTime = now; proposedTimeLock = _timelock; emit Proposed(_timelock); } /// @notice Calling this function governor could commit previously proposed new timelock if timelock interval of proposal was passed function commitTimelock() public onlyGovernor { // Check if proposal was made require(timeLockProposalTime != 0, "Didn't proposed yet"); // Check if timelock interval was passed require((timeLockProposalTime + timeLockInterval) < now, "Can't commit yet"); // Set new timelock and emit event timeLockInterval = proposedTimeLock; emit Committed(proposedTimeLock); // Reset timelock time lock timeLockProposalTime = 0; } } // File: contracts/TokenSpender.sol pragma solidity 0.5.16; /// @title Opium.TokenSpender contract holds users ERC20 approvals and allows whitelisted contracts to use tokens contract TokenSpender is WhitelistedWithGovernanceAndChangableTimelock { using SafeERC20 for IERC20; // Initial timelock period uint256 public constant WHITELIST_TIMELOCK = 1 hours; /// @notice Calls constructors of super-contracts /// @param _governor address Address of governor, who is allowed to adjust whitelist constructor(address _governor) public WhitelistedWithGovernance(WHITELIST_TIMELOCK, _governor) {} /// @notice Using this function whitelisted contracts could call ERC20 transfers /// @param token IERC20 Instance of token /// @param from address Address from which tokens are transferred /// @param to address Address of tokens receiver /// @param amount uint256 Amount of tokens to be transferred function claimTokens(IERC20 token, address from, address to, uint256 amount) external onlyWhitelisted { token.safeTransferFrom(from, to, amount); } /// @notice Using this function whitelisted contracts could call ERC721O transfers /// @param token IERC721O Instance of token /// @param from address Address from which tokens are transferred /// @param to address Address of tokens receiver /// @param tokenId uint256 Token ID to be transferred /// @param amount uint256 Amount of tokens to be transferred function claimPositions(IERC721O token, address from, address to, uint256 tokenId, uint256 amount) external onlyWhitelisted { token.safeTransferFrom(from, to, tokenId, amount); } } // File: contracts/Core.sol pragma solidity 0.5.16; /// @title Opium.Core contract creates positions, holds and distributes margin at the maturity contract Core is LibDerivative, LibCommission, UsingRegistry, CoreErrors, ReentrancyGuard { using SafeMath for uint256; using LibPosition for bytes32; using SafeERC20 for IERC20; // Emitted when Core creates new position event Created(address buyer, address seller, bytes32 derivativeHash, uint256 quantity); // Emitted when Core executes positions event Executed(address tokenOwner, uint256 tokenId, uint256 quantity); // Emitted when Core cancels ticker for the first time event Canceled(bytes32 derivativeHash); // Period of time after which ticker could be canceled if no data was provided to the `oracleId` uint256 public constant NO_DATA_CANCELLATION_PERIOD = 2 weeks; // Vaults for pools // This mapping holds balances of pooled positions // poolVaults[syntheticAddress][tokenAddress] => availableBalance mapping (address => mapping(address => uint256)) public poolVaults; // Vaults for fees // This mapping holds balances of fee recipients // feesVaults[feeRecipientAddress][tokenAddress] => availableBalance mapping (address => mapping(address => uint256)) public feesVaults; // Hashes of cancelled tickers mapping (bytes32 => bool) public cancelled; /// @notice Calls Core.Lib.UsingRegistry constructor constructor(address _registry) public UsingRegistry(_registry) {} // PUBLIC FUNCTIONS /// @notice This function allows fee recipients to withdraw their fees /// @param _tokenAddress address Address of an ERC20 token to withdraw function withdrawFee(address _tokenAddress) public nonReentrant { uint256 balance = feesVaults[msg.sender][_tokenAddress]; feesVaults[msg.sender][_tokenAddress] = 0; IERC20(_tokenAddress).safeTransfer(msg.sender, balance); } /// @notice Creates derivative contracts (positions) /// @param _derivative Derivative Derivative definition /// @param _quantity uint256 Quantity of derivatives to be created /// @param _addresses address[2] Addresses of buyer and seller /// [0] - buyer address /// [1] - seller address - if seller is set to `address(0)`, consider as pooled position function create(Derivative memory _derivative, uint256 _quantity, address[2] memory _addresses) public nonReentrant { if (_addresses[1] == address(0)) { _createPooled(_derivative, _quantity, _addresses[0]); } else { _create(_derivative, _quantity, _addresses); } } /// @notice Executes several positions of `msg.sender` with same `tokenId` /// @param _tokenId uint256 `tokenId` of positions that needs to be executed /// @param _quantity uint256 Quantity of positions to execute /// @param _derivative Derivative Derivative definition function execute(uint256 _tokenId, uint256 _quantity, Derivative memory _derivative) public nonReentrant { uint256[] memory tokenIds = new uint256[](1); uint256[] memory quantities = new uint256[](1); Derivative[] memory derivatives = new Derivative[](1); tokenIds[0] = _tokenId; quantities[0] = _quantity; derivatives[0] = _derivative; _execute(msg.sender, tokenIds, quantities, derivatives); } /// @notice Executes several positions of `_tokenOwner` with same `tokenId` /// @param _tokenOwner address Address of the owner of positions /// @param _tokenId uint256 `tokenId` of positions that needs to be executed /// @param _quantity uint256 Quantity of positions to execute /// @param _derivative Derivative Derivative definition function execute(address _tokenOwner, uint256 _tokenId, uint256 _quantity, Derivative memory _derivative) public nonReentrant { uint256[] memory tokenIds = new uint256[](1); uint256[] memory quantities = new uint256[](1); Derivative[] memory derivatives = new Derivative[](1); tokenIds[0] = _tokenId; quantities[0] = _quantity; derivatives[0] = _derivative; _execute(_tokenOwner, tokenIds, quantities, derivatives); } /// @notice Executes several positions of `msg.sender` with different `tokenId`s /// @param _tokenIds uint256[] `tokenId`s of positions that needs to be executed /// @param _quantities uint256[] Quantity of positions to execute for each `tokenId` /// @param _derivatives Derivative[] Derivative definitions for each `tokenId` function execute(uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) public nonReentrant { _execute(msg.sender, _tokenIds, _quantities, _derivatives); } /// @notice Executes several positions of `_tokenOwner` with different `tokenId`s /// @param _tokenOwner address Address of the owner of positions /// @param _tokenIds uint256[] `tokenId`s of positions that needs to be executed /// @param _quantities uint256[] Quantity of positions to execute for each `tokenId` /// @param _derivatives Derivative[] Derivative definitions for each `tokenId` function execute(address _tokenOwner, uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) public nonReentrant { _execute(_tokenOwner, _tokenIds, _quantities, _derivatives); } /// @notice Cancels tickers, burns positions and returns margins to positions owners in case no data were provided within `NO_DATA_CANCELLATION_PERIOD` /// @param _tokenId uint256 `tokenId` of positions that needs to be canceled /// @param _quantity uint256 Quantity of positions to cancel /// @param _derivative Derivative Derivative definition function cancel(uint256 _tokenId, uint256 _quantity, Derivative memory _derivative) public nonReentrant { uint256[] memory tokenIds = new uint256[](1); uint256[] memory quantities = new uint256[](1); Derivative[] memory derivatives = new Derivative[](1); tokenIds[0] = _tokenId; quantities[0] = _quantity; derivatives[0] = _derivative; _cancel(tokenIds, quantities, derivatives); } /// @notice Cancels tickers, burns positions and returns margins to positions owners in case no data were provided within `NO_DATA_CANCELLATION_PERIOD` /// @param _tokenIds uint256[] `tokenId` of positions that needs to be canceled /// @param _quantities uint256[] Quantity of positions to cancel for each `tokenId` /// @param _derivatives Derivative[] Derivative definitions for each `tokenId` function cancel(uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) public nonReentrant { _cancel(_tokenIds, _quantities, _derivatives); } // PRIVATE FUNCTIONS struct CreatePooledLocalVars { SyntheticAggregator syntheticAggregator; IDerivativeLogic derivativeLogic; IERC20 marginToken; TokenSpender tokenSpender; TokenMinter tokenMinter; } /// @notice This function creates pooled positions /// @param _derivative Derivative Derivative definition /// @param _quantity uint256 Quantity of positions to create /// @param _address address Address of position receiver function _createPooled(Derivative memory _derivative, uint256 _quantity, address _address) private { // Local variables CreatePooledLocalVars memory vars; // Create instance of Opium.SyntheticAggregator // Create instance of Opium.IDerivativeLogic // Create instance of margin token // Create instance of Opium.TokenSpender // Create instance of Opium.TokenMinter vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator()); vars.derivativeLogic = IDerivativeLogic(_derivative.syntheticId); vars.marginToken = IERC20(_derivative.token); vars.tokenSpender = TokenSpender(registry.getTokenSpender()); vars.tokenMinter = TokenMinter(registry.getMinter()); // Generate hash for derivative bytes32 derivativeHash = getDerivativeHash(_derivative); // Check with Opium.SyntheticAggregator if syntheticId is a pool require(vars.syntheticAggregator.isPool(derivativeHash, _derivative), ERROR_CORE_NOT_POOL); // Check if ticker was canceled require(!cancelled[derivativeHash], ERROR_CORE_TICKER_WAS_CANCELLED); // Validate input data against Derivative logic (`syntheticId`) require(vars.derivativeLogic.validateInput(_derivative), ERROR_CORE_SYNTHETIC_VALIDATION_ERROR); // Get cached margin required according to logic from Opium.SyntheticAggregator (uint256 margin, ) = vars.syntheticAggregator.getMargin(derivativeHash, _derivative); // Check ERC20 tokens allowance: margin * quantity // `msg.sender` must provide margin for position creation require(vars.marginToken.allowance(msg.sender, address(vars.tokenSpender)) >= margin.mul(_quantity), ERROR_CORE_NOT_ENOUGH_TOKEN_ALLOWANCE); // Take ERC20 tokens from msg.sender, should never revert in correct ERC20 implementation vars.tokenSpender.claimTokens(vars.marginToken, msg.sender, address(this), margin.mul(_quantity)); // Since it's a pooled position, we add transferred margin to pool balance poolVaults[_derivative.syntheticId][_derivative.token] = poolVaults[_derivative.syntheticId][_derivative.token].add(margin.mul(_quantity)); // Mint LONG position tokens vars.tokenMinter.mint(_address, derivativeHash, _quantity); emit Created(_address, address(0), derivativeHash, _quantity); } struct CreateLocalVars { SyntheticAggregator syntheticAggregator; IDerivativeLogic derivativeLogic; IERC20 marginToken; TokenSpender tokenSpender; TokenMinter tokenMinter; } /// @notice This function creates p2p positions /// @param _derivative Derivative Derivative definition /// @param _quantity uint256 Quantity of positions to create /// @param _addresses address[2] Addresses of buyer and seller /// [0] - buyer address /// [1] - seller address function _create(Derivative memory _derivative, uint256 _quantity, address[2] memory _addresses) private { // Local variables CreateLocalVars memory vars; // Create instance of Opium.SyntheticAggregator // Create instance of Opium.IDerivativeLogic // Create instance of margin token // Create instance of Opium.TokenSpender // Create instance of Opium.TokenMinter vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator()); vars.derivativeLogic = IDerivativeLogic(_derivative.syntheticId); vars.marginToken = IERC20(_derivative.token); vars.tokenSpender = TokenSpender(registry.getTokenSpender()); vars.tokenMinter = TokenMinter(registry.getMinter()); // Generate hash for derivative bytes32 derivativeHash = getDerivativeHash(_derivative); // Check with Opium.SyntheticAggregator if syntheticId is not a pool require(!vars.syntheticAggregator.isPool(derivativeHash, _derivative), ERROR_CORE_CANT_BE_POOL); // Check if ticker was canceled require(!cancelled[derivativeHash], ERROR_CORE_TICKER_WAS_CANCELLED); // Validate input data against Derivative logic (`syntheticId`) require(vars.derivativeLogic.validateInput(_derivative), ERROR_CORE_SYNTHETIC_VALIDATION_ERROR); uint256[2] memory margins; // Get cached margin required according to logic from Opium.SyntheticAggregator // margins[0] - buyerMargin // margins[1] - sellerMargin (margins[0], margins[1]) = vars.syntheticAggregator.getMargin(derivativeHash, _derivative); // Check ERC20 tokens allowance: (margins[0] + margins[1]) * quantity // `msg.sender` must provide margin for position creation require(vars.marginToken.allowance(msg.sender, address(vars.tokenSpender)) >= margins[0].add(margins[1]).mul(_quantity), ERROR_CORE_NOT_ENOUGH_TOKEN_ALLOWANCE); // Take ERC20 tokens from msg.sender, should never revert in correct ERC20 implementation vars.tokenSpender.claimTokens(vars.marginToken, msg.sender, address(this), margins[0].add(margins[1]).mul(_quantity)); // Mint LONG and SHORT positions tokens vars.tokenMinter.mint(_addresses[0], _addresses[1], derivativeHash, _quantity); emit Created(_addresses[0], _addresses[1], derivativeHash, _quantity); } struct ExecuteAndCancelLocalVars { TokenMinter tokenMinter; OracleAggregator oracleAggregator; SyntheticAggregator syntheticAggregator; } /// @notice Executes several positions of `_tokenOwner` with different `tokenId`s /// @param _tokenOwner address Address of the owner of positions /// @param _tokenIds uint256[] `tokenId`s of positions that needs to be executed /// @param _quantities uint256[] Quantity of positions to execute for each `tokenId` /// @param _derivatives Derivative[] Derivative definitions for each `tokenId` function _execute(address _tokenOwner, uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) private { require(_tokenIds.length == _quantities.length, ERROR_CORE_TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH); require(_tokenIds.length == _derivatives.length, ERROR_CORE_TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH); // Local variables ExecuteAndCancelLocalVars memory vars; // Create instance of Opium.TokenMinter // Create instance of Opium.OracleAggregator // Create instance of Opium.SyntheticAggregator vars.tokenMinter = TokenMinter(registry.getMinter()); vars.oracleAggregator = OracleAggregator(registry.getOracleAggregator()); vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator()); for (uint256 i; i < _tokenIds.length; i++) { // Check if execution is performed after endTime require(now > _derivatives[i].endTime, ERROR_CORE_EXECUTION_BEFORE_MATURITY_NOT_ALLOWED); // Checking whether execution is performed by `_tokenOwner` or `_tokenOwner` allowed third party executions on it's behalf require( _tokenOwner == msg.sender || IDerivativeLogic(_derivatives[i].syntheticId).thirdpartyExecutionAllowed(_tokenOwner), ERROR_CORE_SYNTHETIC_EXECUTION_WAS_NOT_ALLOWED ); // Returns payout for all positions uint256 payout = _getPayout(_derivatives[i], _tokenIds[i], _quantities[i], vars); // Transfer payout if (payout > 0) { IERC20(_derivatives[i].token).safeTransfer(_tokenOwner, payout); } // Burn executed position tokens vars.tokenMinter.burn(_tokenOwner, _tokenIds[i], _quantities[i]); emit Executed(_tokenOwner, _tokenIds[i], _quantities[i]); } } /// @notice Cancels tickers, burns positions and returns margins to positions owners in case no data were provided within `NO_DATA_CANCELLATION_PERIOD` /// @param _tokenIds uint256[] `tokenId` of positions that needs to be canceled /// @param _quantities uint256[] Quantity of positions to cancel for each `tokenId` /// @param _derivatives Derivative[] Derivative definitions for each `tokenId` function _cancel(uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) private { require(_tokenIds.length == _quantities.length, ERROR_CORE_TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH); require(_tokenIds.length == _derivatives.length, ERROR_CORE_TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH); // Local variables ExecuteAndCancelLocalVars memory vars; // Create instance of Opium.TokenMinter // Create instance of Opium.OracleAggregator // Create instance of Opium.SyntheticAggregator vars.tokenMinter = TokenMinter(registry.getMinter()); vars.oracleAggregator = OracleAggregator(registry.getOracleAggregator()); vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator()); for (uint256 i; i < _tokenIds.length; i++) { // Don't allow to cancel tickers with "dummy" oracleIds require(_derivatives[i].oracleId != address(0), ERROR_CORE_CANT_CANCEL_DUMMY_ORACLE_ID); // Check if cancellation is called after `NO_DATA_CANCELLATION_PERIOD` and `oracleId` didn't provided data require( _derivatives[i].endTime + NO_DATA_CANCELLATION_PERIOD <= now && !vars.oracleAggregator.hasData(_derivatives[i].oracleId, _derivatives[i].endTime), ERROR_CORE_CANCELLATION_IS_NOT_ALLOWED ); // Generate hash for derivative bytes32 derivativeHash = getDerivativeHash(_derivatives[i]); // Emit `Canceled` event only once and mark ticker as canceled if (!cancelled[derivativeHash]) { cancelled[derivativeHash] = true; emit Canceled(derivativeHash); } uint256[2] memory margins; // Get cached margin required according to logic from Opium.SyntheticAggregator // margins[0] - buyerMargin // margins[1] - sellerMargin (margins[0], margins[1]) = vars.syntheticAggregator.getMargin(derivativeHash, _derivatives[i]); uint256 payout; // Check if `_tokenId` is an ID of LONG position if (derivativeHash.getLongTokenId() == _tokenIds[i]) { // Set payout to buyerPayout payout = margins[0]; // Check if `_tokenId` is an ID of SHORT position } else if (derivativeHash.getShortTokenId() == _tokenIds[i]) { // Set payout to sellerPayout payout = margins[1]; } else { // Either portfolioId, hack or bug revert(ERROR_CORE_UNKNOWN_POSITION_TYPE); } // Transfer payout * _quantities[i] if (payout > 0) { IERC20(_derivatives[i].token).safeTransfer(msg.sender, payout.mul(_quantities[i])); } // Burn canceled position tokens vars.tokenMinter.burn(msg.sender, _tokenIds[i], _quantities[i]); } } /// @notice Calculates payout for position and gets fees /// @param _derivative Derivative Derivative definition /// @param _tokenId uint256 `tokenId` of positions /// @param _quantity uint256 Quantity of positions /// @param _vars ExecuteAndCancelLocalVars Helping local variables /// @return payout uint256 Payout for all tokens function _getPayout(Derivative memory _derivative, uint256 _tokenId, uint256 _quantity, ExecuteAndCancelLocalVars memory _vars) private returns (uint256 payout) { // Trying to getData from Opium.OracleAggregator, could be reverted // Opium allows to use "dummy" oracleIds, in this case data is set to `0` uint256 data; if (_derivative.oracleId != address(0)) { data = _vars.oracleAggregator.getData(_derivative.oracleId, _derivative.endTime); } else { data = 0; } uint256[2] memory payoutRatio; // Get payout ratio from Derivative logic // payoutRatio[0] - buyerPayout // payoutRatio[1] - sellerPayout (payoutRatio[0], payoutRatio[1]) = IDerivativeLogic(_derivative.syntheticId).getExecutionPayout(_derivative, data); // Generate hash for derivative bytes32 derivativeHash = getDerivativeHash(_derivative); // Check if ticker was canceled require(!cancelled[derivativeHash], ERROR_CORE_TICKER_WAS_CANCELLED); uint256[2] memory margins; // Get cached total margin required from Opium.SyntheticAggregator // margins[0] - buyerMargin // margins[1] - sellerMargin (margins[0], margins[1]) = _vars.syntheticAggregator.getMargin(derivativeHash, _derivative); uint256[2] memory payouts; // Calculate payouts from ratio // payouts[0] -> buyerPayout = (buyerMargin + sellerMargin) * buyerPayoutRatio / (buyerPayoutRatio + sellerPayoutRatio) // payouts[1] -> sellerPayout = (buyerMargin + sellerMargin) * sellerPayoutRatio / (buyerPayoutRatio + sellerPayoutRatio) payouts[0] = margins[0].add(margins[1]).mul(payoutRatio[0]).div(payoutRatio[0].add(payoutRatio[1])); payouts[1] = margins[0].add(margins[1]).mul(payoutRatio[1]).div(payoutRatio[0].add(payoutRatio[1])); // Check if `_tokenId` is an ID of LONG position if (derivativeHash.getLongTokenId() == _tokenId) { // Check if it's a pooled position if (_vars.syntheticAggregator.isPool(derivativeHash, _derivative)) { // Pooled position payoutRatio is considered as full payout, not as payoutRatio payout = payoutRatio[0]; // Multiply payout by quantity payout = payout.mul(_quantity); // Check sufficiency of syntheticId balance in poolVaults require( poolVaults[_derivative.syntheticId][_derivative.token] >= payout , ERROR_CORE_INSUFFICIENT_POOL_BALANCE ); // Subtract paid out margin from poolVault poolVaults[_derivative.syntheticId][_derivative.token] = poolVaults[_derivative.syntheticId][_derivative.token].sub(payout); } else { // Set payout to buyerPayout payout = payouts[0]; // Multiply payout by quantity payout = payout.mul(_quantity); } // Take fees only from profit makers // Check: payout > buyerMargin * quantity if (payout > margins[0].mul(_quantity)) { // Get Opium and `syntheticId` author fees and subtract it from payout payout = payout.sub(_getFees(_vars.syntheticAggregator, derivativeHash, _derivative, payout - margins[0].mul(_quantity))); } // Check if `_tokenId` is an ID of SHORT position } else if (derivativeHash.getShortTokenId() == _tokenId) { // Set payout to sellerPayout payout = payouts[1]; // Multiply payout by quantity payout = payout.mul(_quantity); // Take fees only from profit makers // Check: payout > sellerMargin * quantity if (payout > margins[1].mul(_quantity)) { // Get Opium fees and subtract it from payout payout = payout.sub(_getFees(_vars.syntheticAggregator, derivativeHash, _derivative, payout - margins[1].mul(_quantity))); } } else { // Either portfolioId, hack or bug revert(ERROR_CORE_UNKNOWN_POSITION_TYPE); } } /// @notice Calculates `syntheticId` author and opium fees from profit makers /// @param _syntheticAggregator SyntheticAggregator Instance of Opium.SyntheticAggregator /// @param _derivativeHash bytes32 Derivative hash /// @param _derivative Derivative Derivative definition /// @param _profit uint256 payout of one position /// @return fee uint256 Opium and `syntheticId` author fee function _getFees(SyntheticAggregator _syntheticAggregator, bytes32 _derivativeHash, Derivative memory _derivative, uint256 _profit) private returns (uint256 fee) { // Get cached `syntheticId` author address from Opium.SyntheticAggregator address authorAddress = _syntheticAggregator.getAuthorAddress(_derivativeHash, _derivative); // Get cached `syntheticId` fee percentage from Opium.SyntheticAggregator uint256 commission = _syntheticAggregator.getAuthorCommission(_derivativeHash, _derivative); // Calculate fee // fee = profit * commission / COMMISSION_BASE fee = _profit.mul(commission).div(COMMISSION_BASE); // If commission is zero, finish if (fee == 0) { return 0; } // Calculate opium fee // opiumFee = fee * OPIUM_COMMISSION_PART / OPIUM_COMMISSION_BASE uint256 opiumFee = fee.mul(OPIUM_COMMISSION_PART).div(OPIUM_COMMISSION_BASE); // Calculate author fee // authorFee = fee - opiumFee uint256 authorFee = fee.sub(opiumFee); // Get opium address address opiumAddress = registry.getOpiumAddress(); // Update feeVault for Opium team // feesVault[opium][token] += opiumFee feesVaults[opiumAddress][_derivative.token] = feesVaults[opiumAddress][_derivative.token].add(opiumFee); // Update feeVault for `syntheticId` author // feeVault[author][token] += authorFee feesVaults[authorAddress][_derivative.token] = feesVaults[authorAddress][_derivative.token].add(authorFee); } } // File: contracts/Errors/MatchingErrors.sol pragma solidity 0.5.16; contract MatchingErrors { string constant internal ERROR_MATCH_CANCELLATION_NOT_ALLOWED = "MATCH:CANCELLATION_NOT_ALLOWED"; string constant internal ERROR_MATCH_ALREADY_CANCELED = "MATCH:ALREADY_CANCELED"; string constant internal ERROR_MATCH_ORDER_WAS_CANCELED = "MATCH:ORDER_WAS_CANCELED"; string constant internal ERROR_MATCH_TAKER_ADDRESS_WRONG = "MATCH:TAKER_ADDRESS_WRONG"; string constant internal ERROR_MATCH_ORDER_IS_EXPIRED = "MATCH:ORDER_IS_EXPIRED"; string constant internal ERROR_MATCH_SENDER_ADDRESS_WRONG = "MATCH:SENDER_ADDRESS_WRONG"; string constant internal ERROR_MATCH_SIGNATURE_NOT_VERIFIED = "MATCH:SIGNATURE_NOT_VERIFIED"; string constant internal ERROR_MATCH_NOT_ENOUGH_ALLOWED_FEES = "MATCH:NOT_ENOUGH_ALLOWED_FEES"; } // File: contracts/Lib/LibEIP712.sol pragma solidity 0.5.16; /// @title Opium.Lib.LibEIP712 contract implements the domain of EIP712 for meta transactions contract LibEIP712 { // EIP712Domain structure // name - protocol name // version - protocol version // verifyingContract - signed message verifying contract struct EIP712Domain { string name; string version; address verifyingContract; } // Calculate typehash of ERC712Domain bytes32 constant internal EIP712DOMAIN_TYPEHASH = keccak256(abi.encodePacked( "EIP712Domain(", "string name,", "string version,", "address verifyingContract", ")" )); // solhint-disable-next-line var-name-mixedcase bytes32 internal DOMAIN_SEPARATOR; // Calculate domain separator at creation constructor () public { DOMAIN_SEPARATOR = keccak256(abi.encode( EIP712DOMAIN_TYPEHASH, keccak256("Opium Network"), keccak256("1"), address(this) )); } /// @notice Hashes EIP712Message /// @param hashStruct bytes32 Hash of structured message /// @return result bytes32 Hash of EIP712Message function hashEIP712Message(bytes32 hashStruct) internal view returns (bytes32 result) { bytes32 domainSeparator = DOMAIN_SEPARATOR; assembly { // Load free memory pointer let memPtr := mload(64) mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header mstore(add(memPtr, 2), domainSeparator) // EIP712 domain hash mstore(add(memPtr, 34), hashStruct) // Hash of struct // Compute hash result := keccak256(memPtr, 66) } return result; } } // File: contracts/Matching/SwaprateMatch/LibSwaprateOrder.sol pragma solidity 0.5.16; /// @title Opium.Matching.SwaprateMatch.LibSwaprateOrder contract implements EIP712 signed SwaprateOrder for Opium.Matching.SwaprateMatch contract LibSwaprateOrder is LibEIP712 { /** Structure of order Description should be considered from the order signer (maker) perspective syntheticId - address of derivative syntheticId oracleId - address of derivative oracleId token - address of derivative margin token makerMarginAddress - address of token that maker is willing to pay with takerMarginAddress - address of token that maker is willing to receive makerAddress - address of maker takerAddress - address of counterparty (taker). If zero address, then taker could be anyone senderAddress - address which is allowed to settle the order on-chain. If zero address, then anyone could settle relayerAddress - address of the relayer fee recipient affiliateAddress - address of the affiliate fee recipient feeTokenAddress - address of token which is used for fees endTime - timestamp of derivative maturity quantity - quantity of positions maker wants to receive partialFill - whether maker allows partial fill of it's order param0...param9 - additional params to pass it to syntheticId relayerFee - amount of fee in feeToken that should be paid to relayer affiliateFee - amount of fee in feeToken that should be paid to affiliate nonce - unique order ID signature - Signature of EIP712 message. Not used in hash, but then set for order processing purposes */ struct SwaprateOrder { address syntheticId; address oracleId; address token; address makerAddress; address takerAddress; address senderAddress; address relayerAddress; address affiliateAddress; address feeTokenAddress; uint256 endTime; uint256 quantity; uint256 partialFill; uint256 param0; uint256 param1; uint256 param2; uint256 param3; uint256 param4; uint256 param5; uint256 param6; uint256 param7; uint256 param8; uint256 param9; uint256 relayerFee; uint256 affiliateFee; uint256 nonce; // Not used in hash bytes signature; } // Calculate typehash of Order bytes32 constant internal EIP712_ORDER_TYPEHASH = keccak256(abi.encodePacked( "Order(", "address syntheticId,", "address oracleId,", "address token,", "address makerAddress,", "address takerAddress,", "address senderAddress,", "address relayerAddress,", "address affiliateAddress,", "address feeTokenAddress,", "uint256 endTime,", "uint256 quantity,", "uint256 partialFill,", "uint256 param0,", "uint256 param1,", "uint256 param2,", "uint256 param3,", "uint256 param4,", "uint256 param5,", "uint256 param6,", "uint256 param7,", "uint256 param8,", "uint256 param9,", "uint256 relayerFee,", "uint256 affiliateFee,", "uint256 nonce", ")" )); /// @notice Hashes the order /// @param _order SwaprateOrder Order to hash /// @return hash bytes32 Order hash function hashOrder(SwaprateOrder memory _order) public pure returns (bytes32 hash) { hash = keccak256( abi.encodePacked( abi.encodePacked( EIP712_ORDER_TYPEHASH, uint256(_order.syntheticId), uint256(_order.oracleId), uint256(_order.token), uint256(_order.makerAddress), uint256(_order.takerAddress), uint256(_order.senderAddress), uint256(_order.relayerAddress), uint256(_order.affiliateAddress), uint256(_order.feeTokenAddress) ), abi.encodePacked( _order.endTime, _order.quantity, _order.partialFill ), abi.encodePacked( _order.param0, _order.param1, _order.param2, _order.param3, _order.param4 ), abi.encodePacked( _order.param5, _order.param6, _order.param7, _order.param8, _order.param9 ), abi.encodePacked( _order.relayerFee, _order.affiliateFee, _order.nonce ) ) ); } /// @notice Verifies order signature /// @param _hash bytes32 Hash of the order /// @param _signature bytes Signature of the order /// @param _address address Address of the order signer /// @return bool Returns whether `_signature` is valid and was created by `_address` function verifySignature(bytes32 _hash, bytes memory _signature, address _address) internal view returns (bool) { require(_signature.length == 65, "ORDER:INVALID_SIGNATURE_LENGTH"); bytes32 digest = hashEIP712Message(_hash); address recovered = retrieveAddress(digest, _signature); return _address == recovered; } /// @notice Helping function to recover signer address /// @param _hash bytes32 Hash for signature /// @param _signature bytes Signature /// @return address Returns address of signature creator function retrieveAddress(bytes32 _hash, bytes memory _signature) private pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := byte(0, mload(add(_signature, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(_hash, v, r, s); } } } // File: contracts/Matching/SwaprateMatch/SwaprateMatchBase.sol pragma solidity 0.5.16; /// @title Opium.Matching.SwaprateMatchBase contract implements logic for order validation and cancelation contract SwaprateMatchBase is MatchingErrors, LibSwaprateOrder, UsingRegistry, ReentrancyGuard { using SafeMath for uint256; using LibPosition for bytes32; using SafeERC20 for IERC20; // Emmitted when order was canceled event Canceled(bytes32 orderHash); // Canceled orders // This mapping holds hashes of canceled orders // canceled[orderHash] => canceled mapping (bytes32 => bool) public canceled; // Verified orders // This mapping holds hashes of verified orders to verify only once // verified[orderHash] => verified mapping (bytes32 => bool) public verified; // Vaults for fees // This mapping holds balances of relayers and affiliates fees to withdraw // balances[feeRecipientAddress][tokenAddress] => balances mapping (address => mapping (address => uint256)) public balances; // Keeps whether fee was already taken mapping (bytes32 => bool) public feeTaken; /// @notice Calling this function maker of the order could cancel it on-chain /// @param _order SwaprateOrder function cancel(SwaprateOrder memory _order) public { require(msg.sender == _order.makerAddress, ERROR_MATCH_CANCELLATION_NOT_ALLOWED); bytes32 orderHash = hashOrder(_order); require(!canceled[orderHash], ERROR_MATCH_ALREADY_CANCELED); canceled[orderHash] = true; emit Canceled(orderHash); } /// @notice Function to withdraw fees from orders for relayer and affiliates /// @param _token IERC20 Instance of token to withdraw function withdraw(IERC20 _token) public nonReentrant { uint256 balance = balances[msg.sender][address(_token)]; balances[msg.sender][address(_token)] = 0; _token.safeTransfer(msg.sender, balance); } /// @notice This function checks whether order was canceled /// @param _hash bytes32 Hash of the order function validateNotCanceled(bytes32 _hash) internal view { require(!canceled[_hash], ERROR_MATCH_ORDER_WAS_CANCELED); } /// @notice This function validates takerAddress of _leftOrder. It should match either with _rightOrder.makerAddress or be set to zero address /// @param _leftOrder SwaprateOrder Left order /// @param _rightOrder SwaprateOrder Right order function validateTakerAddress(SwaprateOrder memory _leftOrder, SwaprateOrder memory _rightOrder) pure internal { require( _leftOrder.takerAddress == address(0) || _leftOrder.takerAddress == _rightOrder.makerAddress, ERROR_MATCH_TAKER_ADDRESS_WRONG ); } /// @notice This function validates whether sender address equals to `msg.sender` or set to zero address /// @param _order SwaprateOrder function validateSenderAddress(SwaprateOrder memory _order) internal view { require( _order.senderAddress == address(0) || _order.senderAddress == msg.sender, ERROR_MATCH_SENDER_ADDRESS_WRONG ); } /// @notice This function validates order signature if not validated before /// @param orderHash bytes32 Hash of the order /// @param _order SwaprateOrder function validateSignature(bytes32 orderHash, SwaprateOrder memory _order) internal { if (verified[orderHash]) { return; } bool result = verifySignature(orderHash, _order.signature, _order.makerAddress); require(result, ERROR_MATCH_SIGNATURE_NOT_VERIFIED); verified[orderHash] = true; } /// @notice This function is responsible for taking relayer and affiliate fees, if they were not taken already /// @param _orderHash bytes32 Hash of the order /// @param _order Order Order itself function takeFees(bytes32 _orderHash, SwaprateOrder memory _order) internal { // Check if fee was already taken if (feeTaken[_orderHash]) { return; } // Check if feeTokenAddress is not set to zero address if (_order.feeTokenAddress == address(0)) { return; } // Calculate total amount of fees needs to be transfered uint256 fees = _order.relayerFee.add(_order.affiliateFee); // If total amount of fees is non-zero if (fees == 0) { return; } // Create instance of fee token IERC20 feeToken = IERC20(_order.feeTokenAddress); // Create instance of TokenSpender TokenSpender tokenSpender = TokenSpender(registry.getTokenSpender()); // Check if user has enough token approval to pay the fees require(feeToken.allowance(_order.makerAddress, address(tokenSpender)) >= fees, ERROR_MATCH_NOT_ENOUGH_ALLOWED_FEES); // Transfer fee tokenSpender.claimTokens(feeToken, _order.makerAddress, address(this), fees); // Get opium address address opiumAddress = registry.getOpiumAddress(); // Add commission to relayer balance, or to opium balance if relayer is not set if (_order.relayerAddress != address(0)) { balances[_order.relayerAddress][_order.feeTokenAddress] = balances[_order.relayerAddress][_order.feeTokenAddress].add(_order.relayerFee); } else { balances[opiumAddress][_order.feeTokenAddress] = balances[opiumAddress][_order.feeTokenAddress].add(_order.relayerFee); } // Add commission to affiliate balance, or to opium balance if affiliate is not set if (_order.affiliateAddress != address(0)) { balances[_order.affiliateAddress][_order.feeTokenAddress] = balances[_order.affiliateAddress][_order.feeTokenAddress].add(_order.affiliateFee); } else { balances[opiumAddress][_order.feeTokenAddress] = balances[opiumAddress][_order.feeTokenAddress].add(_order.affiliateFee); } // Mark the fee of token as taken feeTaken[_orderHash] = true; } /// @notice Helper to get minimal of two integers /// @param _a uint256 First integer /// @param _b uint256 Second integer /// @return uint256 Minimal integer function min(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a < _b ? _a : _b; } } // File: contracts/Matching/SwaprateMatch/SwaprateMatch.sol pragma solidity 0.5.16; /// @title Opium.Matching.SwaprateMatch contract implements create() function to settle a pair of orders and create derivatives for order makers contract SwaprateMatch is SwaprateMatchBase, LibDerivative { // Orders filled quantity // This mapping holds orders filled quantity // filled[orderHash] => filled mapping (bytes32 => uint256) public filled; /// @notice Calls constructors of super-contracts /// @param _registry address Address of Opium.registry constructor (address _registry) public UsingRegistry(_registry) {} /// @notice This function receives left and right orders, derivative related to it /// @param _leftOrder Order /// @param _rightOrder Order /// @param _derivative Derivative Data of derivative for validation and calculation purposes function create(SwaprateOrder memory _leftOrder, SwaprateOrder memory _rightOrder, Derivative memory _derivative) public nonReentrant { // New deals must not offer tokenIds require( _leftOrder.syntheticId == _rightOrder.syntheticId, "MATCH:NOT_CREATION" ); // Check if it's not pool require(!IDerivativeLogic(_derivative.syntheticId).isPool(), "MATCH:CANT_BE_POOL"); // Validate taker if set validateTakerAddress(_leftOrder, _rightOrder); validateTakerAddress(_rightOrder, _leftOrder); // Validate sender if set validateSenderAddress(_leftOrder); validateSenderAddress(_rightOrder); // Validate if was canceled // orderHashes[0] - leftOrderHash // orderHashes[1] - rightOrderHash bytes32[2] memory orderHashes; orderHashes[0] = hashOrder(_leftOrder); validateNotCanceled(orderHashes[0]); validateSignature(orderHashes[0], _leftOrder); orderHashes[1] = hashOrder(_rightOrder); validateNotCanceled(orderHashes[1]); validateSignature(orderHashes[1], _rightOrder); // Calculate derivative hash and get margin // margins[0] - leftMargin // margins[1] - rightMargin (uint256[2] memory margins, ) = _calculateDerivativeAndGetMargin(_derivative); // Calculate and validate availabilities of orders and fill them uint256 fillable = _checkFillability(orderHashes[0], _leftOrder, orderHashes[1], _rightOrder); // Validate derivative parameters with orders _verifyDerivative(_leftOrder, _rightOrder, _derivative); // Take fees takeFees(orderHashes[0], _leftOrder); takeFees(orderHashes[1], _rightOrder); // Send margin to Core _distributeFunds(_leftOrder, _rightOrder, _derivative, margins, fillable); // Settle contracts Core(registry.getCore()).create(_derivative, fillable, [_leftOrder.makerAddress, _rightOrder.makerAddress]); } // PRIVATE FUNCTIONS /// @notice Calculates derivative hash and gets margin /// @param _derivative Derivative /// @return margins uint256[2] left and right margin /// @return derivativeHash bytes32 Hash of the derivative function _calculateDerivativeAndGetMargin(Derivative memory _derivative) private returns (uint256[2] memory margins, bytes32 derivativeHash) { // Calculate derivative related data for validation derivativeHash = getDerivativeHash(_derivative); // Get cached total margin required according to logic // margins[0] - leftMargin // margins[1] - rightMargin (margins[0], margins[1]) = SyntheticAggregator(registry.getSyntheticAggregator()).getMargin(derivativeHash, _derivative); } /// @notice Calculate and validate availabilities of orders and fill them /// @param _leftOrderHash bytes32 /// @param _leftOrder SwaprateOrder /// @param _rightOrderHash bytes32 /// @param _rightOrder SwaprateOrder /// @return fillable uint256 function _checkFillability(bytes32 _leftOrderHash, SwaprateOrder memory _leftOrder, bytes32 _rightOrderHash, SwaprateOrder memory _rightOrder) private returns (uint256 fillable) { // Calculate availabilities of orders uint256 leftAvailable = _leftOrder.quantity.sub(filled[_leftOrderHash]); uint256 rightAvailable = _rightOrder.quantity.sub(filled[_rightOrderHash]); require(leftAvailable != 0 && rightAvailable !=0, "MATCH:NO_AVAILABLE"); // We could only fill minimum available of both counterparties fillable = min(leftAvailable, rightAvailable); // Check fillable with order conditions about partial fill requirements if (_leftOrder.partialFill == 0 && _rightOrder.partialFill == 0) { require(_leftOrder.quantity == _rightOrder.quantity, "MATCH:FULL_FILL_NOT_POSSIBLE"); } else if (_leftOrder.partialFill == 0 && _rightOrder.partialFill == 1) { require(_leftOrder.quantity <= rightAvailable, "MATCH:FULL_FILL_NOT_POSSIBLE"); } else if (_leftOrder.partialFill == 1 && _rightOrder.partialFill == 0) { require(leftAvailable >= _rightOrder.quantity, "MATCH:FULL_FILL_NOT_POSSIBLE"); } // Update filled filled[_leftOrderHash] = filled[_leftOrderHash].add(fillable); filled[_rightOrderHash] = filled[_rightOrderHash].add(fillable); } /// @notice Validate derivative parameters with orders /// @param _leftOrder SwaprateOrder /// @param _rightOrder SwaprateOrder /// @param _derivative Derivative function _verifyDerivative(SwaprateOrder memory _leftOrder, SwaprateOrder memory _rightOrder, Derivative memory _derivative) private pure { string memory orderError = "MATCH:DERIVATIVE_PARAM_IS_WRONG"; // Validate derivative endTime require( _derivative.endTime == _leftOrder.endTime && _derivative.endTime == _rightOrder.endTime, orderError ); // Validate derivative syntheticId require( _derivative.syntheticId == _leftOrder.syntheticId && _derivative.syntheticId == _rightOrder.syntheticId, orderError ); // Validate derivative oracleId require( _derivative.oracleId == _leftOrder.oracleId && _derivative.oracleId == _rightOrder.oracleId, orderError ); // Validate derivative token require( _derivative.token == _leftOrder.token && _derivative.token == _rightOrder.token, orderError ); // Validate derivative params require(_derivative.params.length >= 20, "MATCH:DERIVATIVE_PARAMS_LENGTH_IS_WRONG"); // Validate left order params require(_leftOrder.param0 == _derivative.params[0], orderError); require(_leftOrder.param1 == _derivative.params[1], orderError); require(_leftOrder.param2 == _derivative.params[2], orderError); require(_leftOrder.param3 == _derivative.params[3], orderError); require(_leftOrder.param4 == _derivative.params[4], orderError); require(_leftOrder.param5 == _derivative.params[5], orderError); require(_leftOrder.param6 == _derivative.params[6], orderError); require(_leftOrder.param7 == _derivative.params[7], orderError); require(_leftOrder.param8 == _derivative.params[8], orderError); require(_leftOrder.param9 == _derivative.params[9], orderError); // Validate right order params require(_rightOrder.param0 == _derivative.params[10], orderError); require(_rightOrder.param1 == _derivative.params[11], orderError); require(_rightOrder.param2 == _derivative.params[12], orderError); require(_rightOrder.param3 == _derivative.params[13], orderError); require(_rightOrder.param4 == _derivative.params[14], orderError); require(_rightOrder.param5 == _derivative.params[15], orderError); require(_rightOrder.param6 == _derivative.params[16], orderError); require(_rightOrder.param7 == _derivative.params[17], orderError); require(_rightOrder.param8 == _derivative.params[18], orderError); require(_rightOrder.param9 == _derivative.params[19], orderError); } /// @notice Distributes funds to core /// @param _leftOrder SwaprateOrder /// @param _rightOrder SwaprateOrder /// @param _derivative Derivative /// @param margins uint256[2] left and right margin /// @param _fillable uint256 How many positions are fillable function _distributeFunds(SwaprateOrder memory _leftOrder, SwaprateOrder memory _rightOrder, Derivative memory _derivative, uint256[2] memory margins, uint256 _fillable) private { IERC20 marginToken = IERC20(_derivative.token); TokenSpender tokenSpender = TokenSpender(registry.getTokenSpender()); // Transfer margin from left to Match and send to Core if (margins[0] != 0) { // Check allowance for margins require(marginToken.allowance(_leftOrder.makerAddress, address(tokenSpender)) >= margins[0].mul(_fillable), "MATCH:NOT_ENOUGH_ALLOWED_MARGIN"); // Transfer margins from buyer to Match tokenSpender.claimTokens(marginToken, _leftOrder.makerAddress, address(this), margins[0].mul(_fillable)); } // Transfer margin from right to Match and send to Core if (margins[1] != 0) { // Check allowance for premiums + margin require(marginToken.allowance(_rightOrder.makerAddress, address(tokenSpender)) >= margins[1].mul(_fillable), "MATCH:NOT_ENOUGH_ALLOWED_MARGIN"); // Transfer margins from seller to Match tokenSpender.claimTokens(marginToken, _rightOrder.makerAddress, address(this), margins[1].mul(_fillable)); } if (margins[0].add(margins[1]) != 0) { // Approve margin to Core for derivative creation require(marginToken.approve(address(tokenSpender), margins[0].add(margins[1]).mul(_fillable)), "MATCH:COULDNT_APPROVE_MARGIN_FOR_CORE"); } } }
Returns whether the specified token exists _tokenId uint256 ID of the token to query the existence of return whether the token exists/
function exists(uint256 _tokenId) public view returns (bool) { return tokenTypes[_tokenId] != INVALID; }
1,368,016
/** *Submitted for verification at Etherscan.io on 2022-04-15 */ /** * We Are The Beginning But Not The End */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); } interface IUniswapV2Router02 is IUniswapV2Router01 { function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } interface IUniswapV2Pair { function sync() external; } /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address 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); } } /** * @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 ); } /** * @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); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require( currentAllowance >= amount, "ERC20: transfer amount exceeds allowance" ); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender] + addedValue ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require( currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero" ); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require( senderBalance >= amount, "ERC20: transfer amount exceeds balance" ); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // 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 generally not needed starting with Solidity 0.8, since 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; } } } contract UltraAlpha is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 20; // 20 = .20% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public constant buyMarketingFee = 12; uint256 public constant buyLiquidityFee = 0; uint256 public constant buyDevFee = 0; uint256 public sellTotalFees; uint256 public constant sellMarketingFee = 12; uint256 public constant sellLiquidityFee = 0; uint256 public constant sellDevFee = 0; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping(address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated( address indexed newWallet, address indexed oldWallet ); event devWalletUpdated( address indexed newWallet, address indexed oldWallet ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); event BoughtEarly(address indexed sniper); constructor() ERC20("UltraAlpha", "UltraAlpha") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 totalSupply = 1_000_000_000 * 1e18; // 1 billion total supply maxTransactionAmount = 15_000_000 * 1e18; // 1.5% from total supply maxTransactionAmountTxn maxWallet = 30_000_000 * 1e18; // 3% from total supply maxWallet swapTokensAtAmount = (totalSupply * 3) / 10000; // 0.03% swap wallet buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(0x027DEAE9E907E92312288Fc873921A795e5F26Fd); // set as marketing wallet devWallet = address(0x027DEAE9E907E92312288Fc873921A795e5F26Fd); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable {} // once enabled, can never be turned off function startTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require( newAmount >= (totalSupply() * 1) / 100000, "Swap amount cannot be lower than 0.001% total supply." ); require( newAmount <= (totalSupply() * 5) / 1000, "Swap amount cannot be higher than 0.5% total supply." ); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 1) / 1000) / 1e18, "Cannot set maxTransactionAmount lower than 0.1%" ); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 5) / 1000) / 1e18, "Cannot set maxWallet lower than 0.5%" ); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } //when sell else if ( automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } else if (!_isExcludedMaxTransactionAmount[to]) { require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if (takeFee) { // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } // on buy else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success, ) = address(devWallet).call{value: ethForDev}(""); if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function setAutoLPBurnSettings( uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled ) external onlyOwner { require( _frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes" ); require( _percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%" ); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) { require( block.timestamp > lastManualLpBurnTime + manualBurnFrequency, "Must wait for cooldown to finish" ); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
exclude from paying fees or having max transaction amount
constructor() ERC20("UltraAlpha", "UltraAlpha") { 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); buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
7,863,058
//SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "./interface/IiToken.sol"; import "./interface/IRewardDistributor.sol"; import "./interface/IPriceOracle.sol"; import "./library/Initializable.sol"; import "./library/Ownable.sol"; import "./library/SafeRatioMath.sol"; import "./Controller.sol"; /** * @title dForce's lending reward distributor Contract * @author dForce */ contract RewardDistributor is Initializable, Ownable, IRewardDistributor { using SafeRatioMath for uint256; using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; /// @notice the controller Controller public controller; /// @notice the global Reward distribution speed uint256 public globalDistributionSpeed; /// @notice the Reward distribution speed of each iToken mapping(address => uint256) public distributionSpeed; /// @notice the Reward distribution factor of each iToken, 1.0 by default. stored as a mantissa mapping(address => uint256) public distributionFactorMantissa; struct DistributionState { // Token's last updated index, stored as a mantissa uint256 index; // The block number the index was last updated at uint256 block; } /// @notice the Reward distribution supply state of each iToken mapping(address => DistributionState) public distributionSupplyState; /// @notice the Reward distribution borrow state of each iToken mapping(address => DistributionState) public distributionBorrowState; /// @notice the Reward distribution state of each account of each iToken mapping(address => mapping(address => uint256)) public distributionSupplierIndex; /// @notice the Reward distribution state of each account of each iToken mapping(address => mapping(address => uint256)) public distributionBorrowerIndex; /// @notice the Reward distributed into each account mapping(address => uint256) public reward; /// @notice the Reward token address address public rewardToken; /// @notice whether the reward distribution is paused bool public paused; /// @notice the Reward distribution speed supply side of each iToken mapping(address => uint256) public distributionSupplySpeed; /// @notice the global Reward distribution speed for supply uint256 public globalDistributionSupplySpeed; /** * @dev Throws if called by any account other than the controller. */ modifier onlyController() { require( address(controller) == msg.sender, "onlyController: caller is not the controller" ); _; } /** * @notice Initializes the contract. */ function initialize(Controller _controller) external initializer { require( address(_controller) != address(0), "initialize: controller address should not be zero address!" ); __Ownable_init(); controller = _controller; paused = true; } /** * @notice set reward token address * @dev Admin function, only owner can call this * @param _newRewardToken the address of reward token */ function _setRewardToken(address _newRewardToken) external override onlyOwner { address _oldRewardToken = rewardToken; require( _newRewardToken != address(0) && _newRewardToken != _oldRewardToken, "Reward token address invalid" ); rewardToken = _newRewardToken; emit NewRewardToken(_oldRewardToken, _newRewardToken); } /** * @notice Add the iToken as receipient * @dev Admin function, only controller can call this * @param _iToken the iToken to add as recipient * @param _distributionFactor the distribution factor of the recipient */ function _addRecipient(address _iToken, uint256 _distributionFactor) external override onlyController { distributionFactorMantissa[_iToken] = _distributionFactor; distributionSupplyState[_iToken] = DistributionState({ index: 0, block: block.number }); distributionBorrowState[_iToken] = DistributionState({ index: 0, block: block.number }); emit NewRecipient(_iToken, _distributionFactor); } /** * @notice Pause the reward distribution * @dev Admin function, pause will set global speed to 0 to stop the accumulation */ function _pause() external override onlyOwner { // Set the global distribution speed to 0 to stop accumulation _setGlobalDistributionSpeeds(0, 0); _setPaused(true); } /** * @notice Unpause and set global distribution speed * @dev Admin function * @param _borrowSpeed The speed of Reward distribution to borrow side per second * @param _supplySpeed The speed of Reward distribution to supply side per second */ function _unpause(uint256 _borrowSpeed, uint256 _supplySpeed) external override onlyOwner { _setPaused(false); _setGlobalDistributionSpeeds(_borrowSpeed, _supplySpeed); } /** * @notice Pause/Unpause the reward distribution * @dev Admin function * @param _paused whether to pause/unpause the distribution */ function _setPaused(bool _paused) internal { paused = _paused; emit Paused(_paused); } /** * @notice Sets the global distribution speed, updating each iToken's speed accordingly * @dev Admin function, will fail when paused * @param _supplySpeed The speed of Reward distribution to supply side per second * @param _borrowSpeed The speed of Reward distribution to borrow side per per second */ function _setGlobalDistributionSpeeds( uint256 _borrowSpeed, uint256 _supplySpeed ) public override onlyOwner { require(!paused, "Can not change global speed when paused"); globalDistributionSpeed = _borrowSpeed; globalDistributionSupplySpeed = _supplySpeed; _updateDistributionSpeed(); emit GlobalDistributionSpeedsUpdated(_borrowSpeed, _supplySpeed); } /** * @notice Update each iToken's distribution speed according to current global speed * @dev Only EOA can call this function */ function updateDistributionSpeed() public override { require(msg.sender == tx.origin, "only EOA can update speeds"); require(!paused, "Can not update speeds when paused"); // Do the actual update _updateDistributionSpeed(); } /** * @notice Internal function to update each iToken's distribution speed */ function _updateDistributionSpeed() internal { address[] memory _iTokens = controller.getAlliTokens(); uint256 _globalBorrowSpeed = globalDistributionSpeed; uint256 _globalSupplySpeed = globalDistributionSupplySpeed; uint256 _len = _iTokens.length; uint256[] memory _tokenBorrowValues = new uint256[](_len); uint256 _totalBorrowValue; uint256[] memory _tokenSupplyValues = new uint256[](_len); uint256 _totalSupplyValue; // Calculates the total value and token value // tokenValue = tokenTotalBorrow * price * tokenDistributionFactorMantissa for (uint256 i = 0; i < _len; i++) { IiToken _token = IiToken(_iTokens[i]); // Update both supply and borrow state before updating new speed _updateDistributionState(address(_token), true); _updateDistributionState(address(_token), false); uint256 _totalBorrow = _token.totalBorrows(); uint256 _totalSupply = IERC20Upgradeable(_iTokens[i]).totalSupply(); // It is okay if the underlying price is 0 uint256 _underlyingPrice = IPriceOracle(controller.priceOracle()).getUnderlyingPrice( address(_token) ); _tokenBorrowValues[i] = _totalBorrow.mul(_underlyingPrice).rmul( distributionFactorMantissa[address(_token)] ); _tokenSupplyValues[i] = _totalSupply .rmul(_token.exchangeRateStored()) .mul(_underlyingPrice) .rmul(distributionFactorMantissa[address(_token)]); _totalBorrowValue = _totalBorrowValue.add(_tokenBorrowValues[i]); _totalSupplyValue = _totalSupplyValue.add(_tokenSupplyValues[i]); } // Calculates the distribution speed for each token for (uint256 i = 0; i < _len; i++) { address _token = _iTokens[i]; uint256 _borrowSpeed = _totalBorrowValue > 0 ? _globalBorrowSpeed.mul(_tokenBorrowValues[i]).div( _totalBorrowValue ) : 0; distributionSpeed[_token] = _borrowSpeed; uint256 _supplySpeed = _totalSupplyValue > 0 ? _globalSupplySpeed.mul(_tokenSupplyValues[i]).div( _totalSupplyValue ) : 0; distributionSupplySpeed[_token] = _supplySpeed; emit DistributionSpeedsUpdated(_token, _borrowSpeed, _supplySpeed); } } /** * @notice Sets the distribution factor for a iToken * @dev Admin function to set distribution factor for a iToken * @param _iToken The token to set the factor on * @param _newDistributionFactorMantissa The new distribution factor, scaled by 1e18 */ function _setDistributionFactor( address _iToken, uint256 _newDistributionFactorMantissa ) internal { // iToken must have been listed require(controller.hasiToken(_iToken), "Token has not been listed"); uint256 _oldDistributionFactorMantissa = distributionFactorMantissa[_iToken]; distributionFactorMantissa[_iToken] = _newDistributionFactorMantissa; emit NewDistributionFactor( _iToken, _oldDistributionFactorMantissa, _newDistributionFactorMantissa ); } /** * @notice Sets the distribution factors for a list of iTokens * @dev Admin function to set distribution factors for a list of iTokens * @param _iTokens The list of tokens to set the factor on * @param _distributionFactors The list of distribution factors, scaled by 1e18 */ function _setDistributionFactors( address[] calldata _iTokens, uint256[] calldata _distributionFactors ) external override onlyOwner { require( _iTokens.length == _distributionFactors.length, "Length of _iTokens and _distributionFactors mismatch" ); require(!paused, "Can not update distribution factors when paused"); uint256 _len = _iTokens.length; for (uint256 i = 0; i < _len; i++) { _setDistributionFactor(_iTokens[i], _distributionFactors[i]); } // Update the distribution speed of all iTokens _updateDistributionSpeed(); } /** * @notice Update the iToken's Reward distribution state * @dev Will be called every time when the iToken's supply/borrow changes * @param _iToken The iToken to be updated * @param _isBorrow whether to update the borrow state */ function updateDistributionState(address _iToken, bool _isBorrow) external override { // Skip all updates if it is paused if (paused) { return; } _updateDistributionState(_iToken, _isBorrow); } function _updateDistributionState(address _iToken, bool _isBorrow) internal { require(controller.hasiToken(_iToken), "Token has not been listed"); DistributionState storage state = _isBorrow ? distributionBorrowState[_iToken] : distributionSupplyState[_iToken]; uint256 _speed = _isBorrow ? distributionSpeed[_iToken] : distributionSupplySpeed[_iToken]; uint256 _blockNumber = block.number; uint256 _deltaBlocks = _blockNumber.sub(state.block); if (_deltaBlocks > 0 && _speed > 0) { uint256 _totalToken = _isBorrow ? IiToken(_iToken).totalBorrows().rdiv( IiToken(_iToken).borrowIndex() ) : IERC20Upgradeable(_iToken).totalSupply(); uint256 _totalDistributed = _speed.mul(_deltaBlocks); // Reward distributed per token since last time uint256 _distributedPerToken = _totalToken > 0 ? _totalDistributed.rdiv(_totalToken) : 0; state.index = state.index.add(_distributedPerToken); } state.block = _blockNumber; } /** * @notice Update the account's Reward distribution state * @dev Will be called every time when the account's supply/borrow changes * @param _iToken The iToken to be updated * @param _account The account to be updated * @param _isBorrow whether to update the borrow state */ function updateReward( address _iToken, address _account, bool _isBorrow ) external override { _updateReward(_iToken, _account, _isBorrow); } function _updateReward( address _iToken, address _account, bool _isBorrow ) internal { require(_account != address(0), "Invalid account address!"); require(controller.hasiToken(_iToken), "Token has not been listed"); uint256 _iTokenIndex; uint256 _accountIndex; uint256 _accountBalance; if (_isBorrow) { _iTokenIndex = distributionBorrowState[_iToken].index; _accountIndex = distributionBorrowerIndex[_iToken][_account]; _accountBalance = IiToken(_iToken) .borrowBalanceStored(_account) .rdiv(IiToken(_iToken).borrowIndex()); // Update the account state to date distributionBorrowerIndex[_iToken][_account] = _iTokenIndex; } else { _iTokenIndex = distributionSupplyState[_iToken].index; _accountIndex = distributionSupplierIndex[_iToken][_account]; _accountBalance = IERC20Upgradeable(_iToken).balanceOf(_account); // Update the account state to date distributionSupplierIndex[_iToken][_account] = _iTokenIndex; } uint256 _deltaIndex = _iTokenIndex.sub(_accountIndex); uint256 _amount = _accountBalance.rmul(_deltaIndex); if (_amount > 0) { reward[_account] = reward[_account].add(_amount); emit RewardDistributed(_iToken, _account, _amount, _accountIndex); } } /** * @notice Update reward accrued in iTokens by the holders regardless of paused or not * @param _holders The account to update * @param _iTokens The _iTokens to update */ function updateRewardBatch( address[] memory _holders, address[] memory _iTokens ) public override { // Update rewards for all _iTokens for holders for (uint256 i = 0; i < _iTokens.length; i++) { address _iToken = _iTokens[i]; _updateDistributionState(_iToken, false); _updateDistributionState(_iToken, true); for (uint256 j = 0; j < _holders.length; j++) { _updateReward(_iToken, _holders[j], false); _updateReward(_iToken, _holders[j], true); } } } /** * @notice Claim reward accrued in iTokens by the holders * @param _holders The account to claim for * @param _iTokens The _iTokens to claim from */ function claimReward(address[] memory _holders, address[] memory _iTokens) public override { updateRewardBatch(_holders, _iTokens); // Withdraw all reward for all holders for (uint256 j = 0; j < _holders.length; j++) { address _account = _holders[j]; uint256 _reward = reward[_account]; if (_reward > 0) { reward[_account] = 0; IERC20Upgradeable(rewardToken).safeTransfer(_account, _reward); } } } /** * @notice Claim reward accrued in all iTokens by the holders * @param _holders The account to claim for */ function claimAllReward(address[] memory _holders) external override { claimReward(_holders, controller.getAlliTokens()); } }
Sets the global distribution speed, updating each iToken's speed accordingly Admin function, will fail when paused _supplySpeed The speed of Reward distribution to supply side per second _borrowSpeed The speed of Reward distribution to borrow side per per second/
function _setGlobalDistributionSpeeds( uint256 _borrowSpeed, uint256 _supplySpeed ) public override onlyOwner { require(!paused, "Can not change global speed when paused"); globalDistributionSpeed = _borrowSpeed; globalDistributionSupplySpeed = _supplySpeed; _updateDistributionSpeed(); emit GlobalDistributionSpeedsUpdated(_borrowSpeed, _supplySpeed); }
6,366,959
pragma solidity ^0.4.11; /* * The MIT License (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 */ // A base contract that implements the following concepts: // 1. A smart contract with an owner // 2. Methods that can only be called by the owner // 3. Transferability of ownership contract Owned { // The address of the owner address public owner; // Constructor function Owned() { owner = msg.sender; } // A modifier that provides a pre-check as to whether the sender is the owner modifier _onlyOwner { if (msg.sender != owner) revert(); _; } // Transfers ownership to newOwner, given that the sender is the owner function transferOwnership(address newOwner) _onlyOwner { owner = newOwner; } } // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 contract Token is Owned { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant 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) 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) 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) returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } // Implementation of Token contract contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { //Default assumes totalSupply can't be over max (2^256 - 1). if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { //same as above. Replace this line with the following if you want to protect against wrapping uints. if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } /* This Token Contract implements the standard token functionality (https://github.com/ethereum/EIPs/issues/20) as well as the following OPTIONAL extras intended for use by humans. In other words. This is intended for deployment in something like a Token Factory or Mist wallet, and then used by humans. Imagine coins, currencies, shares, voting weight, etc. Machine-based, rapid creation of many tokens would not necessarily need these extra features or will be minted in other manners. 1) Initial Finite Supply (upon creation one specifies how much is minted). 2) In the absence of a token registry: Optional Decimal, Symbol & Name. 3) Optional approveAndCall() functionality to notify a contract if an approval() has occurred. .*/ contract HumanStandardToken is StandardToken { function() { //if ether is sent to this address, send it back. revert(); } /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = 'H0.1'; //human 0.1 standard. Just an arbitrary versioning scheme. function HumanStandardToken(uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol) { balances[msg.sender] = _initialAmount; // Give the creator all initial tokens totalSupply = _initialAmount; // Update total supply name = _tokenName; // Set the name for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if (!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) {revert();} return true; } } contract CapitalMiningToken is HumanStandardToken { /* Public variables of the token */ // Vanity variables uint256 public simulatedBlockNumber; uint256 public rewardScarcityFactor; // The factor by which the reward reduces uint256 public rewardReductionRate; // The number of blocks before the reward reduces // Reward related variables uint256 public blockInterval; // Simulate intended blocktime of BitCoin uint256 public rewardValue; // 50 units, to 8 decimal places uint256 public initialReward; // Assignment of initial reward // Payout related variables mapping (address => Account) public pendingPayouts; // Keep track of per-address contributions in this reward block mapping (uint => uint) public totalBlockContribution; // Keep track of total ether contribution per block mapping (uint => bool) public minedBlock; // Checks if block is mined // contains all variables required to disburse AQT to a contributor fairly struct Account { address addr; uint blockPayout; uint lastContributionBlockNumber; uint blockContribution; } uint public timeOfLastBlock; // Variable to keep track of when rewards were given // Constructor function CapitalMiningToken(string _name, uint8 _decimals, string _symbol, string _version, uint256 _initialAmount, uint _simulatedBlockNumber, uint _rewardScarcityFactor, uint _rewardHalveningRate, uint _blockInterval, uint _rewardValue) HumanStandardToken(_initialAmount, _name, _decimals, _symbol) { version = _version; simulatedBlockNumber = _simulatedBlockNumber; rewardScarcityFactor = _rewardScarcityFactor; rewardReductionRate = _rewardHalveningRate; blockInterval = _blockInterval; rewardValue = _rewardValue; initialReward = _rewardValue; timeOfLastBlock = now; } // function to call to contribute Ether to, in exchange for AQT in the next block // mine or updateAccount must be called at least 10 minutes from timeOfLastBlock to get the reward // minimum required contribution is 0.05 Ether function mine() payable _updateBlockAndRewardRate() _updateAccount() { // At this point it is safe to assume that the sender has received all his payouts for previous blocks require(msg.value >= 50 finney); totalBlockContribution[simulatedBlockNumber] += msg.value; // Update total contribution if (pendingPayouts[msg.sender].addr != msg.sender) {// If the sender has not contributed during this interval // Add his address and payout details to the contributor map pendingPayouts[msg.sender] = Account(msg.sender, rewardValue, simulatedBlockNumber, pendingPayouts[msg.sender].blockContribution + msg.value); minedBlock[simulatedBlockNumber] = true; } else {// the sender has contributed during this interval require(pendingPayouts[msg.sender].lastContributionBlockNumber == simulatedBlockNumber); pendingPayouts[msg.sender].blockContribution += msg.value; } return; } modifier _updateBlockAndRewardRate() { // Stop update if the time since last block is less than specified interval if ((now - timeOfLastBlock) >= blockInterval && minedBlock[simulatedBlockNumber] == true) { timeOfLastBlock = now; simulatedBlockNumber += 1; // update reward according to block number rewardValue = initialReward / (2 ** (simulatedBlockNumber / rewardReductionRate)); // 後で梨沙ちゃんと中本さんに見てもらったほうがいい( ´∀` ) // 毎回毎回計算するよりsimulatedBlockNumber%rewardReductionRateみたいな条件でやったらトランザクションが安くなりそう } _; } modifier _updateAccount() { if (pendingPayouts[msg.sender].addr == msg.sender && pendingPayouts[msg.sender].lastContributionBlockNumber < simulatedBlockNumber) { // もうブロックチェーンにのっているからやり直せないがこれ気持ち悪くない? uint payout = pendingPayouts[msg.sender].blockContribution * pendingPayouts[msg.sender].blockPayout / totalBlockContribution[pendingPayouts[msg.sender].lastContributionBlockNumber]; // これ分かりづらいから時間あれば分けてやって pendingPayouts[msg.sender] = Account(0, 0, 0, 0); // mint coins totalSupply += payout; balances[msg.sender] += payout; // broadcast transfer event to owner Transfer(0, owner, payout); // broadcast transfer event from owner to payee Transfer(owner, msg.sender, payout); } _; } function updateAccount() _updateBlockAndRewardRate() _updateAccount() {} function withdrawEther() _onlyOwner() { owner.transfer(this.balance); } } // This contract defines specific parameters that make the initialized coin Bitcoin-like contract Aequitas is CapitalMiningToken { // Constructor function Aequitas() CapitalMiningToken( "Aequitas", // name 8, // decimals "AQT", // symbol "0.1", // version 0, // initialAmount 0, // simulatedBlockNumber 2, // rewardScarcityFactor 210000, // rewardReductionRate 10 minutes, // blockInterval 5000000000 // rewardValue ){} }
Transfers ownership to newOwner, given that the sender is the owner
function transferOwnership(address newOwner) _onlyOwner { owner = newOwner; }
1,814,022
./full_match/5/0x999512dC124371E6B9ff43CE8D1AF83252F0C851/sources/lib/joe-v2/src/libraries/math/SafeCast.sol
Returns x on uint232 and check that it does not overflow x The value as an uint256 return y The value as an uint232/
function safe232(uint256 x) internal pure returns (uint232 y) { if ((y = uint232(x)) != x) revert SafeCast__Exceeds232Bits(); }
1,894,136
./partial_match/1/0xAE69a93945133c00B9985D9361A1cd882d107622/sources/TokenizedStrategy.sol
Sets the performance fee to be charged on reported gains. Can only be called by the current `management`. Denominated in Basis Points. So 100% == 10_000. Cannot be set less than the MIN_FEE. Cannot set greater than to MAX_FEE. _performanceFee New performance fee./
function setPerformanceFee(uint16 _performanceFee) external onlyManagement { require(_performanceFee >= MIN_FEE, "MIN FEE"); require(_performanceFee <= MAX_FEE, "MAX FEE"); _strategyStorage().performanceFee = _performanceFee; emit UpdatePerformanceFee(_performanceFee); }
16,059,400
./full_match/3/0x5C381C55E64BA3C1C0FC533F4c971D6b49ffc928/sources/contracts/frog.sol
Set base uRI baseURI_ base tokens uri/
function setBaseURI(string memory baseURI_) public onlyOwner { _setBaseURI(baseURI_); }
8,250,110
./partial_match/1/0x90B5D11E3Fd268879D99F9e8675622D11b097C02/sources/TG.sol
only owner can add supply controller/
function transferSupplyControllerRole(address newSupplyController) public override onlyOwner { super.transferSupplyControllerRole(newSupplyController); }
16,005,829
pragma solidity ^0.4.18; // File: contracts/MigrationTarget.sol // // Migration target // @dev Implement this interface to make migration target // contract MigrationTarget { function migrateFrom(address _from, uint256 _amount, uint256 _rewards, uint256 _trueBuy, bool _devStatus) public; } // File: contracts/Ownable.sol contract Ownable { address public owner; // Event event OwnershipChanged(address indexed oldOwner, address indexed newOwner); // Modifier modifier onlyOwner { require(msg.sender == owner); _; } function Ownable() public { owner = msg.sender; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipChanged(owner, newOwner); owner = newOwner; } } // File: contracts/ERC20.sol contract ERC20 { uint256 public totalSupply; function balanceOf(address _owner) view public 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) view public returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } // File: contracts/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: contracts/StandardToken.sol /* ERC 20 token */ contract StandardToken is ERC20 { /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal returns (bool success) { // Prevent transfer to 0x0 address. Use burn() instead require(_to != address(0)); // Check if the sender has enough require(balances[_from] >= _value); // Check for overflows require(balances[_to] + _value > balances[_to]); // Save this for an assertion in the future uint256 previousBalances = balances[_from] + balances[_to]; // Subtract from the sender balances[_from] -= _value; // Add the same to the recipient balances[_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(balances[_from] + balances[_to] == previousBalances); return true; } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { return _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 <= allowed[_from][msg.sender]); // Check allowance allowed[_from][msg.sender] -= _value; return _transfer(_from, _to, _value); } function balanceOf(address _owner) view public returns (uint256 balance) { return balances[_owner]; } /** * 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) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) view public returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; } // File: contracts/RoyaltyToken.sol /* Royalty token */ contract RoyaltyToken is StandardToken { using SafeMath for uint256; // restricted addresses mapping(address => bool) public restrictedAddresses; event RestrictedStatusChanged(address indexed _address, bool status); struct Account { uint256 balance; uint256 lastRoyaltyPoint; } mapping(address => Account) public accounts; uint256 public totalRoyalty; uint256 public unclaimedRoyalty; /** * Get Royalty amount for given account * * @param account The address for Royalty account */ function RoyaltysOwing(address account) public view returns (uint256) { uint256 newRoyalty = totalRoyalty.sub(accounts[account].lastRoyaltyPoint); return balances[account].mul(newRoyalty).div(totalSupply); } /** * @dev Update account for Royalty * @param account The address of owner */ function updateAccount(address account) internal { uint256 owing = RoyaltysOwing(account); accounts[account].lastRoyaltyPoint = totalRoyalty; if (owing > 0) { unclaimedRoyalty = unclaimedRoyalty.sub(owing); accounts[account].balance = accounts[account].balance.add(owing); } } function disburse() public payable { require(totalSupply > 0); require(msg.value > 0); uint256 newRoyalty = msg.value; totalRoyalty = totalRoyalty.add(newRoyalty); unclaimedRoyalty = unclaimedRoyalty.add(newRoyalty); } /** * @dev Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { // Require that the sender is not restricted require(restrictedAddresses[msg.sender] == false); updateAccount(_to); updateAccount(msg.sender); return super.transfer(_to, _value); } /** * @dev Transfer tokens from other address. Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool success) { updateAccount(_to); updateAccount(_from); return super.transferFrom(_from, _to, _value); } function withdrawRoyalty() public { updateAccount(msg.sender); // retrieve Royalty amount uint256 RoyaltyAmount = accounts[msg.sender].balance; require(RoyaltyAmount > 0); accounts[msg.sender].balance = 0; // transfer Royalty amount msg.sender.transfer(RoyaltyAmount); } } // File: contracts/Q2.sol contract Q2 is Ownable, RoyaltyToken { using SafeMath for uint256; string public name = "Q2"; string public symbol = "Q2"; uint8 public decimals = 18; bool public whitelist = true; // whitelist addresses mapping(address => bool) public whitelistedAddresses; // token creation cap uint256 public creationCap = 15000000 * (10 ** 18); // 15M uint256 public reservedFund = 10000000 * (10 ** 18); // 10M // stage info struct Stage { uint8 number; uint256 exchangeRate; uint256 startBlock; uint256 endBlock; uint256 cap; } // events event MintTokens(address indexed _to, uint256 _value); event StageStarted(uint8 _stage, uint256 _totalSupply, uint256 _balance); event StageEnded(uint8 _stage, uint256 _totalSupply, uint256 _balance); event WhitelistStatusChanged(address indexed _address, bool status); event WhitelistChanged(bool status); // eth wallet address public ethWallet; mapping (uint8 => Stage) stages; // current state info uint8 public currentStage; function Q2(address _ethWallet) public { ethWallet = _ethWallet; // reserved tokens mintTokens(ethWallet, reservedFund); } function mintTokens(address to, uint256 value) internal { require(value > 0); balances[to] = balances[to].add(value); totalSupply = totalSupply.add(value); require(totalSupply <= creationCap); // broadcast event emit MintTokens(to, value); } function () public payable { buyTokens(); } function buyTokens() public payable { require(whitelist==false || whitelistedAddresses[msg.sender] == true); require(msg.value > 0); Stage memory stage = stages[currentStage]; require(block.number >= stage.startBlock && block.number <= stage.endBlock); uint256 tokens = msg.value * stage.exchangeRate; require(totalSupply.add(tokens) <= stage.cap); mintTokens(msg.sender, tokens); } function startStage( uint256 _exchangeRate, uint256 _cap, uint256 _startBlock, uint256 _endBlock ) public onlyOwner { require(_exchangeRate > 0 && _cap > 0); require(_startBlock > block.number); require(_startBlock < _endBlock); // stop current stage if it's running Stage memory currentObj = stages[currentStage]; if (currentObj.endBlock > 0) { // broadcast stage end event emit StageEnded(currentStage, totalSupply, address(this).balance); } // increment current stage currentStage = currentStage + 1; // create new stage object Stage memory s = Stage({ number: currentStage, startBlock: _startBlock, endBlock: _endBlock, exchangeRate: _exchangeRate, cap: _cap + totalSupply }); stages[currentStage] = s; // broadcast stage started event emit StageStarted(currentStage, totalSupply, address(this).balance); } function withdraw() public onlyOwner { ethWallet.transfer(address(this).balance); } function getCurrentStage() view public returns ( uint8 number, uint256 exchangeRate, uint256 startBlock, uint256 endBlock, uint256 cap ) { Stage memory currentObj = stages[currentStage]; number = currentObj.number; exchangeRate = currentObj.exchangeRate; startBlock = currentObj.startBlock; endBlock = currentObj.endBlock; cap = currentObj.cap; } function changeWhitelistStatus(address _address, bool status) public onlyOwner { whitelistedAddresses[_address] = status; emit WhitelistStatusChanged(_address, status); } function changeRestrictedtStatus(address _address, bool status) public onlyOwner { restrictedAddresses[_address] = status; emit RestrictedStatusChanged(_address, status); } function changeWhitelist(bool status) public onlyOwner { whitelist = status; emit WhitelistChanged(status); } } // File: contracts/Quarters.sol interface TokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract Quarters is Ownable, StandardToken { // Public variables of the token string public name = "Quarters"; string public symbol = "Q"; uint8 public decimals = 0; // no decimals, only integer quarters uint16 public ethRate = 4000; // Quarters/ETH uint256 public tranche = 40000; // Number of Quarters in initial tranche // List of developers // address -> status mapping (address => bool) public developers; uint256 public outstandingQuarters; address public q2; // number of Quarters for next tranche uint8 public trancheNumerator = 2; uint8 public trancheDenominator = 1; // initial multiples, rates (as percentages) for tiers of developers uint32 public mega = 20; uint32 public megaRate = 115; uint32 public large = 100; uint32 public largeRate = 90; uint32 public medium = 2000; uint32 public mediumRate = 75; uint32 public small = 50000; uint32 public smallRate = 50; uint32 public microRate = 25; // rewards related storage mapping (address => uint256) public rewards; // rewards earned, but not yet collected mapping (address => uint256) public trueBuy; // tranche rewards are set based on *actual* purchases of Quarters uint256 public rewardAmount = 40; uint8 public rewardNumerator = 1; uint8 public rewardDenominator = 4; // reserve ETH from Q2 to fund rewards uint256 public reserveETH=0; // ETH rate changed event EthRateChanged(uint16 currentRate, uint16 newRate); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); event QuartersOrdered(address indexed sender, uint256 ethValue, uint256 tokens); event DeveloperStatusChanged(address indexed developer, bool status); event TrancheIncreased(uint256 _tranche, uint256 _etherPool, uint256 _outstandingQuarters); event MegaEarnings(address indexed developer, uint256 value, uint256 _baseRate, uint256 _tranche, uint256 _outstandingQuarters, uint256 _etherPool); event Withdraw(address indexed developer, uint256 value, uint256 _baseRate, uint256 _tranche, uint256 _outstandingQuarters, uint256 _etherPool); event BaseRateChanged(uint256 _baseRate, uint256 _tranche, uint256 _outstandingQuarters, uint256 _etherPool, uint256 _totalSupply); event Reward(address indexed _address, uint256 value, uint256 _outstandingQuarters, uint256 _totalSupply); /** * developer modifier */ modifier onlyActiveDeveloper() { require(developers[msg.sender] == true); _; } /** * Constructor function * * Initializes contract with initial supply tokens to the owner of the contract */ function Quarters( address _q2, uint256 firstTranche ) public { q2 = _q2; tranche = firstTranche; // number of Quarters to be sold before increasing price } function setEthRate (uint16 rate) onlyOwner public { // Ether price is set in Wei require(rate > 0); ethRate = rate; emit EthRateChanged(ethRate, rate); } /** * Adjust reward amount */ function adjustReward (uint256 reward) onlyOwner public { rewardAmount = reward; // may be zero, no need to check value to 0 } function adjustWithdrawRate(uint32 mega2, uint32 megaRate2, uint32 large2, uint32 largeRate2, uint32 medium2, uint32 mediumRate2, uint32 small2, uint32 smallRate2, uint32 microRate2) onlyOwner public { // the values (mega, large, medium, small) are multiples, e.g., 20x, 100x, 10000x // the rates (megaRate, etc.) are percentage points, e.g., 150 is 150% of the remaining etherPool if (mega2 > 0 && megaRate2 > 0) { mega = mega2; megaRate = megaRate2; } if (large2 > 0 && largeRate2 > 0) { large = large2; largeRate = largeRate2; } if (medium2 > 0 && mediumRate2 > 0) { medium = medium2; mediumRate = mediumRate2; } if (small2 > 0 && smallRate2 > 0){ small = small2; smallRate = smallRate2; } if (microRate2 > 0) { microRate = microRate2; } } /** * adjust tranche for next cycle */ function adjustNextTranche (uint8 numerator, uint8 denominator) onlyOwner public { require(numerator > 0 && denominator > 0); trancheNumerator = numerator; trancheDenominator = denominator; } function adjustTranche(uint256 tranche2) onlyOwner public { require(tranche2 > 0); tranche = tranche2; } /** * Adjust rewards for `_address` */ function updatePlayerRewards(address _address) internal { require(_address != address(0)); uint256 _reward = 0; if (rewards[_address] == 0) { _reward = rewardAmount; } else if (rewards[_address] < tranche) { _reward = trueBuy[_address] * rewardNumerator / rewardDenominator; } if (_reward > 0) { // update rewards record rewards[_address] = tranche; balances[_address] += _reward; allowed[_address][msg.sender] += _reward; // set allowance totalSupply += _reward; outstandingQuarters += _reward; uint256 spentETH = (_reward * (10 ** 18)) / ethRate; if (reserveETH >= spentETH) { reserveETH -= spentETH; } else { reserveETH = 0; } // tranche size change _changeTrancheIfNeeded(); emit Approval(_address, msg.sender, _reward); emit Reward(_address, _reward, outstandingQuarters, totalSupply); } } /** * Developer status */ function setDeveloperStatus (address _address, bool status) onlyOwner public { developers[_address] = status; emit DeveloperStatusChanged(_address, status); } /** * 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; } return false; } /** * 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(balances[msg.sender] >= _value); // Check if the sender has enough balances[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply outstandingQuarters -= _value; // Update outstanding quarters emit Burn(msg.sender, _value); // log rate change emit BaseRateChanged(getBaseRate(), tranche, outstandingQuarters, address(this).balance, totalSupply); 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(balances[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowed[_from][msg.sender]); // Check allowance balances[_from] -= _value; // Subtract from the targeted balance allowed[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply outstandingQuarters -= _value; // Update outstanding quarters emit Burn(_from, _value); // log rate change emit BaseRateChanged(getBaseRate(), tranche, outstandingQuarters, address(this).balance, totalSupply); return true; } /** * Buy quarters by sending ethers to contract address (no data required) */ function () payable public { _buy(msg.sender); } function buy() payable public { _buy(msg.sender); } function buyFor(address buyer) payable public { uint256 _value = _buy(buyer); // allow donor (msg.sender) to spend buyer's tokens allowed[buyer][msg.sender] += _value; emit Approval(buyer, msg.sender, _value); } function _changeTrancheIfNeeded() internal { if (totalSupply >= tranche) { // change tranche size for next cycle tranche = (tranche * trancheNumerator) / trancheDenominator; // fire event for tranche change emit TrancheIncreased(tranche, address(this).balance, outstandingQuarters); } } // returns number of quarters buyer got function _buy(address buyer) internal returns (uint256) { require(buyer != address(0)); uint256 nq = (msg.value * ethRate) / (10 ** 18); require(nq != 0); if (nq > tranche) { nq = tranche; } totalSupply += nq; balances[buyer] += nq; trueBuy[buyer] += nq; outstandingQuarters += nq; // change tranche size _changeTrancheIfNeeded(); // event for quarters order (invoice) emit QuartersOrdered(buyer, msg.value, nq); // log rate change emit BaseRateChanged(getBaseRate(), tranche, outstandingQuarters, address(this).balance, totalSupply); // transfer owner's cut Q2(q2).disburse.value(msg.value * 15 / 100)(); // return nq return nq; } /** * Transfer allowance from other address's allowance * * 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 transferAllowance(address _from, address _to, uint256 _value) public returns (bool success) { updatePlayerRewards(_from); require(_value <= allowed[_from][msg.sender]); // Check allowance allowed[_from][msg.sender] -= _value; if (_transfer(_from, _to, _value)) { // allow msg.sender to spend _to's tokens allowed[_to][msg.sender] += _value; emit Approval(_to, msg.sender, _value); return true; } return false; } function withdraw(uint256 value) onlyActiveDeveloper public { require(balances[msg.sender] >= value); uint256 baseRate = getBaseRate(); require(baseRate > 0); // check if base rate > 0 uint256 earnings = value * baseRate; uint256 rate = getRate(value); // get rate from value and tranche uint256 earningsWithBonus = (rate * earnings) / 100; if (earningsWithBonus > address(this).balance) { earnings = address(this).balance; } else { earnings = earningsWithBonus; } balances[msg.sender] -= value; outstandingQuarters -= value; // update the outstanding Quarters uint256 etherPool = address(this).balance - earnings; if (rate == megaRate) { emit MegaEarnings(msg.sender, earnings, baseRate, tranche, outstandingQuarters, etherPool); // with current base rate } // event for withdraw emit Withdraw(msg.sender, earnings, baseRate, tranche, outstandingQuarters, etherPool); // with current base rate // log rate change emit BaseRateChanged(getBaseRate(), tranche, outstandingQuarters, address(this).balance, totalSupply); // earning for developers msg.sender.transfer(earnings); } function disburse() public payable { reserveETH += msg.value; } function getBaseRate () view public returns (uint256) { if (outstandingQuarters > 0) { return (address(this).balance - reserveETH) / outstandingQuarters; } return (address(this).balance - reserveETH); } function getRate (uint256 value) view public returns (uint32) { if (value * mega > tranche) { // size & rate for mega developer return megaRate; } else if (value * large > tranche) { // size & rate for large developer return largeRate; } else if (value * medium > tranche) { // size and rate for medium developer return mediumRate; } else if (value * small > tranche){ // size and rate for small developer return smallRate; } return microRate; // rate for micro developer } // // Migrations // // Target contract address public migrationTarget; bool public migrating = false; // Migrate event event Migrate(address indexed _from, uint256 _value); // // Migrate tokens to the new token contract. // function migrate() public { require(migrationTarget != address(0)); uint256 _amount = balances[msg.sender]; require(_amount > 0); balances[msg.sender] = 0; totalSupply = totalSupply - _amount; outstandingQuarters = outstandingQuarters - _amount; rewards[msg.sender] = 0; trueBuy[msg.sender] = 0; developers[msg.sender] = false; emit Migrate(msg.sender, _amount); MigrationTarget(migrationTarget).migrateFrom(msg.sender, _amount, rewards[msg.sender], trueBuy[msg.sender], developers[msg.sender]); } // // Set address of migration target contract // @param _target The address of the MigrationTarget contract // function setMigrationTarget(address _target) onlyOwner public { migrationTarget = _target; } }
allow donor (msg.sender) to spend buyer's tokens
function buyFor(address buyer) payable public { uint256 _value = _buy(buyer); allowed[buyer][msg.sender] += _value; emit Approval(buyer, msg.sender, _value); }
5,510,628
./full_match/77/0x804A40d12FdeD71D41cD69a0054d371a80Cc84da/sources/deploy/contracts/synthereum-pool/v5/LiquidityPoolLib.sol
Update the fee percentage self Data type the library is attached to _feePercentage The new fee percentage/
function setFeePercentage( ISynthereumLiquidityPoolStorage.Storage storage self, FixedPoint.Unsigned calldata _feePercentage ) external { require( _feePercentage.rawValue < 10**(18), 'Fee Percentage must be less than 100%' ); self.fee.feeData.feePercentage = _feePercentage; emit SetFeePercentage(_feePercentage.rawValue); }
5,046,520
pragma solidity ^0.5.0; // produced by the Solididy File Flattener (c) David Appleton 2018 // contact : [email protected] // released under Apache 2.0 licence library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint len; uint memPtr; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { uint memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @param item RLP encoded bytes */ function rlpLen(RLPItem memory item) internal pure returns (uint) { return item.len; } /* * @param item RLP encoded bytes */ function payloadLen(RLPItem memory item) internal pure returns (uint) { return item.len - _payloadOffset(item.memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory result) { require(isList(item)); uint items = numItems(item); result = new RLPItem[](items); uint memPtr = item.memPtr + _payloadOffset(item.memPtr); uint dataLen; for (uint i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { if (item.len == 0) return false; uint8 byte0; uint memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); if (result.length == 0) return result; uint ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } // any non-zero byte is considered true function toBoolean(RLPItem memory item) internal pure returns (bool) { require(item.len == 1); uint result; uint memPtr = item.memPtr; assembly { result := byte(0, mload(memPtr)) } return result == 0 ? false : true; } function toAddress(RLPItem memory item) internal pure returns (address) { // 1 byte for the length prefix require(item.len == 21); return address(toUint(item)); } function toUint(RLPItem memory item) internal pure returns (uint) { require(item.len > 0 && item.len <= 33); uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; uint result; uint memPtr = item.memPtr + offset; assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint) { // one byte prefix require(item.len == 33); uint result; uint memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { require(item.len > 0); uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; // data length bytes memory result = new bytes(len); uint destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint) { if (item.len == 0) return 0; uint count = 0; uint currPtr = item.memPtr + _payloadOffset(item.memPtr); uint endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item count++; } return count; } // @return entire rlp item byte length function _itemLength(uint memPtr) private pure returns (uint len) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 1; else if (byte0 < STRING_LONG_START) return byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len len := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { return byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length len := add(dataLen, add(byteLen, 1)) } } } // @return number of bytes until the data function _payloadOffset(uint memPtr) private pure returns (uint) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy(uint src, uint dest, uint len) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } } library BytesUtil { uint8 constant WORD_SIZE = 32; // @param _bytes raw bytes that needs to be slices // @param start start of the slice relative to `_bytes` // @param len length of the sliced byte array function slice(bytes memory _bytes, uint start, uint len) internal pure returns (bytes memory) { require(_bytes.length - start >= len); if (_bytes.length == len) return _bytes; bytes memory result; uint src; uint dest; assembly { // memory & free memory pointer result := mload(0x40) mstore(result, len) // store the size in the prefix mstore(0x40, add(result, and(add(add(0x20, len), 0x1f), not(0x1f)))) // padding // pointers src := add(start, add(0x20, _bytes)) dest := add(0x20, result) } // copy as many word sizes as possible for(; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // copy remaining bytes uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } return result; } } library SafeMath { /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } } library ECDSA { /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param signature bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // prefix the hash with an ethereum signed message hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(hash, v, r, s); } } } library TMSimpleMerkleTree { using BytesUtil for bytes; // @param leaf a leaf of the tree // @param index position of this leaf in the tree that is zero indexed // @param rootHash block header of the merkle tree // @param proof sequence of 32-byte hashes from the leaf up to, but excluding, the root // @paramt total total # of leafs in the tree function checkMembership(bytes32 leaf, uint256 index, bytes32 rootHash, bytes memory proof, uint256 total) internal pure returns (bool) { // variable size Merkle tree, but proof must consist of 32-byte hashes require(proof.length % 32 == 0); // incorrect proof length bytes32 computedHash = computeHashFromAunts(index, total, leaf, proof); return computedHash == rootHash; } // helper function as described in the tendermint docs function computeHashFromAunts(uint256 index, uint256 total, bytes32 leaf, bytes memory innerHashes) private pure returns (bytes32) { require(index < total); // index must be within bound of the # of leave require(total > 0); // must have one leaf node if (total == 1) { require(innerHashes.length == 0); // 1 txn has no proof return leaf; } require(innerHashes.length != 0); // >1 txns should have a proof uint256 numLeft = (total + 1) / 2; bytes32 proofElement; // prepend 0x20 byte literal to hashes // tendermint prefixes intermediate hashes with 0x20 bytes literals // before hashing them. bytes memory b = new bytes(1); assembly { let memPtr := add(b, 0x20) mstore8(memPtr, 0x20) } uint innerHashesMemOffset = innerHashes.length - 32; if (index < numLeft) { bytes32 leftHash = computeHashFromAunts(index, numLeft, leaf, innerHashes.slice(0, innerHashes.length - 32)); assembly { // get the last 32-byte hash from innerHashes array proofElement := mload(add(add(innerHashes, 0x20), innerHashesMemOffset)) } return sha256(abi.encodePacked(b, leftHash, b, proofElement)); } else { bytes32 rightHash = computeHashFromAunts(index-numLeft, total-numLeft, leaf, innerHashes.slice(0, innerHashes.length - 32)); assembly { // get the last 32-byte hash from innerHashes array proofElement := mload(add(add(innerHashes, 0x20), innerHashesMemOffset)) } return sha256(abi.encodePacked(b, proofElement, b, rightHash)); } } } library MinPriorityQueue { using SafeMath for uint256; function insert(uint256[] storage heapList, uint256 k) internal { heapList.push(k); if (heapList.length > 1) percUp(heapList, heapList.length.sub(1)); } function delMin(uint256[] storage heapList) internal returns (uint256) { require(heapList.length > 0); uint256 min = heapList[0]; // move the last element to the front heapList[0] = heapList[heapList.length.sub(1)]; delete heapList[heapList.length.sub(1)]; heapList.length = heapList.length.sub(1); if (heapList.length > 1) { percDown(heapList, 0); } return min; } function minChild(uint256[] storage heapList, uint256 i) private view returns (uint256) { uint lChild = i.mul(2).add(1); uint rChild = i.mul(2).add(2); if (rChild > heapList.length.sub(1) || heapList[lChild] < heapList[rChild]) return lChild; else return rChild; } function percUp(uint256[] storage heapList, uint256 i) private { uint256 position = i; uint256 value = heapList[i]; // continue to percolate up while smaller than the parent while (i != 0 && value < heapList[i.sub(1).div(2)]) { heapList[i] = heapList[i.sub(1).div(2)]; i = i.sub(1).div(2); } // place the value in the correct parent if (position != i) heapList[i] = value; } function percDown(uint256[] storage heapList, uint256 i) private { uint position = i; uint value = heapList[i]; // continue to percolate down while larger than the child uint child = minChild(heapList, i); while(child < heapList.length && value > heapList[child]) { heapList[i] = heapList[child]; i = child; child = minChild(heapList, i); } // place value in the correct child if (position != i) heapList[i] = value; } } contract PlasmaMVP { using MinPriorityQueue for uint256[]; using BytesUtil for bytes; using RLPReader for bytes; using RLPReader for RLPReader.RLPItem; using SafeMath for uint256; using TMSimpleMerkleTree for bytes32; using ECDSA for bytes32; /* * Events */ event ChangedOperator(address oldOperator, address newOperator); event AddedToBalances(address owner, uint256 amount); event BlockSubmitted(bytes32 header, uint256 blockNumber, uint256 numTxns, uint256 feeAmount); event Deposit(address depositor, uint256 amount, uint256 depositNonce, uint256 ethBlockNum); event StartedTransactionExit(uint256[3] position, address owner, uint256 amount, bytes confirmSignatures, uint256 committedFee); event StartedDepositExit(uint256 nonce, address owner, uint256 amount, uint256 committedFee); event ChallengedExit(uint256[4] position, address owner, uint256 amount); event FinalizedExit(uint256[4] position, address owner, uint256 amount); /* * Storage */ address public operator; uint256 public lastCommittedBlock; uint256 public depositNonce; mapping(uint256 => plasmaBlock) public plasmaChain; mapping(uint256 => depositStruct) public deposits; struct plasmaBlock{ bytes32 header; uint256 numTxns; uint256 feeAmount; uint256 createdAt; } struct depositStruct { address owner; uint256 amount; uint256 createdAt; uint256 ethBlockNum; } // exits uint256 public minExitBond; uint256[] public txExitQueue; uint256[] public depositExitQueue; mapping(uint256 => exit) public txExits; mapping(uint256 => exit) public depositExits; enum ExitState { NonExistent, Pending, Challenged, Finalized } struct exit { uint256 amount; uint256 committedFee; uint256 createdAt; address owner; uint256[4] position; // (blkNum, txIndex, outputIndex, depositNonce) ExitState state; // default value is `NonExistent` } // funds mapping(address => uint256) public balances; uint256 public totalWithdrawBalance; // constants uint256 constant txIndexFactor = 10; uint256 constant blockIndexFactor = 1000000; uint256 constant lastBlockNum = 2**109; uint256 constant feeIndex = 2**16-1; /** Modifiers **/ modifier isBonded() { require(msg.value >= minExitBond); if (msg.value > minExitBond) { uint256 excess = msg.value.sub(minExitBond); balances[msg.sender] = balances[msg.sender].add(excess); totalWithdrawBalance = totalWithdrawBalance.add(excess); } _; } modifier onlyOperator() { require(msg.sender == operator); _; } function changeOperator(address newOperator) public onlyOperator { require(newOperator != address(0)); emit ChangedOperator(operator, newOperator); operator = newOperator; } constructor() public { operator = msg.sender; lastCommittedBlock = 0; depositNonce = 1; minExitBond = 200000; } // @param blocks 32 byte merkle headers appended in ascending order // @param txnsPerBlock number of transactions per block // @param feesPerBlock amount of fees the validator has collected per block // @param blockNum the block number of the first header // @notice each block is capped at 2**16-1 transactions function submitBlock(bytes32[] memory headers, uint256[] memory txnsPerBlock, uint256[] memory feePerBlock, uint256 blockNum) public onlyOperator { require(blockNum == lastCommittedBlock.add(1)); require(headers.length == txnsPerBlock.length && txnsPerBlock.length == feePerBlock.length); for (uint i = 0; i < headers.length && lastCommittedBlock <= lastBlockNum; i++) { require(headers[i] != bytes32(0) && txnsPerBlock[i] > 0 && txnsPerBlock[i] < feeIndex); lastCommittedBlock = lastCommittedBlock.add(1); plasmaChain[lastCommittedBlock] = plasmaBlock({ header: headers[i], numTxns: txnsPerBlock[i], feeAmount: feePerBlock[i], createdAt: block.timestamp }); emit BlockSubmitted(headers[i], lastCommittedBlock, txnsPerBlock[i], feePerBlock[i]); } } // @param owner owner of this deposit function deposit(address owner) public payable { deposits[depositNonce] = depositStruct(owner, msg.value, block.timestamp, block.number); emit Deposit(owner, msg.value, depositNonce, block.number); depositNonce = depositNonce.add(uint256(1)); } // @param depositNonce the nonce of the specific deposit function startDepositExit(uint256 nonce, uint256 committedFee) public payable isBonded { require(deposits[nonce].owner == msg.sender); require(deposits[nonce].amount > committedFee); require(depositExits[nonce].state == ExitState.NonExistent); address owner = deposits[nonce].owner; uint256 amount = deposits[nonce].amount; uint256 priority = block.timestamp << 128 | nonce; depositExitQueue.insert(priority); depositExits[nonce] = exit({ owner: owner, amount: amount, committedFee: committedFee, createdAt: block.timestamp, position: [0,0,0,nonce], state: ExitState.Pending }); emit StartedDepositExit(nonce, owner, amount, committedFee); } // Transaction encoding: // [[Blknum1, TxIndex1, Oindex1, DepositNonce1, Input1ConfirmSig, // Blknum2, TxIndex2, Oindex2, DepositNonce2, Input2ConfirmSig, // NewOwner, Denom1, NewOwner, Denom2, Fee], // [Signature1, Signature2]] // // All integers are padded to 32 bytes. Input's confirm signatures are 130 bytes for each input. // Zero bytes if unapplicable (deposit/fee inputs) Signatures are 65 bytes in length // // @param txBytes rlp encoded transaction // @notice this function will revert if the txBytes are malformed function decodeTransaction(bytes memory txBytes) internal pure returns (RLPReader.RLPItem[] memory txList, RLPReader.RLPItem[] memory sigList, bytes32 txHash) { // entire byte length of the rlp encoded transaction. require(txBytes.length == 811); RLPReader.RLPItem[] memory spendMsg = txBytes.toRlpItem().toList(); require(spendMsg.length == 2); txList = spendMsg[0].toList(); require(txList.length == 15); sigList = spendMsg[1].toList(); require(sigList.length == 2); // bytes the signatures are over txHash = keccak256(spendMsg[0].toRlpBytes()); } // @param txPos location of the transaction [blkNum, txIndex, outputIndex] // @param txBytes transaction bytes containing the exiting output // @param proof merkle proof of inclusion in the plasma chain // @param confSig0 confirm signatures sent by the owners of the first input acknowledging the spend. // @param confSig1 confirm signatures sent by the owners of the second input acknowledging the spend (if applicable). // @notice `confirmSignatures` and `ConfirmSig0`/`ConfirmSig1` are unrelated to each other. // @notice `confirmSignatures` is either 65 or 130 bytes in length dependent on if a second input is present // @notice `confirmSignatures` should be empty if the output trying to be exited is a fee output function startTransactionExit(uint256[3] memory txPos, bytes memory txBytes, bytes memory proof, bytes memory confirmSignatures, uint256 committedFee) public payable isBonded { require(txPos[1] < feeIndex); uint256 position = calcPosition(txPos); require(txExits[position].state == ExitState.NonExistent); uint256 amount = startTransactionExitHelper(txPos, txBytes, proof, confirmSignatures); require(amount > committedFee); // calculate the priority of the transaction taking into account the withdrawal delay attack // withdrawal delay attack: https://github.com/FourthState/plasma-mvp-rootchain/issues/42 uint256 createdAt = plasmaChain[txPos[0]].createdAt; txExitQueue.insert(SafeMath.max(createdAt.add(1 weeks), block.timestamp) << 128 | position); // write exit to storage txExits[position] = exit({ owner: msg.sender, amount: amount, committedFee: committedFee, createdAt: block.timestamp, position: [txPos[0], txPos[1], txPos[2], 0], state: ExitState.Pending }); emit StartedTransactionExit(txPos, msg.sender, amount, confirmSignatures, committedFee); } // @returns amount of the exiting transaction // @notice the purpose of this helper was to work around the capped evm stack frame function startTransactionExitHelper(uint256[3] memory txPos, bytes memory txBytes, bytes memory proof, bytes memory confirmSignatures) private view returns (uint256) { bytes32 txHash; RLPReader.RLPItem[] memory txList; RLPReader.RLPItem[] memory sigList; (txList, sigList, txHash) = decodeTransaction(txBytes); uint base = txPos[2].mul(2); require(msg.sender == txList[base.add(10)].toAddress()); plasmaBlock memory blk = plasmaChain[txPos[0]]; // Validation bytes32 merkleHash = sha256(txBytes); require(merkleHash.checkMembership(txPos[1], blk.header, proof, blk.numTxns)); address recoveredAddress; bytes32 confirmationHash = sha256(abi.encodePacked(merkleHash, blk.header)); bytes memory sig = sigList[0].toBytes(); require(sig.length == 65 && confirmSignatures.length % 65 == 0 && confirmSignatures.length > 0 && confirmSignatures.length <= 130); recoveredAddress = confirmationHash.recover(confirmSignatures.slice(0, 65)); require(recoveredAddress != address(0) && recoveredAddress == txHash.recover(sig)); if (txList[5].toUintStrict() > 0 || txList[8].toUintStrict() > 0) { // existence of a second input sig = sigList[1].toBytes(); require(sig.length == 65 && confirmSignatures.length == 130); recoveredAddress = confirmationHash.recover(confirmSignatures.slice(65, 65)); require(recoveredAddress != address(0) && recoveredAddress == txHash.recover(sig)); } // check that the UTXO's two direct inputs have not been previously exited require(validateTransactionExitInputs(txList)); return txList[base.add(11)].toUintStrict(); } // For any attempted exit of an UTXO, validate that the UTXO's two inputs have not // been previously exited or are currently pending an exit. function validateTransactionExitInputs(RLPReader.RLPItem[] memory txList) private view returns (bool) { for (uint256 i = 0; i < 2; i++) { ExitState state; uint256 base = uint256(5).mul(i); uint depositNonce_ = txList[base.add(3)].toUintStrict(); if (depositNonce_ == 0) { uint256 blkNum = txList[base].toUintStrict(); uint256 txIndex = txList[base.add(1)].toUintStrict(); uint256 outputIndex = txList[base.add(2)].toUintStrict(); uint256 position = calcPosition([blkNum, txIndex, outputIndex]); state = txExits[position].state; } else state = depositExits[depositNonce_].state; if (state != ExitState.NonExistent && state != ExitState.Challenged) return false; } return true; } // Validator of any block can call this function to exit the fees collected // for that particular block. The fee exit is added to exit queue with the lowest priority for that block. // In case of the fee UTXO already spent, anyone can challenge the fee exit by providing // the spend of the fee UTXO. // @param blockNumber the block for which the validator wants to exit fees function startFeeExit(uint256 blockNumber, uint256 committedFee) public payable onlyOperator isBonded { plasmaBlock memory blk = plasmaChain[blockNumber]; require(blk.header != bytes32(0)); uint256 feeAmount = blk.feeAmount; // nonzero fee and prevent and greater than the committed fee if spent. // default value for a fee amount is zero. Will revert if a block for // this number has not been committed require(feeAmount > committedFee); // a fee UTXO has explicitly defined position [blockNumber, 2**16 - 1, 0] uint256 position = calcPosition([blockNumber, feeIndex, 0]); require(txExits[position].state == ExitState.NonExistent); txExitQueue.insert(SafeMath.max(blk.createdAt.add(1 weeks), block.timestamp) << 128 | position); txExits[position] = exit({ owner: msg.sender, amount: feeAmount, committedFee: committedFee, createdAt: block.timestamp, position: [blockNumber, feeIndex, 0, 0], state: ExitState.Pending }); // pass in empty bytes for confirmSignatures for StartedTransactionExit event. emit StartedTransactionExit([blockNumber, feeIndex, 0], operator, feeAmount, "", 0); } // @param exitingTxPos position of the invalid exiting transaction [blkNum, txIndex, outputIndex] // @param challengingTxPos position of the challenging transaction [blkNum, txIndex] // @param txBytes raw transaction bytes of the challenging transaction // @param proof proof of inclusion for this merkle hash // @param confirmSignature signature used to invalidate the invalid exit. Signature is over (merkleHash, block header) // @notice The operator can challenge an exit which commits an invalid fee by simply passing in empty bytes for confirm signature as they are not needed. // The committed fee is checked againt the challenging tx bytes function challengeExit(uint256[4] memory exitingTxPos, uint256[2] memory challengingTxPos, bytes memory txBytes, bytes memory proof, bytes memory confirmSignature) public { bytes32 txHash = keccak256(abi.encodePacked(exitingTxPos, challengingTxPos)); //inject HASH WITH MUL VAR LEN ARG RLPReader.RLPItem[] memory txList; RLPReader.RLPItem[] memory sigList; (txList, sigList, txHash) = decodeTransaction(txBytes); // `challengingTxPos` is sequentially after `exitingTxPos` require(exitingTxPos[0] < challengingTxPos[0] || (exitingTxPos[0] == challengingTxPos[0] && exitingTxPos[1] < challengingTxPos[1])); // must be a direct spend bool firstInput = exitingTxPos[0] == txList[0].toUintStrict() && exitingTxPos[1] == txList[1].toUintStrict() && exitingTxPos[2] == txList[2].toUintStrict() && exitingTxPos[3] == txList[3].toUintStrict(); require(firstInput || exitingTxPos[0] == txList[5].toUintStrict() && exitingTxPos[1] == txList[6].toUintStrict() && exitingTxPos[2] == txList[7].toUintStrict() && exitingTxPos[3] == txList[8].toUintStrict()); // transaction to be challenged should have a pending exit exit storage exit_ = exitingTxPos[3] == 0 ? txExits[calcPosition([exitingTxPos[0], exitingTxPos[1], exitingTxPos[2]])] : depositExits[exitingTxPos[3]]; require(exit_.state == ExitState.Pending); plasmaBlock memory blk = plasmaChain[challengingTxPos[0]]; bytes32 merkleHash = keccak256(abi.encodePacked(exitingTxPos, challengingTxPos)); //inject HASH WITH MUL VAR LEN ARG require(blk.header != bytes32(0) && merkleHash.checkMembership(challengingTxPos[1], blk.header, proof, blk.numTxns)); address recoveredAddress; // we check for confirm signatures if: // The exiting tx is a first input and commits the correct fee // OR // The exiting tx is the second input in the challenging transaction // // If this challenge was a fee mismatch, then we check the first transaction signature // to prevent the operator from forging invalid inclusions // // For a fee mismatch, the state becomes `NonExistent` so that the exit can be reopened. // Otherwise, `Challenged` so that the exit can never be opened. if (firstInput && exit_.committedFee != txList[14].toUintStrict()) { bytes memory sig = sigList[0].toBytes(); recoveredAddress = txHash.recover(sig); require(sig.length == 65 && recoveredAddress != address(0) && exit_.owner == recoveredAddress); exit_.state = ExitState.NonExistent; } else { bytes32 confirmationHash = keccak256(abi.encodePacked(exitingTxPos, challengingTxPos)); //inject HASH WITH MUL VAR LEN ARG recoveredAddress = confirmationHash.recover(confirmSignature); require(confirmSignature.length == 65 && recoveredAddress != address(0) && exit_.owner == recoveredAddress); exit_.state = ExitState.Challenged; } // exit successfully challenged. Award the sender with the bond balances[msg.sender] = balances[msg.sender].add(minExitBond); totalWithdrawBalance = totalWithdrawBalance.add(minExitBond); emit AddedToBalances(msg.sender, minExitBond); emit ChallengedExit(exit_.position, exit_.owner, exit_.amount - exit_.committedFee); } function finalizeDepositExits() public { finalize(depositExitQueue, true); } function finalizeTransactionExits() public { finalize(txExitQueue, false); } // Finalizes exits by iterating through either the depositExitQueue or txExitQueue. // Users can determine the number of exits they're willing to process by varying // the amount of gas allow finalize*Exits() to process. // Each transaction takes < 80000 gas to process. function finalize(uint256[] storage queue, bool isDeposits) private { if (queue.length == 0) return; // retrieve the lowest priority and the appropriate exit struct uint256 priority = queue[0]; exit memory currentExit; uint256 position; // retrieve the right 128 bits from the priority to obtain the position assembly { position := and(priority, div(not(0x0), exp(256, 16))) } currentExit = isDeposits ? depositExits[position] : txExits[position]; /* * Conditions: * 1. Exits exist * 2. Exits must be a week old * 3. Funds must exist for the exit to withdraw */ uint256 amountToAdd; uint256 challengePeriod = isDeposits ? 5 days : 1 weeks; while (block.timestamp.sub(currentExit.createdAt) > challengePeriod && plasmaChainBalance() > 0 && gasleft() > 80000) { // skip currentExit if it is not in 'started/pending' state. if (currentExit.state != ExitState.Pending) { queue.delMin(); } else { // reimburse the bond but remove fee allocated for the operator amountToAdd = currentExit.amount.add(minExitBond).sub(currentExit.committedFee); balances[currentExit.owner] = balances[currentExit.owner].add(amountToAdd); totalWithdrawBalance = totalWithdrawBalance.add(amountToAdd); if (isDeposits) depositExits[position].state = ExitState.Finalized; else txExits[position].state = ExitState.Finalized; emit FinalizedExit(currentExit.position, currentExit.owner, amountToAdd); emit AddedToBalances(currentExit.owner, amountToAdd); // move onto the next oldest exit queue.delMin(); } if (queue.length == 0) { return; } // move onto the next oldest exit priority = queue[0]; // retrieve the right 128 bits from the priority to obtain the position assembly { position := and(priority, div(not(0x0), exp(256, 16))) } currentExit = isDeposits ? depositExits[position] : txExits[position]; } } // @notice will revert if the output index is out of bounds function calcPosition(uint256[3] memory txPos) private view returns (uint256) { require(validatePostion([txPos[0], txPos[1], txPos[2], 0])); uint256 position = txPos[0].mul(blockIndexFactor).add(txPos[1].mul(txIndexFactor)).add(txPos[2]); require(position <= 2**128-1); // check for an overflow return position; } function validatePostion(uint256[4] memory position) private view returns (bool) { uint256 blkNum = position[0]; uint256 txIndex = position[1]; uint256 oIndex = position[2]; uint256 depNonce = position[3]; if (blkNum > 0) { // utxo input // uncommitted block if (blkNum > lastCommittedBlock) return false; // txIndex out of bounds for the block if (txIndex >= plasmaChain[blkNum].numTxns && txIndex != feeIndex) return false; // fee input must have a zero output index if (txIndex == feeIndex && oIndex > 0) return false; // deposit nonce must be zero if (depNonce > 0) return false; // only two outputs if (oIndex > 1) return false; } else { // deposit or fee input // deposit input must be zero'd output position // `blkNum` is not checked as it will fail above if (depNonce > 0 && (txIndex > 0 || oIndex > 0)) return false; } return true; } function withdraw() public returns (uint256) { if (balances[msg.sender] == 0) { return 0; } uint256 transferAmount = balances[msg.sender]; delete balances[msg.sender]; totalWithdrawBalance = totalWithdrawBalance.sub(transferAmount); // will revert the above deletion if it fails msg.sender.transfer(transferAmount); return transferAmount; } /* * Getters */ function plasmaChainBalance() public view returns (uint) { // takes into accounts the failed withdrawals return address(this).balance - totalWithdrawBalance; } function balanceOf(address _address) public view returns (uint256) { return balances[_address]; } function txQueueLength() public view returns (uint) { return txExitQueue.length; } function depositQueueLength() public view returns (uint) { return depositExitQueue.length; } }
returns raw rlp encoding in bytes
function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); if (result.length == 0) return result; uint ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; }
15,852,655
/** *Submitted for verification at Etherscan.io on 2021-04-19 */ // Sources flattened with hardhat v2.0.3 https://hardhat.org // File deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.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 SafeMathUpgradeable { /** * @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 deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol pragma solidity ^0.6.2; /** * @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 in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.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 SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File deps/@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.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 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]; } // 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 deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // 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; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // File deps/@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.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 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; } // File deps/@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol pragma solidity ^0.6.0; /** * @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; } // File deps/@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol pragma solidity ^0.6.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. */ contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // File deps/@openzeppelin/contracts-upgradeable/cryptography/MerkleProofUpgradeable.sol pragma solidity ^0.6.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProofUpgradeable { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // File interfaces/badger/ICumulativeMultiTokenMerkleDistributor.sol pragma solidity >=0.5.0; /* Cumulative Merkle distributor */ interface ICumulativeMultiTokenMerkleDistributor { /// @notice Emit when insufficient funds to handle incoming root totals event InsufficientFundsForRoot(bytes32 indexed root); event RootProposed( uint256 indexed cycle, bytes32 indexed root, bytes32 indexed contentHash, uint256 startBlock, uint256 endBlock, uint256 timestamp, uint256 blockNumber ); event RootUpdated( uint256 indexed cycle, bytes32 indexed root, bytes32 indexed contentHash, uint256 startBlock, uint256 endBlock, uint256 timestamp, uint256 blockNumber ); event Claimed(address indexed user, address indexed token, uint256 amount, uint256 indexed cycle, uint256 timestamp, uint256 blockNumber); } // File interfaces/digg/IDigg.sol pragma solidity >=0.5.0 <0.8.0; interface IDigg { // Used for authentication function monetaryPolicy() external view returns (address); function rebaseStartTime() external view returns (uint256); /** * @param monetaryPolicy_ The address of the monetary policy contract to use for authentication. */ function setMonetaryPolicy(address monetaryPolicy_) external; /** * @dev Notifies Fragments contract about a new rebase cycle. * @param supplyDelta The number of new fragment tokens to add into circulation via expansion. * @return The total number of fragments after the supply adjustment. */ function rebase(uint256 epoch, int256 supplyDelta) external returns (uint256); /** * @return The total number of fragments. */ function totalSupply() external view returns (uint256); /** * @return The total number of underlying shares. */ function totalShares() external view returns (uint256); /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) external view returns (uint256); /** * @param who The address to query. * @return The underlying shares of the specified address. */ function sharesOf(address who) external view returns (uint256); function _sharesPerFragment() external view returns (uint256); function _initialSharesPerFragment() external view returns (uint256); /** * @param fragments Fragment value to convert. * @return The underlying share value of the specified fragment amount. */ function fragmentsToShares(uint256 fragments) external view returns (uint256); /** * @param shares Share value to convert. * @return The current fragment value of the specified underlying share amount. */ function sharesToFragments(uint256 shares) external view returns (uint256); function scaledSharesToShares(uint256 fragments) external view returns (uint256); function sharesToScaledShares(uint256 shares) external view returns (uint256); /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) external returns (bool); /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) external view returns (uint256); /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom( address from, address to, uint256 value ) external returns (bool); /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) external returns (bool); /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) external returns (bool); /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); } // File contracts/badger-geyser/BadgerTreeV2.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract BadgerTreeV2 is Initializable, AccessControlUpgradeable, ICumulativeMultiTokenMerkleDistributor, PausableUpgradeable { using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; struct MerkleData { bytes32 root; bytes32 contentHash; uint256 timestamp; uint256 publishBlock; uint256 startBlock; uint256 endBlock; } bytes32 public constant ROOT_PROPOSER_ROLE = keccak256("ROOT_PROPOSER_ROLE"); bytes32 public constant ROOT_VALIDATOR_ROLE = keccak256("ROOT_VALIDATOR_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant UNPAUSER_ROLE = keccak256("UNPAUSER_ROLE"); address private constant DIGG_ADDRESS = 0x798D1bE841a82a273720CE31c822C61a67a601C3; uint256 public currentCycle; bytes32 public merkleRoot; bytes32 public merkleContentHash; uint256 public lastPublishTimestamp; uint256 public lastPublishBlockNumber; uint256 public pendingCycle; bytes32 public pendingMerkleRoot; bytes32 public pendingMerkleContentHash; uint256 public lastProposeTimestamp; uint256 public lastProposeBlockNumber; mapping(address => mapping(address => uint256)) public claimed; mapping(address => uint256) public totalClaimed; uint256 public lastPublishStartBlock; uint256 public lastPublishEndBlock; uint256 public lastProposeStartBlock; uint256 public lastProposeEndBlock; mapping(uint256 => bytes32) merkleRoots; // Mapping of historical merkle roots. Other information about each cycle such as content hash and start/end blocks are not used on-chain and can be found in historical events function initialize( address admin, address initialProposer, address initialValidator ) public initializer { __AccessControl_init(); __Pausable_init_unchained(); _setupRole(DEFAULT_ADMIN_ROLE, admin); // The admin can edit all role permissions _setupRole(ROOT_PROPOSER_ROLE, initialProposer); // The admin can edit all role permissions _setupRole(ROOT_VALIDATOR_ROLE, initialValidator); // The admin can edit all role permissions } /// ===== Modifiers ===== /// @notice Admins can approve new root updaters or admins function _onlyAdmin() internal view { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "onlyAdmin"); } /// @notice Root updaters can update the root function _onlyRootProposer() internal view { require(hasRole(ROOT_PROPOSER_ROLE, msg.sender), "onlyRootProposer"); } function _onlyRootValidator() internal view { require(hasRole(ROOT_VALIDATOR_ROLE, msg.sender), "onlyRootValidator"); } function _onlyPauser() internal view { require(hasRole(PAUSER_ROLE, msg.sender), "onlyPauser"); } function _onlyUnpauser() internal view { require(hasRole(UNPAUSER_ROLE, msg.sender), "onlyUnpauser"); } function getCurrentMerkleData() external view returns (MerkleData memory) { return MerkleData(merkleRoot, merkleContentHash, lastPublishTimestamp, lastPublishBlockNumber, lastPublishStartBlock, lastPublishEndBlock); } function getPendingMerkleData() external view returns (MerkleData memory) { return MerkleData( pendingMerkleRoot, pendingMerkleContentHash, lastProposeTimestamp, lastProposeBlockNumber, lastProposeStartBlock, lastProposeEndBlock ); } function getMerkleRootFor(uint256 cycle) public view returns (bytes32) { return merkleRoots[cycle]; } function hasPendingRoot() external view returns (bool) { return pendingCycle == currentCycle.add(1); } /// @dev Return true if account has outstanding claims in any token from the given input data function isClaimAvailableFor( address user, address[] memory tokens, uint256[] memory cumulativeAmounts ) public view returns (bool) { for (uint256 i = 0; i < tokens.length; i++) { uint256 userClaimable = cumulativeAmounts[i].sub(claimed[user][tokens[i]]); if (userClaimable > 0) { return true; } } return false; } /// @dev Get the number of tokens claimable for an account, given a list of tokens and latest cumulativeAmounts data function getClaimableFor( address user, address[] memory tokens, uint256[] memory cumulativeAmounts ) public view returns (address[] memory, uint256[] memory) { uint256[] memory userClaimable = new uint256[](tokens.length); for (uint256 i = 0; i < tokens.length; i++) { userClaimable[i] = cumulativeAmounts[i].sub(_getClaimed(user, tokens[i])); } return (tokens, userClaimable); } /// @dev Get the cumulative number of tokens claimed for an account, given a list of tokens function getClaimedFor(address user, address[] memory tokens) public view returns (address[] memory, uint256[] memory) { uint256[] memory userClaimed = new uint256[](tokens.length); for (uint256 i = 0; i < tokens.length; i++) { userClaimed[i] = claimed[user][tokens[i]]; } return (tokens, userClaimed); } /// @dev Utility function to encode a merkle tree node function encodeClaim( address[] calldata tokens, uint256[] calldata cumulativeAmounts, address account, uint256 index, uint256 cycle ) public pure returns (bytes memory encoded, bytes32 hash) { encoded = abi.encode(index, account, cycle, tokens, cumulativeAmounts); hash = keccak256(encoded); } /// @notice Claim specifiedrewards for a set of tokens at a given cycle number /// @notice Can choose to skip certain tokens by setting amount to claim to zero for that token index function claim( address[] calldata tokens, uint256[] calldata cumulativeAmounts, uint256 index, uint256 cycle, bytes32[] calldata merkleProof, uint256[] calldata amountsToClaim ) external whenNotPaused { // require(cycle <= currentCycle, "Invalid cycle"); require(cycle == currentCycle, "Invalid cycle"); _verifyClaimProof(tokens, cumulativeAmounts, index, cycle, merkleProof); bool claimedAny = false; // User must claim at least 1 token by the end of the function // Claim each token for (uint256 i = 0; i < tokens.length; i++) { // Run claim and register claimedAny if a claim occurs if (_tryClaim(msg.sender, cycle, tokens[i], cumulativeAmounts[i], amountsToClaim[i])) { claimedAny = true; } } // If no tokens were claimed, revert if (claimedAny == false) { revert("No tokens to claim"); } } // ===== Root Updater Restricted ===== /// @notice Propose a new root and content hash, which will be stored as pending until approved function proposeRoot( bytes32 root, bytes32 contentHash, uint256 cycle, uint256 startBlock, uint256 endBlock ) external whenNotPaused { _onlyRootProposer(); require(cycle == currentCycle.add(1), "Incorrect cycle"); // require(startBlock == lastPublishEndBlock.add(1), "Incorrect start block"); pendingCycle = cycle; pendingMerkleRoot = root; pendingMerkleContentHash = contentHash; lastProposeStartBlock = startBlock; lastProposeEndBlock = endBlock; lastProposeTimestamp = now; lastProposeBlockNumber = block.number; emit RootProposed(cycle, pendingMerkleRoot, pendingMerkleContentHash, startBlock, endBlock, now, block.number); } /// ===== Guardian Restricted ===== /// @notice Approve the current pending root and content hash function approveRoot( bytes32 root, bytes32 contentHash, uint256 cycle, uint256 startBlock, uint256 endBlock ) external whenNotPaused { _onlyRootValidator(); require(root == pendingMerkleRoot, "Incorrect root"); require(contentHash == pendingMerkleContentHash, "Incorrect content hash"); require(cycle == pendingCycle, "Incorrect cycle"); require(startBlock == lastProposeStartBlock, "Incorrect cycle start block"); require(endBlock == lastProposeEndBlock, "Incorrect cycle end block"); currentCycle = cycle; merkleRoots[cycle] = root; merkleRoot = root; merkleContentHash = contentHash; lastPublishStartBlock = startBlock; lastPublishEndBlock = endBlock; lastPublishTimestamp = now; lastPublishBlockNumber = block.number; emit RootUpdated(currentCycle, root, contentHash, startBlock, endBlock, now, block.number); } /// @notice Pause publishing of new roots function pause() external { _onlyPauser(); _pause(); } /// @notice Unpause publishing of new roots function unpause() external { _onlyUnpauser(); _unpause(); } /// ===== Internal Helper Functions ===== function _verifyClaimProof( address[] calldata tokens, uint256[] calldata cumulativeAmounts, uint256 index, uint256 cycle, bytes32[] calldata merkleProof ) internal view { // Verify the merkle proof. bytes32 node = keccak256(abi.encode(index, msg.sender, cycle, tokens, cumulativeAmounts)); // require(MerkleProofUpgradeable.verify(merkleProof, getMerkleRootFor(cycle), node), "Invalid proof"); require(MerkleProofUpgradeable.verify(merkleProof, merkleRoot, node), "Invalid proof"); } function _getClaimed(address account, address token) internal view returns (uint256) { return claimed[account][token]; } function _setClaimed( address account, address token, uint256 amount ) internal { claimed[account][token] = amount; } function _tryClaim( address account, uint256 cycle, address token, uint256 cumulativeClaimable, uint256 toClaim ) internal returns (bool claimAttempted) { // If none claimable for token or none specifed to claim, skip this token if (cumulativeClaimable == 0 || toClaim == 0) { return false; } uint256 claimedBefore = _getClaimed(account, token); uint256 claimable = cumulativeClaimable.sub(claimedBefore); // If none claimable, don't attempt to claim if (claimable == 0) { return false; } require(claimable > 0, "None available to claim"); // This is reduntant, it is kept to ward off evil claimers. require(toClaim <= claimable, "Excessive claim"); uint256 claimedAfter = claimedBefore.add(toClaim); _setClaimed(account, token, claimedAfter); require(claimedAfter <= cumulativeClaimable, "Invariant: cumulative claimed > cumulative claimable"); IERC20Upgradeable(token).safeTransfer(account, _parseValue(token, toClaim)); emit Claimed(account, token, toClaim, cycle, now, block.number); return true; } /// @dev Determine how many tokens to distribute based on cumulativeAmount /// @dev Parse share values for rebasing tokens according to their logic /// @dev Return normal ERC20 values directly /// @dev Currently handles the DIGG special case function _parseValue(address token, uint256 amount) internal view returns (uint256) { if (token == DIGG_ADDRESS) { return IDigg(token).sharesToFragments(amount); } else { return amount; } } /// @dev test function to get cycle to starting point function setCycle(uint256 x) public { _onlyAdmin(); currentCycle = x; } }
Get the cumulative number of tokens claimed for an account, given a list of tokens
function getClaimedFor(address user, address[] memory tokens) public view returns (address[] memory, uint256[] memory) { uint256[] memory userClaimed = new uint256[](tokens.length); for (uint256 i = 0; i < tokens.length; i++) { userClaimed[i] = claimed[user][tokens[i]]; } return (tokens, userClaimed); }
5,865,522
/* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.3; contract LibEIP712 { // EIP191 header for EIP712 prefix string constant internal EIP191_HEADER = "\x19\x01"; // EIP712 Domain Name value string constant internal EIP712_DOMAIN_NAME = "0x Protocol"; // EIP712 Domain Version value string constant internal EIP712_DOMAIN_VERSION = "2"; // Hash of the EIP712 Domain Separator Schema bytes32 public constant EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = keccak256(abi.encodePacked( "EIP712Domain(", "string name,", "string version,", "address verifyingContract", ")" )); // Hash of the EIP712 Domain Separator data // solhint-disable-next-line var-name-mixedcase bytes32 public EIP712_DOMAIN_HASH; constructor () public { EIP712_DOMAIN_HASH = keccak256(abi.encode( EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH, keccak256(bytes(EIP712_DOMAIN_NAME)), keccak256(bytes(EIP712_DOMAIN_VERSION)), address(this) )); } /// @dev Calculates EIP712 encoding for a hash struct in this EIP712 Domain. /// @param hashStruct The EIP712 hash struct. /// @return EIP712 hash applied to this EIP712 Domain. function hashEIP712Message(bytes32 hashStruct) internal view returns (bytes32) { return keccak256(abi.encodePacked(EIP191_HEADER, EIP712_DOMAIN_HASH, hashStruct)); } }
Calculates EIP712 encoding for a hash struct in this EIP712 Domain. hashStruct The EIP712 hash struct. return EIP712 hash applied to this EIP712 Domain.
function hashEIP712Message(bytes32 hashStruct) internal view returns (bytes32) { return keccak256(abi.encodePacked(EIP191_HEADER, EIP712_DOMAIN_HASH, hashStruct)); }
1,073,075
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.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); } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @param operator The address which initiated the transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param id The ID of the token being transferred * @param value The amount of tokens being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } /** * @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); } } } } /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev 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); } } /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI, Ownable { using Address for address; using Strings for uint256; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @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, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } contract NafstarsAvatarsNFT is ERC1155("https://nafstars.nft4all.com/metadata/avatars/presale/{id}.json") { uint256 public mintPrice = 0.15 ether; uint256 public supplyCount = 0; uint256 public supplyMax = 500; address public withdrawAddress; string public name = "Nafstars Avatars NFT"; string public symbol = "NAVATARS"; function setURI(string memory newURI) public virtual onlyOwner { _setURI(newURI); } function setMintPrice(uint256 mintPrice_) public onlyOwner { mintPrice = mintPrice_; } function setWithdrawAddress(address withdrawAddress_) public onlyOwner { withdrawAddress = withdrawAddress_; } function mint(address to) public payable { require(supplyCount + 1 <= supplyMax, "Supply reached."); if (_msgSender() != owner()) { require(msg.value >= mintPrice, "Insufficient funds."); } supplyCount = supplyCount + 1; _mint(to, 1, 1, ""); } function batchMint(address to, uint256 amount) public payable { require(amount > 0, "Invalid amount."); require(supplyCount + amount <= supplyMax, "Supply reached."); if (_msgSender() != owner()) { require(msg.value >= mintPrice * amount, "Insufficient funds."); } supplyCount = supplyCount + amount; _mint(to, 1, amount, ""); } function withdraw() external payable { require(_msgSender() == owner() || _msgSender() == withdrawAddress, "Ownable: caller not authorized"); (bool payment, ) = payable(withdrawAddress).call{value: address(this).balance}(""); require(payment); } }
xref:ROOT:erc1155.adocbatch-operations[Batched] version of {_mint}. Requirements: - `ids` and `amounts` must have the same length. - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the acceptance magic value./
function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); }
5,879,061
pragma solidity ^0.4.17; contract RevertProxy { bytes data; function() public { data = msg.data; } // solium-disable security/no-low-level-calls function execute(address _target) external returns (bool) { return _target.call(data); } }
solium-disable security/no-low-level-calls
function execute(address _target) external returns (bool) { return _target.call(data); }
6,379,158
./partial_match/42220/0xE0F2cc70E52f05eDb383313393d88Df2937DA55a/sources/Swap.sol
withdraw all admin fees to a given address self Swap struct to withdraw fees from to Address to send the fees to/
function withdrawAdminFees(Swap storage self, address to) external { for (uint256 i = 0; i < self.pooledTokens.length; i++) { IERC20 token = self.pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub(self.balances[i]); if (balance != 0) { token.safeTransfer(to, balance); } } }
3,500,270
./full_match/137/0x2A29dB56F0e7e9Dd6f8e1e16EE69D1F48D6A43D9/sources/contracts/MasterChef.sol
Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0 || pool.allocPoint == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 newtReward = multiplier.mul(NewtPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); newt.mint(devaddr, newtReward.div(10)); newt.mint(address(this), newtReward); pool.accNewtPerShare = pool.accNewtPerShare.add( newtReward.mul(1e18).div(lpSupply) ); pool.lastRewardBlock = block.number; }
4,722,221
./full_match/4/0x9bd1c031423ad95ed6C7b46B3Fa9a733C4361a3C/sources/contracts/Market.sol
Executes the sale for a published NFT nftAddress - Address of the NFT registry assetId - ID of the published NFT/
function executeOrder(address nftAddress, uint256 assetId) external { _executeOrder(nftAddress, assetId); }
12,382,544
pragma solidity ^0.4.16; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract WBIToken { // 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); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function WBIToken( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; 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` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function 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 on 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 on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData 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 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 Burn(_from, _value); return true; } function transferBatch(address[] recipients, uint256[] values) external { require(recipients.length == values.length); for (uint256 i = 0; i < recipients.length; i++) { _transfer(msg.sender, recipients[i], values[i]); } } }
Internal transfer, only can be called by this contract/ Prevent transfer to 0x0 address. Use burn() instead Check if the sender has enough Check for overflows Save this for an assertion in the future Subtract from the sender Add the same to the recipient Asserts are used to use static analysis to find bugs in your code. They should never fail
function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); }
10,326,635
pragma solidity ^0.4.21; /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint 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; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { uint public totalSupply; function balanceOf(address who) public view returns (uint); function transfer(address to, uint value) public returns (bool); event Transfer(address indexed from, address indexed to, uint value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint; mapping(address => uint) balances; /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { revert(); } _; } /** * @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, uint _value) public onlyPayloadSize(2 * 32) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint); function transferFrom(address from, address to, uint value) public returns (bool); function approve(address spender, uint value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint value); } /** * @title Standard ERC20 token * * @dev Implemantation of the basic standart 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 BasicToken, ERC20 { mapping (address => mapping (address => uint)) 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 uint the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) returns (bool) { uint _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) revert(); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on beahlf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) revert(); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens than an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) public view returns (uint remaining) { return allowed[_owner][_spender]; } } /** * @title LimitedTransferToken * @dev LimitedTransferToken defines the generic interface and the implementation to limit token * transferability for different events. It is intended to be used as a base class for other token * contracts. * LimitedTransferToken has been designed to allow for different limiting factors, * this can be achieved by recursively calling super.transferableTokens() until the base class is * hit. For example: * function transferableTokens(address holder, uint time, uint number) constant public returns (uint256) { * return min256(unlockedTokens, super.transferableTokens(holder, time, number)); * } * A working example is VestedToken.sol: * https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/VestedToken.sol */ contract LimitedTransferToken is ERC20 { /** * @dev Checks whether it can transfer or otherwise throws. */ modifier canTransfer(address _sender, uint _value) { if (_value > transferableTokens(_sender, now, block.number)) revert(); _; } /** * @dev Checks modifier and allows transfer if tokens are not locked. * @param _to The address that will recieve the tokens. * @param _value The amount of tokens to be transferred. */ function transfer(address _to, uint _value) public canTransfer(msg.sender, _value) returns (bool) { return super.transfer(_to, _value); } /** * @dev Checks modifier and allows transfer if tokens are not locked. * @param _from The address that will send the tokens. * @param _to The address that will recieve the tokens. * @param _value The amount of tokens to be transferred. */ function transferFrom(address _from, address _to, uint _value) public canTransfer(_from, _value) returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev Default transferable tokens function returns all tokens for a holder (no limit). * @dev Overwriting transferableTokens(address holder, uint time, uint number) is the way to provide the * specific logic for limiting token transferability for a holder over time or number. */ function transferableTokens(address holder, uint /* time */, uint /* number */) view public returns (uint256) { return balanceOf(holder); } } /** * @title Vested token * @dev Tokens that can be vested for a group of addresses. */ contract VestedToken is StandardToken, LimitedTransferToken { uint256 MAX_GRANTS_PER_ADDRESS = 20; struct TokenGrant { address granter; // 20 bytes uint256 value; // 32 bytes uint start; uint cliff; uint vesting; // 3 * 8 = 24 bytes bool revokable; bool burnsOnRevoke; // 2 * 1 = 2 bits? or 2 bytes? bool timeOrNumber; } // total 78 bytes = 3 sstore per operation (32 per sstore) mapping (address => TokenGrant[]) public grants; event NewTokenGrant(address indexed from, address indexed to, uint256 value, uint256 grantId); /** * @dev Grant tokens to a specified address * @param _to address The address which the tokens will be granted to. * @param _value uint256 The amount of tokens to be granted. * @param _start uint64 Time of the beginning of the grant. * @param _cliff uint64 Time of the cliff period. * @param _vesting uint64 The vesting period. */ function grantVestedTokens( address _to, uint256 _value, uint _start, uint _cliff, uint _vesting, bool _revokable, bool _burnsOnRevoke, bool _timeOrNumber ) public returns (bool) { // Check for date inconsistencies that may cause unexpected behavior if (_cliff < _start || _vesting < _cliff) { revert(); } // To prevent a user being spammed and have his balance locked (out of gas attack when calculating vesting). if (tokenGrantsCount(_to) > MAX_GRANTS_PER_ADDRESS) revert(); uint count = grants[_to].push( TokenGrant( _revokable ? msg.sender : 0, // avoid storing an extra 20 bytes when it is non-revokable _value, _start, _cliff, _vesting, _revokable, _burnsOnRevoke, _timeOrNumber ) ); transfer(_to, _value); emit NewTokenGrant(msg.sender, _to, _value, count - 1); return true; } /** * @dev Revoke the grant of tokens of a specifed address. * @param _holder The address which will have its tokens revoked. * @param _grantId The id of the token grant. */ function revokeTokenGrant(address _holder, uint _grantId) public returns (bool) { TokenGrant storage grant = grants[_holder][_grantId]; if (!grant.revokable) { // Check if grant was revokable revert(); } if (grant.granter != msg.sender) { // Only granter can revoke it revert(); } address receiver = grant.burnsOnRevoke ? 0xdead : msg.sender; uint256 nonVested = nonVestedTokens(grant, now, block.number); // remove grant from array delete grants[_holder][_grantId]; grants[_holder][_grantId] = grants[_holder][grants[_holder].length.sub(1)]; grants[_holder].length -= 1; balances[receiver] = balances[receiver].add(nonVested); balances[_holder] = balances[_holder].sub(nonVested); emit Transfer(_holder, receiver, nonVested); return true; } /** * @dev Calculate the total amount of transferable tokens of a holder at a given time * @param holder address The address of the holder * @param time uint The specific time. * @return An uint representing a holder&#39;s total amount of transferable tokens. */ function transferableTokens(address holder, uint time, uint number) view public returns (uint256) { uint256 grantIndex = tokenGrantsCount(holder); if (grantIndex == 0) return balanceOf(holder); // shortcut for holder without grants // Iterate through all the grants the holder has, and add all non-vested tokens uint256 nonVested = 0; for (uint256 i = 0; i < grantIndex; i++) { nonVested = SafeMath.add(nonVested, nonVestedTokens(grants[holder][i], time, number)); } // Balance - totalNonVested is the amount of tokens a holder can transfer at any given time uint256 vestedTransferable = SafeMath.sub(balanceOf(holder), nonVested); // Return the minimum of how many vested can transfer and other value // in case there are other limiting transferability factors (default is balanceOf) return SafeMath.min256(vestedTransferable, super.transferableTokens(holder, time, number)); } /** * @dev Check the amount of grants that an address has. * @param _holder The holder of the grants. * @return A uint representing the total amount of grants. */ function tokenGrantsCount(address _holder) public view returns (uint index) { return grants[_holder].length; } /** * @dev Calculate amount of vested tokens at a specifc time. * @param tokens uint256 The amount of tokens grantted. * @param time uint64 The time to be checked * @param start uint64 A time representing the begining of the grant * @param cliff uint64 The cliff period. * @param vesting uint64 The vesting period. * @return An uint representing the amount of vested tokensof a specif grant. * transferableTokens * | _/-------- vestedTokens rect * | _/ * | _/ * | _/ * | _/ * | / * | .| * | . | * | . | * | . | * | . | * | . | * +===+===========+---------+----------> time * Start Clift Vesting */ function calculateVestedTokensTime( uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vesting) public pure returns (uint256) { // Shortcuts for before cliff and after vesting cases. if (time < cliff) return 0; if (time >= vesting) return tokens; // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can use just calculate a value // in the vesting rect (as shown in above&#39;s figure) // vestedTokens = tokens * (time - start) / (vesting - start) uint256 vestedTokens = SafeMath.div(SafeMath.mul(tokens, SafeMath.sub(time, start)), SafeMath.sub(vesting, start)); return vestedTokens; } function calculateVestedTokensNumber( uint256 tokens, uint256 number, uint256 start, uint256 cliff, uint256 vesting) public pure returns (uint256) { // Shortcuts for before cliff and after vesting cases. if (number < cliff) return 0; if (number >= vesting) return tokens; // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can use just calculate a value // in the vesting rect (as shown in above&#39;s figure) // vestedTokens = tokens * (number - start) / (vesting - start) uint256 vestedTokens = SafeMath.div(SafeMath.mul(tokens, SafeMath.sub(number, start)), SafeMath.sub(vesting, start)); return vestedTokens; } function calculateVestedTokens( bool timeOrNumber, uint256 tokens, uint256 time, uint256 number, uint256 start, uint256 cliff, uint256 vesting) public pure returns (uint256) { if (timeOrNumber) { return calculateVestedTokensTime( tokens, time, start, cliff, vesting ); } else { return calculateVestedTokensNumber( tokens, number, start, cliff, vesting ); } } /** * @dev Get all information about a specifc grant. * @param _holder The address which will have its tokens revoked. * @param _grantId The id of the token grant. * @return Returns all the values that represent a TokenGrant(address, value, start, cliff, * revokability, burnsOnRevoke, and vesting) plus the vested value at the current time. */ function tokenGrant(address _holder, uint _grantId) public view returns (address granter, uint256 value, uint256 vested, uint start, uint cliff, uint vesting, bool revokable, bool burnsOnRevoke, bool timeOrNumber) { TokenGrant storage grant = grants[_holder][_grantId]; granter = grant.granter; value = grant.value; start = grant.start; cliff = grant.cliff; vesting = grant.vesting; revokable = grant.revokable; burnsOnRevoke = grant.burnsOnRevoke; timeOrNumber = grant.timeOrNumber; vested = vestedTokens(grant, now, block.number); } /** * @dev Get the amount of vested tokens at a specific time. * @param grant TokenGrant The grant to be checked. * @param time The time to be checked * @return An uint representing the amount of vested tokens of a specific grant at a specific time. */ function vestedTokens(TokenGrant grant, uint time, uint number) private pure returns (uint256) { return calculateVestedTokens( grant.timeOrNumber, grant.value, uint256(time), uint256(number), uint256(grant.start), uint256(grant.cliff), uint256(grant.vesting) ); } /** * @dev Calculate the amount of non vested tokens at a specific time. * @param grant TokenGrant The grant to be checked. * @param time uint64 The time to be checked * @return An uint representing the amount of non vested tokens of a specifc grant on the * passed time frame. */ function nonVestedTokens(TokenGrant grant, uint time, uint number) private pure returns (uint256) { return grant.value.sub(vestedTokens(grant, time, number)); } /** * @dev Calculate the date when the holder can trasfer all its tokens * @param holder address The address of the holder * @return An uint representing the date of the last transferable tokens. */ function lastTokenIsTransferableDate(address holder) view public returns (uint date) { date = now; uint256 grantIndex = grants[holder].length; for (uint256 i = 0; i < grantIndex; i++) { if (grants[holder][i].timeOrNumber) { date = SafeMath.max256(grants[holder][i].vesting, date); } } } function lastTokenIsTransferableNumber(address holder) view public returns (uint number) { number = block.number; uint256 grantIndex = grants[holder].length; for (uint256 i = 0; i < grantIndex; i++) { if (!grants[holder][i].timeOrNumber) { number = SafeMath.max256(grants[holder][i].vesting, number); } } } } // QUESTIONS FOR AUDITORS: // - Considering we inherit from VestedToken, how much does that hit at our gas price? // vesting: 365 days, 365 days / 1 vesting contract GOCToken is VestedToken { //FIELDS string public name = "Global Optimal Chain"; string public symbol = "GOC"; uint public decimals = 18; uint public INITIAL_SUPPLY = 20 * 100000000 * 1 ether; uint public iTime; uint public iBlock; // Initialization contract grants msg.sender all of existing tokens. function GOCToken() public { totalSupply = INITIAL_SUPPLY; iTime = now; iBlock = block.number; address toAddress = msg.sender; balances[toAddress] = totalSupply; grantVestedTokens(toAddress, totalSupply.div(100).mul(30), iTime, iTime, iTime, false, false, true); grantVestedTokens(toAddress, totalSupply.div(100).mul(30), iTime, iTime + 365 days, iTime + 365 days, false, false, true); grantVestedTokens(toAddress, totalSupply.div(100).mul(20), iTime + 1095 days, iTime + 1095 days, iTime + 1245 days, false, false, true); uint startMine = uint(1054080) + block.number;// 1054080 = (183 * 24 * 60 * 60 / 15) uint finishMine = uint(210240000) + block.number;// 210240000 = (100 * 365 * 24 * 60 * 60 / 15) grantVestedTokens(toAddress, totalSupply.div(100).mul(20), startMine, startMine, finishMine, false, false, false); } // Transfer amount of tokens from sender account to recipient. function transfer(address _to, uint _value) public returns (bool) { // no-op, allow even during crowdsale, in order to work around using grantVestedTokens() while in crowdsale if (_to == msg.sender) return false; return super.transfer(_to, _value); } // Transfer amount of tokens from a specified address to a recipient. // Transfer amount of tokens from sender account to recipient. function transferFrom(address _from, address _to, uint _value) public returns (bool) { return super.transferFrom(_from, _to, _value); } function currentTransferableTokens(address holder) view public returns (uint256) { return transferableTokens(holder, now, block.number); } }
Check the amount of grants that an address has. _holder The holder of the grants. return A uint representing the total amount of grants./
function tokenGrantsCount(address _holder) public view returns (uint index) { return grants[_holder].length; }
65,332
./partial_match/80001/0x3715FE0c0E39c2D28dB7f374Fe1F58481da51697/sources/contracts/interfaces/plugins/IDynamicFeeManager.sol
The interface for the Algebra dynamic fee manager This contract calculates adaptive fee
interface IDynamicFeeManager is IAlgebraDynamicFeePlugin { event FeeConfiguration(AlgebraFeeConfiguration feeConfig); function feeConfig() external view returns (uint16 alpha1, uint16 alpha2, uint32 beta1, uint32 beta2, uint16 gamma1, uint16 gamma2, uint16 baseFee); function changeFeeConfiguration(AlgebraFeeConfiguration calldata feeConfig) external; pragma solidity >=0.5.0; }
8,820,004
./full_match/1/0xa22Bd52116359e0cC8Fe21De52A959922CC7dF2a/sources/contracts/MarketingVoting.sol
Add an option `_option` is an option of answers on question
function addOption(string memory _option) external onlyRole(CONFIGURATOR_ROLE) { require(!_isStringEmpty(_option), "MarketingVoting: option is an empty string"); Option memory option = Option(_option, true); options.push(option); optionsCount++; }
16,466,160
./full_match/80001/0x5ccdEd3f094A02551e22C2D5d3c3834835942D48/sources/src/libraries/JoeLibrary.sol
given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { if (amountIn == 0) revert JoeLibrary__InsufficientAmount(); if (reserveIn == 0 || reserveOut == 0) revert JoeLibrary__InsufficientLiquidity(); uint256 amountInWithFee = amountIn * 997; uint256 numerator = amountInWithFee * reserveOut; uint256 denominator = reserveIn * 1000 + amountInWithFee; amountOut = numerator / denominator; }
9,534,698
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "library.sol"; /** * @title Implementation of the {IERC20} interface. * @dev defines a dynamically generated ERC20-compliant option contract with given expiry date */ contract Option is Context, IOption { using SafeMath for uint256; /// @dev RoundData always kept for each round struct RoundData { mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowances; mapping (address => uint256) paidPremium; uint expiryDate; uint settlePrice; // settle price of this round, and is the strike price for next round. uint totalPremiums; // total premium in this round uint accPremiumShare; // accumulated premium share for a pooler } /// @dev all rounds RoundData[] private rounds; /// @dev buyer's latest unsettled round mapping (address => uint) private unclaimedProfitsRounds; /// @dev mark pooler's highest settled round for a pooler. mapping (address => uint) private settledRounds; /// @dev a monotonic increasing round uint private currentRound; // @dev current round total supply uint256 _totalSupply; /// @dev option decimal should be identical asset decimal uint8 private _decimals; /// @dev the duration of this option, cannot be changed uint private immutable _duration; /// @dev pool contract address IOptionPool immutable private _pool; modifier onlyPool() { require(msg.sender == address(_pool), "Option: access restricted to owner"); _; } /** * @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 (uint duration_, uint8 decimals_, IOptionPool poolContract) public { _decimals = decimals_; // option settings _duration = duration_; // set duration once _pool = poolContract; // push round 0 rounds.push(); } /* * @dev only can reset this option if expiryDate has reached */ function resetOption(uint strikePrice_, uint newSupply) external override onlyPool { // load current round to r uint r = rounds.length-1; // record settle price rounds[r].settlePrice = strikePrice_; // kill storage to refund gas delete rounds[r].balances[address(_pool)]; // increase r for new round r++; // push to rounds array rounds.push(); // setting new round parameters _totalSupply = newSupply; rounds[r].expiryDate = block.timestamp + _duration; rounds[r].balances[address(_pool)] = newSupply; // set currentRound for readability currentRound = r; } /** * @dev get expiry date from round r */ function getRoundExpiryDate(uint r) external override view returns(uint) { return rounds[r].expiryDate; } /** * @dev get strike price from round r */ function getRoundStrikePrice(uint r) external override view returns(uint) { if (r > 0) { return rounds[r-1].settlePrice; } return 0; } /** * @dev get settle price from round r */ function getRoundSettlePrice(uint r) external override view returns(uint) { return rounds[r].settlePrice; } /** * @dev get total premiums from round r */ function getRoundTotalPremiums(uint r) external override view returns(uint) { return rounds[r].totalPremiums; } /** * @dev get balance from round r */ function getRoundBalanceOf(uint r, address account) external override view returns (uint256) { return rounds[r].balances[account]; } /** * @dev get round accumulated premium share */ function getRoundAccPremiumShare(uint r) external view override returns(uint) { return rounds[r].accPremiumShare; } /** * @dev set round accumulated premium share */ function setRoundAccPremiumShare(uint r, uint accPremiumShare) external override onlyPool { rounds[r].accPremiumShare = accPremiumShare; } /** * @dev get the unclaimed profits round for an account */ function getUnclaimedProfitsRound(address account) external override view returns (uint) { return unclaimedProfitsRounds[account]; } /** * @dev set a unclaimed profits round for an account */ function setUnclaimedProfitsRound(uint r, address account) external override onlyPool { unclaimedProfitsRounds[account] = r; } /** * @dev get highest settled round for a pooler */ function getSettledRound(address account) external override view returns (uint) { return settledRounds[account]; } /** * @dev set highest settled round for a pooler */ function setSettledRound(uint r, address account) external override onlyPool { settledRounds[account] = r; } /** * @dev add premium fee to current round in USDT */ function addPremium(address account, uint256 amountUSDT) external override onlyPool { rounds[currentRound].totalPremiums += amountUSDT; rounds[currentRound].paidPremium[account] += amountUSDT; } /** * @dev get paid premium for an account in round */ function getRoundAccountPaidPremiums(uint r, address account) external view override returns(uint) { return rounds[r].paidPremium[account]; } /** * @dev total premium fee in current round. */ function totalPremiums() external override view returns (uint) { return rounds[currentRound].totalPremiums; } /** * @dev get current round */ function getRound() external override view returns (uint) { return currentRound; } /** * @dev returns expiry date for current round */ function expiryDate() external override view returns (uint) { return rounds[currentRound].expiryDate; } /** * @dev returns strike price for current round */ function strikePrice() external override view returns (uint) { if (currentRound > 0) { return rounds[currentRound-1].settlePrice; } return 0; } /** * @dev Returns the name of the token. */ function name() public view override returns (string memory) { return string(abi.encodePacked(_pool.name(), "-", Strings.toString(_duration))); } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return name(); } /** * @dev Returns the pool of the contract. */ function getPool() public view override returns (address) { return address(_pool); } /** * @dev Returns the duration of the contract. */ function getDuration() public view override returns (uint) { return _duration; } /** * @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 override 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 rounds[currentRound].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 rounds[currentRound].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(), rounds[currentRound].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, rounds[currentRound].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, rounds[currentRound].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); rounds[currentRound].balances[sender] = rounds[currentRound].balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); rounds[currentRound].balances[recipient] = rounds[currentRound].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); rounds[currentRound].balances[account] = rounds[currentRound].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); _totalSupply = _totalSupply.sub(amount); rounds[currentRound].balances[account] = rounds[currentRound].balances[account].sub(amount, "ERC20: burn amount exceeds balance"); 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"); rounds[currentRound].allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256) internal { require(block.timestamp < rounds[currentRound].expiryDate, "option expired"); // settle buyers' profits, omit settlement if it's _pool address. if (from != address(0) && from != address(_pool)) { _pool.settleBuyer(from); } if (to != address(0) && to != address(_pool)) { _pool.settleBuyer(to); } } }
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"); rounds[currentRound].allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
15,832,605
pragma solidity ^0.6.2; import './Memory.sol'; /** * @dev Interface poseidon hash function */ contract PoseidonUnit { function poseidon(uint256[] memory) public pure returns(uint256) {} } /** * @dev Rollup helper functions */ contract RollupHelpers { using Memory for *; PoseidonUnit insPoseidonUnit; struct Entry { bytes32 e1; bytes32 e2; bytes32 e3; bytes32 e4; bytes32 e5; bytes32 e6; } uint constant bytesOffChainTx = 3*2 + 2; uint constant rField = 21888242871839275222246405745257275088548364400416034343698204186575808495617; uint64 constant IDEN3_ROLLUP_TX = 4839017969649077913; /** * @dev Load poseidon smart contract * @param _poseidonContractAddr poseidon contract address */ constructor (address _poseidonContractAddr) public { insPoseidonUnit = PoseidonUnit(_poseidonContractAddr); } /** * @dev hash poseidon multi-input elements * @param inputs input element array * @return poseidon hash */ function hashGeneric(uint256[] memory inputs) internal view returns (uint256){ return insPoseidonUnit.poseidon(inputs); } /** * @dev hash poseidon for sparse merkle tree nodes * @param left input element array * @param right input element array * @return poseidon hash */ function hashNode(uint256 left, uint256 right) internal view returns (uint256){ uint256[] memory inputs = new uint256[](2); inputs[0] = left; inputs[1] = right; return hashGeneric(inputs); } /** * @dev hash poseidon for sparse merkle tree final nodes * @param key input element array * @param value input element array * @return poseidon hash1 */ function hashFinalNode(uint256 key, uint256 value) internal view returns (uint256){ uint256[] memory inputs = new uint256[](3); inputs[0] = key; inputs[1] = value; inputs[2] = 1; return hashGeneric(inputs); } /** * @dev poseidon hash for entry generic structure * @param entry entry structure * @return poseidon hash */ function hashEntry(Entry memory entry) internal view returns (uint256){ uint256[] memory inputs = new uint256[](6); inputs[0] = uint256(entry.e1); inputs[1] = uint256(entry.e2); inputs[2] = uint256(entry.e3); inputs[3] = uint256(entry.e4); inputs[4] = uint256(entry.e5); inputs[5] = uint256(entry.e6); return hashGeneric(inputs); } /** * @dev Verify sparse merkle tree proof * @param root root to verify * @param siblings all siblings * @param key key to verify * @param value value to verify * @param isNonExistence existence or non-existence verification * @param isOld indicates non-existence non-empty verification * @param oldKey needed in case of non-existence proof with non-empty node * @param oldValue needed in case of non-existence proof with non-empty node * @return true if verification is correct, false otherwise */ function smtVerifier(uint256 root, uint256[] memory siblings, uint256 key, uint256 value, uint256 oldKey, uint256 oldValue, bool isNonExistence, bool isOld, uint256 maxLevels) internal view returns (bool){ // Step 1: check if proof is non-existence non-empty uint256 newHash; if (isNonExistence && isOld) { // Check old key is final node uint exist = 0; uint levCounter = 0; while ((exist == 0) && (levCounter < maxLevels)) { exist = (uint8(oldKey >> levCounter) & 0x01) ^ (uint8(key >> levCounter) & 0x01); levCounter += 1; } if (exist == 0) { return false; } newHash = hashFinalNode(oldKey, oldValue); } // Step 2: Calcuate root uint256 nextHash = isNonExistence ? newHash : hashFinalNode(key, value); uint256 siblingTmp; for (int256 i = int256(siblings.length) - 1; i >= 0; i--) { siblingTmp = siblings[uint256(i)]; bool leftRight = (uint8(key >> i) & 0x01) == 1; nextHash = leftRight ? hashNode(siblingTmp, nextHash) : hashNode(nextHash, siblingTmp); } // Step 3: Check root return root == nextHash; } /** * @dev build entry for fee plan * @param feePlan contains all fee plan data * @return entry structure */ function buildEntryFeePlan(bytes32[2] memory feePlan) internal pure returns (Entry memory entry) { // build element 1 entry.e1 = bytes32(feePlan[0] << 128) >> (256 - 128); // build element 2 entry.e2 = bytes32(feePlan[0]) >> (256 - 128); // build element 3 entry.e3 = bytes32(feePlan[1] << 128)>>(256 - 128); // build element 4 entry.e4 = bytes32(feePlan[1]) >> (256 - 128); } /** * @dev Calculate total fee amount for the beneficiary * @param tokenIds contains all token id (feePlanCoinsInput) * @param totalFees contains total fee for every token Id (feeTotal) * @param nToken token position on fee plan * @return total fee amount */ function calcTokenTotalFee(bytes32 tokenIds, bytes32 totalFees, uint nToken) internal pure returns (uint32, uint256) { uint256 ptr = 256 - ((nToken+1)*16); // get fee depending on token uint256 fee = float2Fix(uint16(bytes2(totalFees << ptr))); // get token id uint32 tokenId = uint16(bytes2(tokenIds << ptr)); return (tokenId, fee); } /** * @dev build entry for the exit tree leaf * @param amount amount * @param token token type * @param Ax x coordinate public key babyJub * @param Ay y coordinate public key babyJub * @param ethAddress ethereum address * @param nonce nonce parameter * @return entry structure */ function buildTreeState(uint256 amount, uint32 token, uint256 Ax, uint Ay, address ethAddress, uint48 nonce) internal pure returns (Entry memory entry) { // build element 1 entry.e1 = bytes32(bytes4(token)) >> (256 - 32); entry.e1 |= bytes32(bytes6(nonce)) >> (256 - 48 - 32); // build element 2 entry.e2 = bytes32(amount); // build element 3 entry.e3 = bytes32(Ax); // build element 4 entry.e4 = bytes32(Ay); // build element 5 entry.e5 = bytes32(bytes20(ethAddress)) >> (256 - 160); } /** * @dev build transaction data * @param amountF amount to send encoded as half precision float * @param token token identifier * @param nonce nonce parameter * @param fee fee sent by the user, it represents some % of the amount * @param rqOffset atomic swap paramater * @param onChain flag to indicate that transaction is an onChain one * @param newAccount flag to indicate if transaction is of deposit type * @return element */ function buildTxData( uint16 amountF, uint32 token, uint48 nonce, uint8 fee, uint8 rqOffset, bool onChain, bool newAccount ) internal pure returns (bytes32 element) { // build element element = bytes32(bytes8(IDEN3_ROLLUP_TX)) >> (256 - 64); element |= bytes32(bytes2(amountF)) >> (256 - 16 - 64); element |= bytes32(bytes4(token)) >> (256 - 32 - 16 - 64); element |= bytes32(bytes6(nonce)) >> (256 - 48 - 32 - 16 - 64); bytes1 nextByte = bytes1(fee) & 0x0f; nextByte = nextByte | (bytes1(rqOffset << 4) & 0x70); nextByte = onChain ? (nextByte | 0x80): nextByte; element |= bytes32(nextByte) >> (256 - 8 - 48 - 32 - 16 - 64); bytes1 last = newAccount ? bytes1(0x01) : bytes1(0x00); element |= bytes32(last) >> (256 - 8 - 8 - 48 - 32 - 16 - 64); } /** * @dev build on-chain Hash * @param oldOnChainHash previous on chain hash * @param txData transaction data coded into a bytes32 * @param loadAmount input amount * @param dataOnChain poseidon hash of the onChain data * @param fromEthAddr ethereum addres sender * @return entry structure */ function buildOnChainHash( uint256 oldOnChainHash, uint256 txData, uint128 loadAmount, uint256 dataOnChain, address fromEthAddr ) internal pure returns (Entry memory entry) { // build element 1 entry.e1 = bytes32(oldOnChainHash); // build element 2 entry.e2 = bytes32(txData); // build element 3 entry.e3 = bytes32(bytes16(loadAmount)) >> (256 - 128); // build element 4 entry.e4 = bytes32(dataOnChain); // build element 5 entry.e5 = bytes32(bytes20(fromEthAddr)) >> (256 - 160); } /** * @dev build hash of the on-chain data * @param fromAx x coordinate public key BabyJubJub sender * @param fromAy y coordinate public key BabyJubJub sender * @param toEthAddr ethereum addres receiver * @param toAx x coordinate public key BabyJubJub receiver * @param toAy y coordinate public key BabyJubJub receiver * @return entry structure */ function buildOnChainData( uint256 fromAx, uint256 fromAy, address toEthAddr, uint256 toAx, uint256 toAy ) internal pure returns (Entry memory entry) { // build element 1 entry.e1 = bytes32(fromAx); // build element 2 entry.e2 = bytes32(fromAy); // build element 3 entry.e3 = bytes32(bytes20(toEthAddr)) >> (256 - 160); // build element 4 entry.e4 = bytes32(toAx); // build element 5 entry.e5 = bytes32(toAy); } /** * @dev Decode half floating precision * @param float Float half precision encode number * @return Decoded floating half precision */ function float2Fix(uint16 float) public pure returns (uint256) { uint256 m = float & 0x3FF; uint256 e = float >> 11; uint256 e5 = (float >> 10) & 1; uint256 exp = 10 ** e; uint256 fix = m * exp; if ((e5 == 1) && (e != 0)){ fix = fix + (exp / 2); } return fix; } /** * @dev Retrieve ethereum address from a msg plus signature * @param msgHash message hash * @param rsv signature * @return Ethereum address recovered from the signature */ function checkSig(bytes32 msgHash, bytes memory rsv) public pure returns (address) { bytes32 r; bytes32 s; uint8 v; // solium-disable security/no-inline-assembly assembly { r := mload(add(rsv, 32)) s := mload(add(rsv, 64)) v := byte(0, mload(add(rsv, 96))) } return ecrecover(msgHash, v, r, s); } /** * @dev update on-chain fees * it updates every batch if it is full or build * @param onChainTxCount number of on-chain transactions in the same batch * @param currentFee current on-chain fee * @return newFee */ function updateOnchainFee(uint256 onChainTxCount, uint256 currentFee) internal pure returns (uint256 newFee) { if (10 < onChainTxCount) newFee = (currentFee*100722)/100000; else if (10 > onChainTxCount) newFee = (currentFee*100000)/100722; else newFee = currentFee; if (newFee > 1 ether) newFee = 1 ether; else if (newFee < (1 szabo / 1000) ) // 1 Gwei newFee = 1 szabo / 1000; } /** * @dev update deposit fee * It updates every batch * @param depositCount number of deposits in the same batch * @param oldFee current deposit fee * @return newFee */ function updateDepositFee(uint32 depositCount, uint256 oldFee) internal pure returns (uint256 newFee) { newFee = oldFee; for (uint32 i = 0; i < depositCount; i++) { newFee = newFee * 10000008235 / 10000000000; } } }
build on-chain Hash oldOnChainHash previous on chain hash txData transaction data coded into a bytes32 loadAmount input amount dataOnChain poseidon hash of the onChain data fromEthAddr ethereum addres sender return entry structure/ build element 1 build element 2 build element 3 build element 4 build element 5
function buildOnChainHash( uint256 oldOnChainHash, uint256 txData, uint128 loadAmount, uint256 dataOnChain, address fromEthAddr ) internal pure returns (Entry memory entry) { entry.e1 = bytes32(oldOnChainHash); entry.e2 = bytes32(txData); entry.e3 = bytes32(bytes16(loadAmount)) >> (256 - 128); entry.e4 = bytes32(dataOnChain); entry.e5 = bytes32(bytes20(fromEthAddr)) >> (256 - 160); }
12,971,283
pragma solidity ^0.4.16; 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; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } 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( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; 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 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 Burn(_from, _value); return true; } } /******************************************/ /* ADVANCED TOKEN STARTS HERE */ /******************************************/ contract MyAdvancedToken is owned, TokenERC20 { uint256 public sellPrice; uint256 public buyPrice; 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 MyAdvancedToken( uint256 initialSupply, string tokenName, string tokenSymbol ) TokenERC20(initialSupply, tokenName, tokenSymbol) public {} /* 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 Transfer(_from, _to, _value); } /// @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; FrozenFunds(target, freeze); } }
Internal transfer, only can be called by this contract /
function _transfer(address _from, address _to, uint _value) internal { Transfer(_from, _to, _value); }
460,877
./partial_match/1/0x0cAD0089AA44FAC9A941D27649AB452ae38126b9/sources/WHALE.sol
once enabled, can never be turned off
function swimWhale() external onlyOwner { tradingActive = true; swapEnabled = true; }
9,347,879
pragma solidity ^0.4.20; contract AssetTransfer /* is WorkbenchBase('AssetTransfer', 'AssetTransfer') */ { enum StateType { Active, OfferPlaced, PendingInspection, Inspected, Appraised, NotionalAcceptance, BuyerAccepted, SellerAccepted, Accepted, Terminated } address public InstanceOwner; string public Description; uint public AskingPrice; StateType public State; address public InstanceBuyer; uint public OfferPrice; address public InstanceInspector; address public InstanceAppraiser; function AssetTransfer(string description, uint256 price) public { InstanceOwner = msg.sender; AskingPrice = price; Description = description; State = StateType.Active; // ContractCreated(); } function Terminate() public { if (InstanceOwner != msg.sender) { revert(); } State = StateType.Terminated; // ContractUpdated('Terminate'); } function Modify(string description, uint256 price) public { if (State != StateType.Active) { revert(); } if (InstanceOwner != msg.sender) { revert(); } Description = description; AskingPrice = price; // ContractUpdated('Modify'); } function MakeOffer(address inspector, address appraiser, uint256 offerPrice) public { if (inspector == 0x0 || appraiser == 0x0 || offerPrice == 0) { revert(); } if (State != StateType.Active) { revert(); } // Cannot enforce "AllowedRoles":["Buyer"] because Role information is unavailable if (InstanceOwner == msg.sender) // not expressible in the current specification language { revert(); } InstanceBuyer = msg.sender; InstanceInspector = inspector; InstanceAppraiser = appraiser; OfferPrice = offerPrice; State = StateType.OfferPlaced; // ContractUpdated('MakeOffer'); } function AcceptOffer() public { if (State != StateType.OfferPlaced) { revert(); } if (InstanceOwner != msg.sender) { revert(); } State = StateType.PendingInspection; // ContractUpdated('AcceptOffer'); } function Reject() public { if (State != StateType.OfferPlaced && State != StateType.PendingInspection && State != StateType.Inspected && State != StateType.Appraised && State != StateType.NotionalAcceptance && State != StateType.BuyerAccepted) { revert(); } if (InstanceOwner != msg.sender) { revert(); } InstanceBuyer = 0x0; State = StateType.Active; // ContractUpdated('Reject'); } function Accept() public { if (msg.sender != InstanceBuyer && msg.sender != InstanceOwner) { revert(); } if (msg.sender == InstanceOwner && State != StateType.NotionalAcceptance && State != StateType.BuyerAccepted) { revert(); } if (msg.sender == InstanceBuyer && State != StateType.NotionalAcceptance && State != StateType.SellerAccepted) { revert(); } if (msg.sender == InstanceBuyer) { if (State == StateType.NotionalAcceptance) { State = StateType.BuyerAccepted; } else if (State == StateType.SellerAccepted) { State = StateType.Accepted; } } else { if (State == StateType.NotionalAcceptance) { State = StateType.SellerAccepted; } else if (State == StateType.BuyerAccepted) { State = StateType.Accepted; } } // ContractUpdated('Accept'); } function ModifyOffer(uint256 offerPrice) public { if (State != StateType.OfferPlaced) { revert(); } if (InstanceBuyer != msg.sender || offerPrice == 0) { revert(); } OfferPrice = offerPrice; // ContractUpdated('ModifyOffer'); } function RescindOffer() public { if (State != StateType.OfferPlaced && State != StateType.PendingInspection && State != StateType.Inspected && State != StateType.Appraised && State != StateType.NotionalAcceptance && State != StateType.SellerAccepted) { revert(); } if (InstanceBuyer != msg.sender) { revert(); } InstanceBuyer = 0x0; OfferPrice = 0; State = StateType.Active; // ContractUpdated('RescindOffer'); } function MarkAppraised() public { if (InstanceAppraiser != msg.sender) { revert(); } if (State == StateType.PendingInspection) { State = StateType.Appraised; } else if (State == StateType.Inspected) { State = StateType.NotionalAcceptance; } else { revert(); } // ContractUpdated('MarkAppraised'); } function MarkInspected() public { if (InstanceInspector != msg.sender) { revert(); } if (State == StateType.PendingInspection) { State = StateType.Inspected; } else if (State == StateType.Appraised) { State = StateType.NotionalAcceptance; } else { revert(); } // ContractUpdated('MarkInspected'); } }
Cannot enforce "AllowedRoles":["Buyer"] because Role information is unavailable
function MakeOffer(address inspector, address appraiser, uint256 offerPrice) public { if (inspector == 0x0 || appraiser == 0x0 || offerPrice == 0) { revert(); } if (State != StateType.Active) { revert(); } { revert(); } InstanceBuyer = msg.sender; InstanceInspector = inspector; InstanceAppraiser = appraiser; OfferPrice = offerPrice; State = StateType.OfferPlaced;
13,038,252
pragma solidity ^0.8.0; pragma abicoder v2; import "./DELEGATE.sol"; interface iAppStore{ function install(uint256 appNumber) external view returns(string memory name,string[] memory names,address[] memory cons); } interface iApp{ function lock(address _lock) external; } interface iOverview{ function setApp(address[] memory apps,uint256 id) external; function setApp(address app,uint256 id) external; } //可以结合利用稳定的多签合约来管理 contract OS{ struct app{ string name; address[] delegates; //can see if need to update address[] constitute; mapping(address => uint256) delegateIndex; mapping(address => uint256) constituteIndex; mapping(address => string) constituteName; mapping(string => address) nameToConstitute; //it's no need to know that if it is inited //mapping(address => bool) inited; bool isUninstall; address lockAddress; } address public owner; uint256 public ownerIndex; mapping(address => mapping(bytes32 => bool)) public rightOf; mapping(uint256 => mapping(bytes32 => bool)) public rightAppOf; mapping(uint256 => app) private apps; //store constitute address mapping(uint256 => uint256) public appStoreNumber; //not inuse mapping(address => uint256) public delegatesOf; mapping(string => uint256) public nameToIndex; uint256 public appNext = 1; //can cosider remove the index of app address public outDoor; address public appStore; address public overview; /** @dev 构造 @param _owner 拥有者 @param _appStore appStore的地址 */ constructor(address _owner,address _appStore,address _overview){ owner = _owner; appStore = _appStore; overview = _overview; } //"owner"'s app的index恒为1 modifier ownerOnly(){ require(msg.sender == owner || delegatesOf[msg.sender] == ownerIndex,"OS/owner/not"); _; } modifier self(){ require(msg.sender == address(this) || msg.sender == owner,"OS/self/not"); _; } function changeOnwer() external ownerOnly{ owner = address(0); } function transferOwnerShip(address newOwner) external ownerOnly{ require(newOwner != address(0),"OS/transferOwnerShip/zero_address"); owner = newOwner; } /** @dev 授权 @param to_ 被授权的app地址 @param right 授权能力 @param status 授权状态 */ function approveRight(address to_,bytes32 right,bool status)external ownerOnly{ rightOf[to_][right] = status; } /** @dev 授权app @param appIndex app编号 @param right * @param status * */ function approveAppRight(uint256 appIndex,bytes32 right,bool status)external ownerOnly{ rightAppOf[appIndex][right] = status; } /** @dev 设置owner的app编号 @param newIndex app编号 */ function setOwnerIndex(uint256 newIndex) external ownerOnly{ require(newIndex > 0,"OS/setOwnerIndex/newIndex/zero"); ownerIndex = newIndex; emit SetOwnerIndex(newIndex,block.timestamp); } event SetOwnerIndex(uint256 indexed newIndex,uint256); function changeLock(address _new,string memory _name) external ownerOnly{ apps[nameToIndex[_name]].lockAddress = _new; emit ChangeLock(_new,block.timestamp); } event ChangeLock(address indexed new,uint256 time); //it can update /** @dev 安装 @param _appStoreNumber app在appStore的编号 */ function install(uint256 _appStoreNumber,address lockAddress) external { beforeSelf(msg.data); (string memory _name,string[] memory names,address[] memory _constitute) = iAppStore(appStore).install(_appStoreNumber); apps[appNext].name = _name; require(nameToIndex[_name] == 0,"OS/install/appname/inuse"); nameToIndex[_name] = appNext; require(_constitute.length == names.length,"OS/install/length/names_constitute/not_equal"); for(uint256 i = 0;i < names.length;i++){ apps[appNext].constitute = _constitute; apps[appNext].constituteName[_constitute[i]] = names[i]; //constituteOf[_constitute[i]] = appNext; apps[appNext].nameToConstitute[names[i]] = _constitute[i]; } for(uint256 i = 0;i < _constitute.length;i++){ Delegate deleAddress = new Delegate(address(this),appNext,i); apps[appNext].constituteIndex[_constitute[i]] = i+1; apps[appNext].delegates.push(address(deleAddress)); delegatesOf[address(deleAddress)] = appNext; iApp(address(deleAddress)).lock(lockAddress); _constitute[i] = address(deleAddress); apps[appNext].delegateIndex[_constitute[i]] = i+1; } apps[appNext].lockAddress = lockAddress; iOverview(overview).setApp(_constitute,appNext); appNext ++; emit Install(_appStoreNumber,block.timestamp,lockAddress); } event Install(uint256 indexed _appStoreNumber,uint256,address lock); /** @dev 更新 @param _appStoreNumber * */ function update(uint256 _appStoreNumber) external { beforeSelf(msg.data); (string memory _name,string[] memory names,address[] memory _constitute) = iAppStore(appStore).install(_appStoreNumber); require(_constitute.length == names.length,"OS/update/length/names_constitute/not_equal"); uint256 id = nameToIndex[_name]; require(id > 0,"os:id not in use"); uint256 length = apps[id].constitute.length; require(_constitute.length >= length,"OS/update/less_length"); for(uint256 i = 0;i < length;i++){ if(apps[id].constitute[i] != _constitute[i]){ apps[id].constitute[i] = _constitute[i]; } } if(_constitute.length - length > 0){ address allApp = new address[](_constitute.length - length) for(uint256 i = 0;i < _constitute.length - length;i++){ Delegate deleAddress = new Delegate(address(this),id,i+length); apps[appNext].constituteIndex[_constitute[i+length]] = i+1+length; apps[appNext].delegates.push(address(deleAddress)); delegatesOf[address(deleAddress)] = id; iApp(address(deleAddress)).lock(lockAddress); allApp[i] = address(deleAddress); apps[appNext].delegateIndex[allApp[i]] = i+1+length; } iOverview(overview).setApp(allApp,id); } emit Update1(_appStoreNumber,block.timestamp); } event Update1(uint256 indexed _appStoreNumber,uint256); /** @dev 更新app @param appName * @param constituteName 组件名字 @param newCon 新组件 */ function update(string memory appName,string memory constituteName,address newCon) external{ beforeSelf(msg.data); _update(appName,constituteName,newCon); emit Update2(appName,constituteName,newCon,block.timestamp); } event Update2(string indexed appName,string constituteName,address newCon,uint256); //it can update by yourself function _update(string memory appName,string memory constituteName,address newCon) internal { address tempAddress = getAddress(appName,constituteName); require( tempAddress != address(0),"OS/update/getAddress/zero_address"); uint256 tempIndex = apps[nameToIndex[appName]].constituteIndex[tempAddress]; apps[nameToIndex[appName]].constitute[tempIndex] = newCon; } /** @dev 添加新组件 @param appName * @param constituteName * @param newCon * */ function addConstitute(string memory appName,string memory constituteName,address newCon) external { beforeSelf(msg.data); require( getAddress(appName,constituteName) == address(0),"OS/addConstitute/getAddress/inuse"); uint256 index = nameToIndex[appName]; uint256 nextIndex = apps[index].delegates.length; Delegate tempD = new Delegate(address(this),index,nextIndex); delegatesOf[address(tempD)] = index; apps[index].constitute.push(newCon); apps[index].delegates.push(address(tempD)); apps[index].constituteIndex[newCon] = apps[index].constitute.length; apps[index].constituteName[newCon] = constituteName; emit AddConstitute(appName,constituteName,newCon,block.timestamp); } event AddConstitute(string indexed appName,string constituteName,address newCon,uint256); /** @dev 使app不可用 */ function disable(uint256 appIndex) external { beforeSelf(msg.data); apps[appIndex].isUninstall = true; emit Disable(appIndex,block.timestamp); } event Disable(uint256 indexed appIndex,uint256); /** @dev 使app可用 */ function enable(uint256 appIndex) external { beforeSelf(msg.data); apps[appIndex].isUninstall = false; emit Enable(appIndex,block.timestamp); } event Enable(uint256 indexed appIndex,uint256); /** @dev app调用时,需要设置的调用地址 */ function setOut(address to_) external { outDoor = to_; } /** @dev 用于app对外调用 */ fallback(bytes calldata _in) external payable returns(bytes memory){ beforeSelf(_in); bool success; bytes memory re; if(msg.value == 0){ (success,re) = outDoor.call(_in); } else{ (success,re) = outDoor.call{value:msg.value}(_in); } require(success,"OS/Fallback/call_error"); emit CallTo(outDoor,_in,block.timestamp); return re; } event CallTo(address indexed outDoor0,bytes _in,uint256); receive() external payable{} function transferETH(address to_,uint256 amount)external{ beforeSelf(msg.data); payable(to_).transfer(amount); emit TransferETH(to_,amount,block.timestamp); } event TransferETH(address indexed to_,uint256 amount,uint256); function getAddress(uint256 index,uint256 conIndex) external view returns(address){ return apps[index].constitute[conIndex]; } function getAddress(string memory appName,string memory constituteName) public view returns(address){ app storage appT = apps[nameToIndex[appName]]; address con = appT.nameToConstitute[constituteName]; uint256 index = appT.constituteIndex[con]; return appT.delegates[index-1]; } function verify(address to_,string memory appName,string memory constituteName) external view returns(bool){ return getAddress(appName,constituteName) == to_; } function getLock(string memory _name) external view returns(address){ return apps[nameToIndex[_name]].lockAddress; } /** @dev 认证权限 */ function beforeSelf(bytes memory _in) internal view { require(!apps[delegatesOf[msg.sender]].isUninstall,"OS/Fallback/app/disable"); bytes4 callAPI4; //bytes memory callData_ = calldata; for(uint256 i = 0;i < 4;i++){ callAPI4 |= bytes4(_in[i]&0xFF)>>(i*8); } bytes32 choose = bytes32(callAPI4) | (bytes32(bytes20(outDoor)) >>32); bool right1 = rightOf[msg.sender][choose]; bool right2 = rightAppOf[delegatesOf[msg.sender]][choose]; require(right1 || right2 ,"OS/Fallback/no_right"); } }
/constituteOf[_constitute[i]] = appNext;
function install(uint256 _appStoreNumber,address lockAddress) external { beforeSelf(msg.data); (string memory _name,string[] memory names,address[] memory _constitute) = iAppStore(appStore).install(_appStoreNumber); apps[appNext].name = _name; require(nameToIndex[_name] == 0,"OS/install/appname/inuse"); nameToIndex[_name] = appNext; require(_constitute.length == names.length,"OS/install/length/names_constitute/not_equal"); for(uint256 i = 0;i < names.length;i++){ apps[appNext].constitute = _constitute; apps[appNext].constituteName[_constitute[i]] = names[i]; apps[appNext].nameToConstitute[names[i]] = _constitute[i]; } for(uint256 i = 0;i < _constitute.length;i++){ Delegate deleAddress = new Delegate(address(this),appNext,i); apps[appNext].constituteIndex[_constitute[i]] = i+1; apps[appNext].delegates.push(address(deleAddress)); delegatesOf[address(deleAddress)] = appNext; iApp(address(deleAddress)).lock(lockAddress); _constitute[i] = address(deleAddress); apps[appNext].delegateIndex[_constitute[i]] = i+1; } apps[appNext].lockAddress = lockAddress; iOverview(overview).setApp(_constitute,appNext); appNext ++; emit Install(_appStoreNumber,block.timestamp,lockAddress); } event Install(uint256 indexed _appStoreNumber,uint256,address lock); @param _appStoreNumber *
13,137,171
./full_match/1/0x0487443E94356E4C9677151b11d5048710bA80A8/sources/contracts/abstract/ERC721.sol
See {IERC721-approve}./
function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); if (to == owner) revert APPROVAL_TO_CURRENT_OWNER(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) revert CALLER_NOT_OWNER_OR_APPROVED(); _approve(to, tokenId); }
3,876,767
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.4.21; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: REMIX_FILE_SYNC/ApprovedCreatorRegistryInterface.sol pragma solidity ^0.4.22; /** * Interface to the digital media store external contract that is * responsible for storing the common digital media and collection data. * This allows for new token contracts to be deployed and continue to reference * the digital media and collection data. */ contract ApprovedCreatorRegistryInterface { function getVersion() public pure returns (uint); function typeOfContract() public pure returns (string); function isOperatorApprovedForCustodialAccount( address _operator, address _custodialAddress) public view returns (bool); } // File: REMIX_FILE_SYNC/DigitalMediaStoreInterface.sol pragma solidity 0.4.25; /** * Interface to the digital media store external contract that is * responsible for storing the common digital media and collection data. * This allows for new token contracts to be deployed and continue to reference * the digital media and collection data. */ contract DigitalMediaStoreInterface { function getDigitalMediaStoreVersion() public pure returns (uint); function getStartingDigitalMediaId() public view returns (uint256); function registerTokenContractAddress() external; /** * Creates a new digital media object in storage * @param _creator address the address of the creator * @param _printIndex uint32 the current print index for the limited edition media * @param _totalSupply uint32 the total allowable prints for this media * @param _collectionId uint256 the collection id that this media belongs to * @param _metadataPath string the ipfs metadata path * @return the id of the new digital media created */ function createDigitalMedia( address _creator, uint32 _printIndex, uint32 _totalSupply, uint256 _collectionId, string _metadataPath) external returns (uint); /** * Increments the current print index of the digital media object * @param _digitalMediaId uint256 the id of the digital media * @param _increment uint32 the amount to increment by */ function incrementDigitalMediaPrintIndex( uint256 _digitalMediaId, uint32 _increment) external; /** * Retrieves the digital media object by id * @param _digitalMediaId uint256 the address of the creator */ function getDigitalMedia(uint256 _digitalMediaId) external view returns( uint256 id, uint32 totalSupply, uint32 printIndex, uint256 collectionId, address creator, string metadataPath); /** * Creates a new collection * @param _creator address the address of the creator * @param _metadataPath string the ipfs metadata path * @return the id of the new collection created */ function createCollection(address _creator, string _metadataPath) external returns (uint); /** * Retrieves a collection by id * @param _collectionId uint256 */ function getCollection(uint256 _collectionId) external view returns( uint256 id, address creator, string metadataPath); } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.4.21; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/lifecycle/Pausable.sol pragma solidity ^0.4.21; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } // File: REMIX_FILE_SYNC/MediaStoreVersionControl.sol pragma solidity 0.4.25; /** * A special control class that is used to configure and manage a token contract's * different digital media store versions. * * Older versions of token contracts had the ability to increment the digital media's * print edition in the media store, which was necessary in the early stages to provide * upgradeability and flexibility. * * New verions will get rid of this ability now that token contract logic * is more stable and we've built in burn capabilities. * * In order to support the older tokens, we need to be able to look up the appropriate digital * media store associated with a given digital media id on the latest token contract. */ contract MediaStoreVersionControl is Pausable { // The single allowed creator for this digital media contract. DigitalMediaStoreInterface public v1DigitalMediaStore; // The current digitial media store, used for this tokens creation. DigitalMediaStoreInterface public currentDigitalMediaStore; uint256 public currentStartingDigitalMediaId; /** * Validates that the managers are initialized. */ modifier managersInitialized() { require(v1DigitalMediaStore != address(0)); require(currentDigitalMediaStore != address(0)); _; } /** * Sets a digital media store address upon construction. * Once set it's immutable, so that a token contract is always * tied to one digital media store. */ function setDigitalMediaStoreAddress(address _dmsAddress) internal { DigitalMediaStoreInterface candidateDigitalMediaStore = DigitalMediaStoreInterface(_dmsAddress); require(candidateDigitalMediaStore.getDigitalMediaStoreVersion() == 2, "Incorrect version."); currentDigitalMediaStore = candidateDigitalMediaStore; currentDigitalMediaStore.registerTokenContractAddress(); currentStartingDigitalMediaId = currentDigitalMediaStore.getStartingDigitalMediaId(); } /** * Publicly callable by the owner, but can only be set one time, so don't make * a mistake when setting it. * * Will also check that the version on the other end of the contract is in fact correct. */ function setV1DigitalMediaStoreAddress(address _dmsAddress) public onlyOwner { require(address(v1DigitalMediaStore) == 0, "V1 media store already set."); DigitalMediaStoreInterface candidateDigitalMediaStore = DigitalMediaStoreInterface(_dmsAddress); require(candidateDigitalMediaStore.getDigitalMediaStoreVersion() == 1, "Incorrect version."); v1DigitalMediaStore = candidateDigitalMediaStore; v1DigitalMediaStore.registerTokenContractAddress(); } /** * Depending on the digital media id, determines whether to return the previous * version of the digital media manager. */ function _getDigitalMediaStore(uint256 _digitalMediaId) internal view managersInitialized returns (DigitalMediaStoreInterface) { if (_digitalMediaId < currentStartingDigitalMediaId) { return v1DigitalMediaStore; } else { return currentDigitalMediaStore; } } } // File: REMIX_FILE_SYNC/DigitalMediaManager.sol pragma solidity 0.4.25; /** * Manager that interfaces with the underlying digital media store contract. */ contract DigitalMediaManager is MediaStoreVersionControl { struct DigitalMedia { uint256 id; uint32 totalSupply; uint32 printIndex; uint256 collectionId; address creator; string metadataPath; } struct DigitalMediaCollection { uint256 id; address creator; string metadataPath; } ApprovedCreatorRegistryInterface public creatorRegistryStore; // Set the creator registry address upon construction. Immutable. function setCreatorRegistryStore(address _crsAddress) internal { ApprovedCreatorRegistryInterface candidateCreatorRegistryStore = ApprovedCreatorRegistryInterface(_crsAddress); require(candidateCreatorRegistryStore.getVersion() == 1); // Simple check to make sure we are adding the registry contract indeed // https://fravoll.github.io/solidity-patterns/string_equality_comparison.html require(keccak256(candidateCreatorRegistryStore.typeOfContract()) == keccak256("approvedCreatorRegistry")); creatorRegistryStore = candidateCreatorRegistryStore; } /** * Validates that the Registered store is initialized. */ modifier registryInitialized() { require(creatorRegistryStore != address(0)); _; } /** * Retrieves a collection object by id. */ function _getCollection(uint256 _id) internal view managersInitialized returns(DigitalMediaCollection) { uint256 id; address creator; string memory metadataPath; (id, creator, metadataPath) = currentDigitalMediaStore.getCollection(_id); DigitalMediaCollection memory collection = DigitalMediaCollection({ id: id, creator: creator, metadataPath: metadataPath }); return collection; } /** * Retrieves a digital media object by id. */ function _getDigitalMedia(uint256 _id) internal view managersInitialized returns(DigitalMedia) { uint256 id; uint32 totalSupply; uint32 printIndex; uint256 collectionId; address creator; string memory metadataPath; DigitalMediaStoreInterface _digitalMediaStore = _getDigitalMediaStore(_id); (id, totalSupply, printIndex, collectionId, creator, metadataPath) = _digitalMediaStore.getDigitalMedia(_id); DigitalMedia memory digitalMedia = DigitalMedia({ id: id, creator: creator, totalSupply: totalSupply, printIndex: printIndex, collectionId: collectionId, metadataPath: metadataPath }); return digitalMedia; } /** * Increments the print index of a digital media object by some increment. */ function _incrementDigitalMediaPrintIndex(DigitalMedia _dm, uint32 _increment) internal managersInitialized { DigitalMediaStoreInterface _digitalMediaStore = _getDigitalMediaStore(_dm.id); _digitalMediaStore.incrementDigitalMediaPrintIndex(_dm.id, _increment); } // Check if the token operator is approved for the owner address function isOperatorApprovedForCustodialAccount( address _operator, address _owner) internal view registryInitialized returns(bool) { return creatorRegistryStore.isOperatorApprovedForCustodialAccount( _operator, _owner); } } // File: REMIX_FILE_SYNC/SingleCreatorControl.sol pragma solidity 0.4.25; /** * A special control class that's used to help enforce that a DigitalMedia contract * will service only a single creator's address. This is used when deploying a * custom token contract owned and managed by a single creator. */ contract SingleCreatorControl { // The single allowed creator for this digital media contract. address public singleCreatorAddress; // The single creator has changed. event SingleCreatorChanged( address indexed previousCreatorAddress, address indexed newCreatorAddress); /** * Sets the single creator associated with this contract. This function * can only ever be called once, and should ideally be called at the point * of constructing the smart contract. */ function setSingleCreator(address _singleCreatorAddress) internal { require(singleCreatorAddress == address(0), "Single creator address already set."); singleCreatorAddress = _singleCreatorAddress; } /** * Checks whether a given creator address matches the single creator address. * Will always return true if a single creator address was never set. */ function isAllowedSingleCreator(address _creatorAddress) internal view returns (bool) { require(_creatorAddress != address(0), "0x0 creator addresses are not allowed."); return singleCreatorAddress == address(0) || singleCreatorAddress == _creatorAddress; } /** * A publicly accessible function that allows the current single creator * assigned to this contract to change to another address. */ function changeSingleCreator(address _newCreatorAddress) public { require(_newCreatorAddress != address(0)); require(msg.sender == singleCreatorAddress, "Not approved to change single creator."); singleCreatorAddress = _newCreatorAddress; emit SingleCreatorChanged(singleCreatorAddress, _newCreatorAddress); } } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Basic.sol pragma solidity ^0.4.21; /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721.sol pragma solidity ^0.4.21; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() public view returns (string _name); function symbol() public view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Receiver.sol pragma solidity ^0.4.21; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. This function MUST use 50,000 gas or less. Return of other * than the magic value MUST result in the transaction being reverted. * Note: the contract address is always the message sender. * @param _from The sending address * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` */ function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4); } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/AddressUtils.sol pragma solidity ^0.4.21; /** * 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. assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly return size > 0; } } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721BasicToken.sol pragma solidity ^0.4.21; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is ERC721Basic { using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existance of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * @dev The zero address indicates there is no approved address. * @dev There can only be one approved address per token at a given time. * @dev Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for a the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * @dev An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address _owner, address _operator) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) { address owner = ownerOf(_tokenId); return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender); } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @dev Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); emit Approval(_owner, address(0), _tokenId); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * @dev The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Token.sol pragma solidity ^0.4.21; /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Token is ERC721, ERC721BasicToken { // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping (address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; /** * @dev Constructor function */ function ERC721Token(string _name, string _symbol) public { name_ = _name; symbol_ = _symbol; } /** * @dev Gets the token name * @return string representing the token name */ function name() public view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() public view returns (string) { return symbol_; } /** * @dev Returns an URI for a given token ID * @dev Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view 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 * @dev Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * @dev Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // 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; } } // File: REMIX_FILE_SYNC/ERC721Safe.sol pragma solidity 0.4.25; // We have to specify what version of compiler this code will compile with contract ERC721Safe is ERC721Token { bytes4 constant internal InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant internal InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('safeTransferFrom(address,address,uint256)')); function supportsInterface(bytes4 _interfaceID) external view returns (bool); } // File: REMIX_FILE_SYNC/Memory.sol pragma solidity 0.4.25; library Memory { // Size of a word, in bytes. uint internal constant WORD_SIZE = 32; // Size of the header of a 'bytes' array. uint internal constant BYTES_HEADER_SIZE = 32; // Address of the free memory pointer. uint internal constant FREE_MEM_PTR = 0x40; // Compares the 'len' bytes starting at address 'addr' in memory with the 'len' // bytes starting at 'addr2'. // Returns 'true' if the bytes are the same, otherwise 'false'. function equals(uint addr, uint addr2, uint len) internal pure returns (bool equal) { assembly { equal := eq(keccak256(addr, len), keccak256(addr2, len)) } } // Compares the 'len' bytes starting at address 'addr' in memory with the bytes stored in // 'bts'. It is allowed to set 'len' to a lower value then 'bts.length', in which case only // the first 'len' bytes will be compared. // Requires that 'bts.length >= len' function equals(uint addr, uint len, bytes memory bts) internal pure returns (bool equal) { require(bts.length >= len); uint addr2; assembly { addr2 := add(bts, /*BYTES_HEADER_SIZE*/32) } return equals(addr, addr2, len); } // Allocates 'numBytes' bytes in memory. This will prevent the Solidity compiler // from using this area of memory. It will also initialize the area by setting // each byte to '0'. function allocate(uint numBytes) internal pure returns (uint addr) { // Take the current value of the free memory pointer, and update. assembly { addr := mload(/*FREE_MEM_PTR*/0x40) mstore(/*FREE_MEM_PTR*/0x40, add(addr, numBytes)) } uint words = (numBytes + WORD_SIZE - 1) / WORD_SIZE; for (uint i = 0; i < words; i++) { assembly { mstore(add(addr, mul(i, /*WORD_SIZE*/32)), 0) } } } // Copy 'len' bytes from memory address 'src', to address 'dest'. // This function does not check the or destination, it only copies // the bytes. function copy(uint src, uint dest, uint len) internal pure { // Copy word-length chunks while possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } dest += WORD_SIZE; src += WORD_SIZE; } // Copy remaining bytes uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } // Returns a memory pointer to the provided bytes array. function ptr(bytes memory bts) internal pure returns (uint addr) { assembly { addr := bts } } // Returns a memory pointer to the data portion of the provided bytes array. function dataPtr(bytes memory bts) internal pure returns (uint addr) { assembly { addr := add(bts, /*BYTES_HEADER_SIZE*/32) } } // This function does the same as 'dataPtr(bytes memory)', but will also return the // length of the provided bytes array. function fromBytes(bytes memory bts) internal pure returns (uint addr, uint len) { len = bts.length; assembly { addr := add(bts, /*BYTES_HEADER_SIZE*/32) } } // Creates a 'bytes memory' variable from the memory address 'addr', with the // length 'len'. The function will allocate new memory for the bytes array, and // the 'len bytes starting at 'addr' will be copied into that new memory. function toBytes(uint addr, uint len) internal pure returns (bytes memory bts) { bts = new bytes(len); uint btsptr; assembly { btsptr := add(bts, /*BYTES_HEADER_SIZE*/32) } copy(addr, btsptr, len); } // Get the word stored at memory address 'addr' as a 'uint'. function toUint(uint addr) internal pure returns (uint n) { assembly { n := mload(addr) } } // Get the word stored at memory address 'addr' as a 'bytes32'. function toBytes32(uint addr) internal pure returns (bytes32 bts) { assembly { bts := mload(addr) } } /* // Get the byte stored at memory address 'addr' as a 'byte'. function toByte(uint addr, uint8 index) internal pure returns (byte b) { require(index < WORD_SIZE); uint8 n; assembly { n := byte(index, mload(addr)) } b = byte(n); } */ } // File: REMIX_FILE_SYNC/HelperUtils.sol pragma solidity 0.4.25; /** * Internal helper functions */ contract HelperUtils { // converts bytes32 to a string // enable this when you use it. Saving gas for now // function bytes32ToString(bytes32 x) private pure returns (string) { // bytes memory bytesString = new bytes(32); // uint charCount = 0; // for (uint j = 0; j < 32; j++) { // byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); // if (char != 0) { // bytesString[charCount] = char; // charCount++; // } // } // bytes memory bytesStringTrimmed = new bytes(charCount); // for (j = 0; j < charCount; j++) { // bytesStringTrimmed[j] = bytesString[j]; // } // return string(bytesStringTrimmed); // } /** * Concatenates two strings * @param _a string * @param _b string * @return string concatenation of two string */ function strConcat(string _a, string _b) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); string memory ab = new string(_ba.length + _bb.length); bytes memory bab = bytes(ab); uint k = 0; for (uint i = 0; i < _ba.length; i++) bab[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) bab[k++] = _bb[i]; return string(bab); } } // File: REMIX_FILE_SYNC/DigitalMediaToken.sol pragma solidity 0.4.25; /** * The DigitalMediaToken contract. Fully implements the ERC721 contract * from OpenZeppelin without any modifications to it. * * This contract allows for the creation of: * 1. New Collections * 2. New DigitalMedia objects * 3. New DigitalMediaRelease objects * * The primary piece of logic is to ensure that an ERC721 token can * have a supply and print edition that is enforced by this contract. */ contract DigitalMediaToken is DigitalMediaManager, ERC721Safe, HelperUtils, SingleCreatorControl { event DigitalMediaReleaseCreateEvent( uint256 id, address owner, uint32 printEdition, string tokenURI, uint256 digitalMediaId); // Event fired when a new digital media is created event DigitalMediaCreateEvent( uint256 id, address storeContractAddress, address creator, uint32 totalSupply, uint32 printIndex, uint256 collectionId, string metadataPath); // Event fired when a digital media's collection is event DigitalMediaCollectionCreateEvent( uint256 id, address storeContractAddress, address creator, string metadataPath); // Event fired when a digital media is burned event DigitalMediaBurnEvent( uint256 id, address caller, address storeContractAddress); // Event fired when burning a token event DigitalMediaReleaseBurnEvent( uint256 tokenId, address owner); event UpdateDigitalMediaPrintIndexEvent( uint256 digitalMediaId, uint32 printEdition); // Event fired when a creator assigns a new creator address. event ChangedCreator( address creator, address newCreator); struct DigitalMediaRelease { // The unique edition number of this digital media release uint32 printEdition; // Reference ID to the digital media metadata uint256 digitalMediaId; } // Maps internal ERC721 token ID to digital media release object. mapping (uint256 => DigitalMediaRelease) public tokenIdToDigitalMediaRelease; // Maps a creator address to a new creator address. Useful if a creator // changes their address or the previous address gets compromised. mapping (address => address) public approvedCreators; // Token ID counter uint256 internal tokenIdCounter = 0; constructor (string _tokenName, string _tokenSymbol, uint256 _tokenIdStartingCounter) public ERC721Token(_tokenName, _tokenSymbol) { tokenIdCounter = _tokenIdStartingCounter; } /** * Creates a new digital media object. * @param _creator address the creator of this digital media * @param _totalSupply uint32 the total supply a creation could have * @param _collectionId uint256 the collectionId that it belongs to * @param _metadataPath string the path to the ipfs metadata * @return uint the new digital media id */ function _createDigitalMedia( address _creator, uint32 _totalSupply, uint256 _collectionId, string _metadataPath) internal returns (uint) { require(_validateCollection(_collectionId, _creator), "Creator for collection not approved."); uint256 newDigitalMediaId = currentDigitalMediaStore.createDigitalMedia( _creator, 0, _totalSupply, _collectionId, _metadataPath); emit DigitalMediaCreateEvent( newDigitalMediaId, address(currentDigitalMediaStore), _creator, _totalSupply, 0, _collectionId, _metadataPath); return newDigitalMediaId; } /** * Burns a token for a given tokenId and caller. * @param _tokenId the id of the token to burn. * @param _caller the address of the caller. */ function _burnToken(uint256 _tokenId, address _caller) internal { address owner = ownerOf(_tokenId); require(_caller == owner || getApproved(_tokenId) == _caller || isApprovedForAll(owner, _caller), "Failed token burn. Caller is not approved."); _burn(owner, _tokenId); delete tokenIdToDigitalMediaRelease[_tokenId]; emit DigitalMediaReleaseBurnEvent(_tokenId, owner); } /** * Burns a digital media. Once this function succeeds, this digital media * will no longer be able to mint any more tokens. Existing tokens need to be * burned individually though. * @param _digitalMediaId the id of the digital media to burn * @param _caller the address of the caller. */ function _burnDigitalMedia(uint256 _digitalMediaId, address _caller) internal { DigitalMedia memory _digitalMedia = _getDigitalMedia(_digitalMediaId); require(_checkApprovedCreator(_digitalMedia.creator, _caller) || isApprovedForAll(_digitalMedia.creator, _caller), "Failed digital media burn. Caller not approved."); uint32 increment = _digitalMedia.totalSupply - _digitalMedia.printIndex; _incrementDigitalMediaPrintIndex(_digitalMedia, increment); address _burnDigitalMediaStoreAddress = address(_getDigitalMediaStore(_digitalMedia.id)); emit DigitalMediaBurnEvent( _digitalMediaId, _caller, _burnDigitalMediaStoreAddress); } /** * Creates a new collection * @param _creator address the creator of this collection * @param _metadataPath string the path to the collection ipfs metadata * @return uint the new collection id */ function _createCollection( address _creator, string _metadataPath) internal returns (uint) { uint256 newCollectionId = currentDigitalMediaStore.createCollection( _creator, _metadataPath); emit DigitalMediaCollectionCreateEvent( newCollectionId, address(currentDigitalMediaStore), _creator, _metadataPath); return newCollectionId; } /** * Creates _count number of new digital media releases (i.e a token). * Bumps up the print index by _count. * @param _owner address the owner of the digital media object * @param _digitalMediaId uint256 the digital media id */ function _createDigitalMediaReleases( address _owner, uint256 _digitalMediaId, uint32 _count) internal { require(_count > 0, "Failed print edition. Creation count must be > 0."); require(_count < 10000, "Cannot print more than 10K tokens at once"); DigitalMedia memory _digitalMedia = _getDigitalMedia(_digitalMediaId); uint32 currentPrintIndex = _digitalMedia.printIndex; require(_checkApprovedCreator(_digitalMedia.creator, _owner), "Creator not approved."); require(isAllowedSingleCreator(_owner), "Creator must match single creator address."); require(_count + currentPrintIndex <= _digitalMedia.totalSupply, "Total supply exceeded."); string memory tokenURI = HelperUtils.strConcat("ipfs://ipfs/", _digitalMedia.metadataPath); for (uint32 i=0; i < _count; i++) { uint32 newPrintEdition = currentPrintIndex + 1 + i; DigitalMediaRelease memory _digitalMediaRelease = DigitalMediaRelease({ printEdition: newPrintEdition, digitalMediaId: _digitalMediaId }); uint256 newDigitalMediaReleaseId = _getNextTokenId(); tokenIdToDigitalMediaRelease[newDigitalMediaReleaseId] = _digitalMediaRelease; emit DigitalMediaReleaseCreateEvent( newDigitalMediaReleaseId, _owner, newPrintEdition, tokenURI, _digitalMediaId ); // This will assign ownership and also emit the Transfer event as per ERC721 _mint(_owner, newDigitalMediaReleaseId); _setTokenURI(newDigitalMediaReleaseId, tokenURI); tokenIdCounter = tokenIdCounter.add(1); } _incrementDigitalMediaPrintIndex(_digitalMedia, _count); emit UpdateDigitalMediaPrintIndexEvent(_digitalMediaId, currentPrintIndex + _count); } /** * Checks that a given caller is an approved creator and is allowed to mint or burn * tokens. If the creator was changed it will check against the updated creator. * @param _caller the calling address * @return bool allowed or not */ function _checkApprovedCreator(address _creator, address _caller) internal view returns (bool) { address approvedCreator = approvedCreators[_creator]; if (approvedCreator != address(0)) { return approvedCreator == _caller; } else { return _creator == _caller; } } /** * Validates the an address is allowed to create a digital media on a * given collection. Collections are tied to addresses. */ function _validateCollection(uint256 _collectionId, address _address) private view returns (bool) { if (_collectionId == 0 ) { return true; } DigitalMediaCollection memory collection = _getCollection(_collectionId); return _checkApprovedCreator(collection.creator, _address); } /** * Generates a new token id. */ function _getNextTokenId() private view returns (uint256) { return tokenIdCounter.add(1); } /** * Changes the creator that is approved to printing new tokens and creations. * Either the _caller must be the _creator or the _caller must be the existing * approvedCreator. * @param _caller the address of the caller * @param _creator the address of the current creator * @param _newCreator the address of the new approved creator */ function _changeCreator(address _caller, address _creator, address _newCreator) internal { address approvedCreator = approvedCreators[_creator]; require(_caller != address(0) && _creator != address(0), "Creator must be valid non 0x0 address."); require(_caller == _creator || _caller == approvedCreator, "Unauthorized caller."); if (approvedCreator == address(0)) { approvedCreators[_caller] = _newCreator; } else { require(_caller == approvedCreator, "Unauthorized caller."); approvedCreators[_creator] = _newCreator; } emit ChangedCreator(_creator, _newCreator); } /** * Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). */ function supportsInterface(bytes4 _interfaceID) external view returns (bool) { return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } } // File: REMIX_FILE_SYNC/OBOControl.sol pragma solidity 0.4.25; contract OBOControl is Pausable { // List of approved on behalf of users. mapping (address => bool) public approvedOBOs; /** * Add a new approved on behalf of user address. */ function addApprovedOBO(address _oboAddress) external onlyOwner { approvedOBOs[_oboAddress] = true; } /** * Removes an approved on bhealf of user address. */ function removeApprovedOBO(address _oboAddress) external onlyOwner { delete approvedOBOs[_oboAddress]; } /** * @dev Modifier to make the obo calls only callable by approved addressess */ modifier isApprovedOBO() { require(approvedOBOs[msg.sender] == true); _; } } // File: REMIX_FILE_SYNC/WithdrawFundsControl.sol pragma solidity 0.4.25; contract WithdrawFundsControl is Pausable { // List of approved on withdraw addresses mapping (address => uint256) public approvedWithdrawAddresses; // Full day wait period before an approved withdraw address becomes active uint256 constant internal withdrawApprovalWaitPeriod = 60 * 60 * 24; event WithdrawAddressAdded(address withdrawAddress); event WithdrawAddressRemoved(address widthdrawAddress); /** * Add a new approved on behalf of user address. */ function addApprovedWithdrawAddress(address _withdrawAddress) external onlyOwner { approvedWithdrawAddresses[_withdrawAddress] = now; emit WithdrawAddressAdded(_withdrawAddress); } /** * Removes an approved on bhealf of user address. */ function removeApprovedWithdrawAddress(address _withdrawAddress) external onlyOwner { delete approvedWithdrawAddresses[_withdrawAddress]; emit WithdrawAddressRemoved(_withdrawAddress); } /** * Checks that a given withdraw address ia approved and is past it's required * wait time. */ function isApprovedWithdrawAddress(address _withdrawAddress) internal view returns (bool) { uint256 approvalTime = approvedWithdrawAddresses[_withdrawAddress]; require (approvalTime > 0); return now - approvalTime > withdrawApprovalWaitPeriod; } } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Holder.sol pragma solidity ^0.4.21; contract ERC721Holder is ERC721Receiver { function onERC721Received(address, uint256, bytes) public returns(bytes4) { return ERC721_RECEIVED; } } // File: REMIX_FILE_SYNC/DigitalMediaSaleBase.sol pragma solidity 0.4.25; /** * Base class that manages the underlying functions of a Digital Media Sale, * most importantly the escrow of digital tokens. * * Manages ensuring that only approved addresses interact with this contract. * */ contract DigitalMediaSaleBase is ERC721Holder, Pausable, OBOControl, WithdrawFundsControl { using SafeMath for uint256; // Mapping of token contract address to bool indicated approval. mapping (address => bool) public approvedTokenContracts; /** * Adds a new token contract address to be approved to be called. */ function addApprovedTokenContract(address _tokenContractAddress) public onlyOwner { approvedTokenContracts[_tokenContractAddress] = true; } /** * Remove an approved token contract address from the list of approved addresses. */ function removeApprovedTokenContract(address _tokenContractAddress) public onlyOwner { delete approvedTokenContracts[_tokenContractAddress]; } /** * Checks that a particular token contract address is a valid address. */ function _isValidTokenContract(address _tokenContractAddress) internal view returns (bool) { return approvedTokenContracts[_tokenContractAddress]; } /** * Returns an ERC721 instance of a token contract address. Throws otherwise. * Only valid and approved token contracts are allowed to be interacted with. */ function _getTokenContract(address _tokenContractAddress) internal view returns (ERC721Safe) { require(_isValidTokenContract(_tokenContractAddress)); return ERC721Safe(_tokenContractAddress); } /** * Checks with the ERC-721 token contract that the _claimant actually owns the token. */ function _owns(address _claimant, uint256 _tokenId, address _tokenContractAddress) internal view returns (bool) { ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress); return (tokenContract.ownerOf(_tokenId) == _claimant); } /** * Checks with the ERC-721 token contract the owner of the a token */ function _ownerOf(uint256 _tokenId, address _tokenContractAddress) internal view returns (address) { ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress); return tokenContract.ownerOf(_tokenId); } /** * Checks to ensure that the token owner has approved the escrow contract */ function _approvedForEscrow(address _seller, uint256 _tokenId, address _tokenContractAddress) internal view returns (bool) { ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress); return (tokenContract.isApprovedForAll(_seller, this) || tokenContract.getApproved(_tokenId) == address(this)); } /** * Escrows an ERC-721 token from the seller to this contract. Assumes that the escrow contract * is already approved to make the transfer, otherwise it will fail. */ function _escrow(address _seller, uint256 _tokenId, address _tokenContractAddress) internal { // it will throw if transfer fails ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress); tokenContract.safeTransferFrom(_seller, this, _tokenId); } /** * Transfer an ERC-721 token from escrow to the buyer. This is to be called after a purchase is * completed. */ function _transfer(address _receiver, uint256 _tokenId, address _tokenContractAddress) internal { // it will throw if transfer fails ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress); tokenContract.safeTransferFrom(this, _receiver, _tokenId); } /** * Method to check whether this is an escrow contract */ function isEscrowContract() public pure returns(bool) { return true; } /** * Withdraws all the funds to a specified non-zero address */ function withdrawFunds(address _withdrawAddress) public onlyOwner { require(isApprovedWithdrawAddress(_withdrawAddress)); _withdrawAddress.transfer(address(this).balance); } } // File: REMIX_FILE_SYNC/DigitalMediaCore.sol pragma solidity 0.4.25; /** * This is the main driver contract that is used to control and run the service. Funds * are managed through this function, underlying contracts are also updated through * this contract. * * This class also exposes a set of creation methods that are allowed to be created * by an approved token creator, on behalf of a particular address. This is meant * to simply the creation flow for MakersToken users that aren't familiar with * the blockchain. The ERC721 tokens that are created are still fully compliant, * although it is possible for a malicious token creator to mint unwanted tokens * on behalf of a creator. Worst case, the creator can burn those tokens. */ contract DigitalMediaCore is DigitalMediaToken { using SafeMath for uint32; // List of approved token creators (on behalf of the owner) mapping (address => bool) public approvedTokenCreators; // Mapping from owner to operator accounts. mapping (address => mapping (address => bool)) internal oboOperatorApprovals; // Mapping of all disabled OBO operators. mapping (address => bool) public disabledOboOperators; // OboApproveAll Event event OboApprovalForAll( address _owner, address _operator, bool _approved); // Fired when disbaling obo capability. event OboDisabledForAll(address _operator); constructor ( string _tokenName, string _tokenSymbol, uint256 _tokenIdStartingCounter, address _dmsAddress, address _crsAddress) public DigitalMediaToken( _tokenName, _tokenSymbol, _tokenIdStartingCounter) { paused = true; setDigitalMediaStoreAddress(_dmsAddress); setCreatorRegistryStore(_crsAddress); } /** * Retrieves a Digital Media object. */ function getDigitalMedia(uint256 _id) external view returns ( uint256 id, uint32 totalSupply, uint32 printIndex, uint256 collectionId, address creator, string metadataPath) { DigitalMedia memory digitalMedia = _getDigitalMedia(_id); require(digitalMedia.creator != address(0), "DigitalMedia not found."); id = _id; totalSupply = digitalMedia.totalSupply; printIndex = digitalMedia.printIndex; collectionId = digitalMedia.collectionId; creator = digitalMedia.creator; metadataPath = digitalMedia.metadataPath; } /** * Retrieves a collection. */ function getCollection(uint256 _id) external view returns ( uint256 id, address creator, string metadataPath) { DigitalMediaCollection memory digitalMediaCollection = _getCollection(_id); require(digitalMediaCollection.creator != address(0), "Collection not found."); id = _id; creator = digitalMediaCollection.creator; metadataPath = digitalMediaCollection.metadataPath; } /** * Retrieves a Digital Media Release (i.e a token) */ function getDigitalMediaRelease(uint256 _id) external view returns ( uint256 id, uint32 printEdition, uint256 digitalMediaId) { require(exists(_id)); DigitalMediaRelease storage digitalMediaRelease = tokenIdToDigitalMediaRelease[_id]; id = _id; printEdition = digitalMediaRelease.printEdition; digitalMediaId = digitalMediaRelease.digitalMediaId; } /** * Creates a new collection. * * No creations of any kind are allowed when the contract is paused. */ function createCollection(string _metadataPath) external whenNotPaused { _createCollection(msg.sender, _metadataPath); } /** * Creates a new digital media object. */ function createDigitalMedia(uint32 _totalSupply, uint256 _collectionId, string _metadataPath) external whenNotPaused { _createDigitalMedia(msg.sender, _totalSupply, _collectionId, _metadataPath); } /** * Creates a new digital media object and mints it's first digital media release token. * * No creations of any kind are allowed when the contract is paused. */ function createDigitalMediaAndReleases( uint32 _totalSupply, uint256 _collectionId, string _metadataPath, uint32 _numReleases) external whenNotPaused { uint256 digitalMediaId = _createDigitalMedia(msg.sender, _totalSupply, _collectionId, _metadataPath); _createDigitalMediaReleases(msg.sender, digitalMediaId, _numReleases); } /** * Creates a new collection, a new digital media object within it and mints a new * digital media release token. * * No creations of any kind are allowed when the contract is paused. */ function createDigitalMediaAndReleasesInNewCollection( uint32 _totalSupply, string _digitalMediaMetadataPath, string _collectionMetadataPath, uint32 _numReleases) external whenNotPaused { uint256 collectionId = _createCollection(msg.sender, _collectionMetadataPath); uint256 digitalMediaId = _createDigitalMedia(msg.sender, _totalSupply, collectionId, _digitalMediaMetadataPath); _createDigitalMediaReleases(msg.sender, digitalMediaId, _numReleases); } /** * Creates a new digital media release (token) for a given digital media id. * * No creations of any kind are allowed when the contract is paused. */ function createDigitalMediaReleases(uint256 _digitalMediaId, uint32 _numReleases) external whenNotPaused { _createDigitalMediaReleases(msg.sender, _digitalMediaId, _numReleases); } /** * Deletes a token / digital media release. Doesn't modify the current print index * and total to be printed. Although dangerous, the owner of a token should always * be able to burn a token they own. * * Only the owner of the token or accounts approved by the owner can burn this token. */ function burnToken(uint256 _tokenId) external { _burnToken(_tokenId, msg.sender); } /* Support ERC721 burn method */ function burn(uint256 tokenId) public { _burnToken(tokenId, msg.sender); } /** * Ends the production run of a digital media. Afterwards no more tokens * will be allowed to be printed for this digital media. Used when a creator * makes a mistake and wishes to burn and recreate their digital media. * * When a contract is paused we do not allow new tokens to be created, * so stopping the production of a token doesn't have much purpose. */ function burnDigitalMedia(uint256 _digitalMediaId) external whenNotPaused { _burnDigitalMedia(_digitalMediaId, msg.sender); } /** * Resets the approval rights for a given tokenId. */ function resetApproval(uint256 _tokenId) external { clearApproval(msg.sender, _tokenId); } /** * Changes the creator for the current sender, in the event we * need to be able to mint new tokens from an existing digital media * print production. When changing creator, the old creator will * no longer be able to mint tokens. * * A creator may need to be changed: * 1. If we want to allow a creator to take control over their token minting (i.e go decentralized) * 2. If we want to re-issue private keys due to a compromise. For this reason, we can call this function * when the contract is paused. * @param _creator the creator address * @param _newCreator the new creator address */ function changeCreator(address _creator, address _newCreator) external { _changeCreator(msg.sender, _creator, _newCreator); } /**********************************************************************/ /**Calls that are allowed to be called by approved creator addresses **/ /**********************************************************************/ /** * Add a new approved token creator. * * Only the owner of this contract can update approved Obo accounts. */ function addApprovedTokenCreator(address _creatorAddress) external onlyOwner { require(disabledOboOperators[_creatorAddress] != true, "Address disabled."); approvedTokenCreators[_creatorAddress] = true; } /** * Removes an approved token creator. * * Only the owner of this contract can update approved Obo accounts. */ function removeApprovedTokenCreator(address _creatorAddress) external onlyOwner { delete approvedTokenCreators[_creatorAddress]; } /** * @dev Modifier to make the approved creation calls only callable by approved token creators */ modifier isApprovedCreator() { require( (approvedTokenCreators[msg.sender] == true && disabledOboOperators[msg.sender] != true), "Unapproved OBO address."); _; } /** * Only the owner address can set a special obo approval list. * When issuing OBO management accounts, we should give approvals through * this method only so that we can very easily reset it's approval in * the event of a disaster scenario. * * Only the owner themselves is allowed to give OboApproveAll access. */ function setOboApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender, "Approval address is same as approver."); require(approvedTokenCreators[_to], "Unrecognized OBO address."); require(disabledOboOperators[_to] != true, "Approval address is disabled."); oboOperatorApprovals[msg.sender][_to] = _approved; emit OboApprovalForAll(msg.sender, _to, _approved); } /** * Only called in a disaster scenario if the account has been compromised. * There's no turning back from this and the oboAddress will no longer be * able to be given approval rights or perform obo functions. * * Only the owner of this contract is allowed to disable an Obo address. * */ function disableOboAddress(address _oboAddress) public onlyOwner { require(approvedTokenCreators[_oboAddress], "Unrecognized OBO address."); disabledOboOperators[_oboAddress] = true; delete approvedTokenCreators[_oboAddress]; emit OboDisabledForAll(_oboAddress); } /** * Override the isApprovalForAll to check for a special oboApproval list. Reason for this * is that we can can easily remove obo operators if they every become compromised. */ function isApprovedForAll(address _owner, address _operator) public view returns (bool) { if (disabledOboOperators[_operator] == true) { return false; } else if (isOperatorApprovedForCustodialAccount(_operator, _owner) == true) { return true; } else if (oboOperatorApprovals[_owner][_operator]) { return true; } else { return super.isApprovedForAll(_owner, _operator); } } /** * Creates a new digital media object and mints it's digital media release tokens. * Called on behalf of the _owner. Pass count to mint `n` number of tokens. * * Only approved creators are allowed to create Obo. * * No creations of any kind are allowed when the contract is paused. */ function oboCreateDigitalMediaAndReleases( address _owner, uint32 _totalSupply, uint256 _collectionId, string _metadataPath, uint32 _numReleases) external whenNotPaused isApprovedCreator { uint256 digitalMediaId = _createDigitalMedia(_owner, _totalSupply, _collectionId, _metadataPath); _createDigitalMediaReleases(_owner, digitalMediaId, _numReleases); } /** * Creates a new collection, a new digital media object within it and mints a new * digital media release token. * Called on behalf of the _owner. * * Only approved creators are allowed to create Obo. * * No creations of any kind are allowed when the contract is paused. */ function oboCreateDigitalMediaAndReleasesInNewCollection( address _owner, uint32 _totalSupply, string _digitalMediaMetadataPath, string _collectionMetadataPath, uint32 _numReleases) external whenNotPaused isApprovedCreator { uint256 collectionId = _createCollection(_owner, _collectionMetadataPath); uint256 digitalMediaId = _createDigitalMedia(_owner, _totalSupply, collectionId, _digitalMediaMetadataPath); _createDigitalMediaReleases(_owner, digitalMediaId, _numReleases); } /** * Creates multiple digital media releases (tokens) for a given digital media id. * Called on behalf of the _owner. * * Only approved creators are allowed to create Obo. * * No creations of any kind are allowed when the contract is paused. */ function oboCreateDigitalMediaReleases( address _owner, uint256 _digitalMediaId, uint32 _numReleases) external whenNotPaused isApprovedCreator { _createDigitalMediaReleases(_owner, _digitalMediaId, _numReleases); } }
Removes an approved on bhealf of user address./
function removeApprovedWithdrawAddress(address _withdrawAddress) external onlyOwner { delete approvedWithdrawAddresses[_withdrawAddress]; emit WithdrawAddressRemoved(_withdrawAddress); }
890,405
./full_match/11155111/0x4Ac3832d773FE6B6dcC8EB6241B83212F1a55096/sources/contracts/discovery/GNS.sol
Build a subgraph ID based on the account creating it and a sequence number for that account. Subgraph ID is the keccak hash of account+seqID return Subgraph ID/ Too bad solidity 0.7.6 still doesn't have block.chainid solhint-disable-next-line no-inline-assembly
function _buildSubgraphID(address _account, uint256 _seqID) internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return uint256(keccak256(abi.encodePacked(_account, _seqID, chainId))); }
3,811,943
// SPDX-License-Identifier: MIT // Copyright (C) 2020, 2021, 2022 [email protected] // contracts/ChainlinkOracle.sol pragma solidity ^0.6.0; // import './interfaces/ISPTERC20.sol'; import './lib/SafeMath.sol'; /// @dev ERC20 of Swap.Pet Tokens(SPTERC20), compatible with OpenZeppelin ERC20 contract SPTERC20{ using SafeMath for uint; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; string private _name; string private _symbol; uint private _totalSupply; uint8 private _decimals; bytes32 public DOMAIN_SEPARATOR; mapping (address => uint) private _balances; mapping (address => mapping (address => uint)) private _allowances; mapping(address => uint) public nonces; event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); constructor(string memory name_, string memory symbol_) public { uint chainId; assembly { chainId := chainid() } _name = name_; _symbol = symbol_; _decimals = 18; DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(name_)), keccak256(bytes('1')), chainId, address(this) ) ); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view returns (uint) { return _totalSupply; } function balanceOf(address account_) public view returns (uint) { return _balances[account_]; } function transfer(address to_, uint256 amount_) public virtual returns (bool) { _transfer(msg.sender, to_, amount_); return true; } function allowance(address owner_, address spender_) public view virtual returns (uint256) { return _allowances[owner_][spender_]; } function approve(address spender_, uint256 amount_) public virtual returns (bool) { _approve(msg.sender, spender_, amount_); return true; } function transferFrom(address from_, address to_, uint256 amount_) public virtual returns (bool) { _transfer(from_, to_, amount_); _approve(from_, msg.sender, _allowances[from_][msg.sender].sub(amount_, "SPTERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender_, uint256 amount_) public virtual returns (bool) { _approve(msg.sender, spender_, _allowances[msg.sender][spender_].add(amount_)); return true; } function decreaseAllowance(address spender_, uint256 amount_) public virtual returns (bool) { _approve(msg.sender, spender_, _allowances[msg.sender][spender_].sub(amount_, "SPTERC20: decreased allowance below zero")); return true; } function _transfer(address from_, address to_, uint256 amount_) internal virtual { require(from_ != address(0), "SPTERC20: transfer from the zero address"); require(to_ != address(0), "SPTERC20: transfer to the zero address"); _balances[from_] = _balances[from_].sub(amount_, "SPTERC20: transfer amount_ exceeds balance"); _balances[to_] = _balances[to_].add(amount_); emit Transfer(from_, to_, amount_); } function _mint(address to_, uint256 amount_) internal virtual { require(to_ != address(0), "SPTERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount_); _balances[to_] = _balances[to_].add(amount_); emit Transfer(address(0), to_, amount_); } function _burn(address from_, uint256 amount_) internal virtual { require(from_ != address(0), "SPTERC20: burn from the zero address"); _balances[from_] = _balances[from_].sub(amount_, "SPTERC20: burn amount_ exceeds balance"); _totalSupply = _totalSupply.sub(amount_); emit Transfer(from_, address(0), amount_); } function _approve(address owner_, address spender_, uint256 amount_) internal virtual { require(owner_ != address(0), "SPTERC20: approve from the zero address"); require(spender_ != address(0), "SPTERC20: approve to the zero address"); _allowances[owner_][spender_] = amount_; emit Approval(owner_, spender_, amount_); } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /// @dev plus function for ERC20 of OpenZeppelin function permit(address owner_, address spender_, uint amount_, uint deadline_, uint8 v_, bytes32 r_, bytes32 s_) external { require(deadline_ >= block.timestamp, 'SPTERC20: permit expired!'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner_, spender_, amount_, nonces[owner_]++, deadline_)) ) ); address recoveredAddress = ecrecover(digest, v_, r_, s_); require(recoveredAddress != address(0) && recoveredAddress == owner_, 'SPTERC20: invalid signature!'); _approve(owner_, spender_, amount_); } }
plus function for ERC20 of OpenZeppelin
function permit(address owner_, address spender_, uint amount_, uint deadline_, uint8 v_, bytes32 r_, bytes32 s_) external { require(deadline_ >= block.timestamp, 'SPTERC20: permit expired!'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner_, spender_, amount_, nonces[owner_]++, deadline_)) ) ); address recoveredAddress = ecrecover(digest, v_, r_, s_); require(recoveredAddress != address(0) && recoveredAddress == owner_, 'SPTERC20: invalid signature!'); _approve(owner_, spender_, amount_); }
14,018,954
// hevm: flattened sources of src/DssSpell.sol // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity =0.6.12 >=0.5.12 >=0.6.12 <0.7.0; pragma experimental ABIEncoderV2; ////// lib/dss-exec-lib/src/CollateralOpts.sol /* pragma solidity ^0.6.12; */ struct CollateralOpts { bytes32 ilk; address gem; address join; address clip; address calc; address pip; bool isLiquidatable; bool isOSM; bool whitelistOSM; uint256 ilkDebtCeiling; uint256 minVaultAmount; uint256 maxLiquidationAmount; uint256 liquidationPenalty; uint256 ilkStabilityFee; uint256 startingPriceFactor; uint256 breakerTolerance; uint256 auctionDuration; uint256 permittedDrop; uint256 liquidationRatio; uint256 kprFlatReward; uint256 kprPctReward; } ////// lib/dss-exec-lib/src/DssExecLib.sol // // DssExecLib.sol -- MakerDAO Executive Spellcrafting Library // // Copyright (C) 2020 Maker Ecosystem Growth Holdings, Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity ^0.6.12; */ /* pragma experimental ABIEncoderV2; */ /* import { CollateralOpts } from "./CollateralOpts.sol"; */ interface Initializable { function init(bytes32) external; } interface Authorizable { function rely(address) external; function deny(address) external; } interface Fileable { function file(bytes32, address) external; function file(bytes32, uint256) external; function file(bytes32, bytes32, uint256) external; function file(bytes32, bytes32, address) external; } interface Drippable { function drip() external returns (uint256); function drip(bytes32) external returns (uint256); } interface Pricing { function poke(bytes32) external; } interface ERC20 { function decimals() external returns (uint8); } interface DssVat { function hope(address) external; function nope(address) external; function ilks(bytes32) external returns (uint256 Art, uint256 rate, uint256 spot, uint256 line, uint256 dust); function Line() external view returns (uint256); function suck(address, address, uint) external; } interface ClipLike { function vat() external returns (address); function dog() external returns (address); function spotter() external view returns (address); function calc() external view returns (address); function ilk() external returns (bytes32); } interface DogLike { function ilks(bytes32) external returns (address clip, uint256 chop, uint256 hole, uint256 dirt); } interface JoinLike { function vat() external returns (address); function ilk() external returns (bytes32); function gem() external returns (address); function dec() external returns (uint256); function join(address, uint) external; function exit(address, uint) external; } // Includes Median and OSM functions interface OracleLike_2 { function src() external view returns (address); function lift(address[] calldata) external; function drop(address[] calldata) external; function setBar(uint256) external; function kiss(address) external; function diss(address) external; function kiss(address[] calldata) external; function diss(address[] calldata) external; function orb0() external view returns (address); function orb1() external view returns (address); } interface MomLike { function setOsm(bytes32, address) external; function setPriceTolerance(address, uint256) external; } interface RegistryLike { function add(address) external; function xlip(bytes32) external view returns (address); } // https://github.com/makerdao/dss-chain-log interface ChainlogLike { function setVersion(string calldata) external; function setIPFS(string calldata) external; function setSha256sum(string calldata) external; function getAddress(bytes32) external view returns (address); function setAddress(bytes32, address) external; function removeAddress(bytes32) external; } interface IAMLike { function ilks(bytes32) external view returns (uint256,uint256,uint48,uint48,uint48); function setIlk(bytes32,uint256,uint256,uint256) external; function remIlk(bytes32) external; function exec(bytes32) external returns (uint256); } interface LerpFactoryLike { function newLerp(bytes32 name_, address target_, bytes32 what_, uint256 startTime_, uint256 start_, uint256 end_, uint256 duration_) external returns (address); function newIlkLerp(bytes32 name_, address target_, bytes32 ilk_, bytes32 what_, uint256 startTime_, uint256 start_, uint256 end_, uint256 duration_) external returns (address); } interface LerpLike { function tick() external returns (uint256); } library DssExecLib { /* WARNING The following library code acts as an interface to the actual DssExecLib library, which can be found in its own deployed contract. Only trust the actual library's implementation. */ address constant public LOG = 0xdA0Ab1e0017DEbCd72Be8599041a2aa3bA7e740F; uint256 constant internal WAD = 10 ** 18; uint256 constant internal RAY = 10 ** 27; uint256 constant internal RAD = 10 ** 45; uint256 constant internal THOUSAND = 10 ** 3; uint256 constant internal MILLION = 10 ** 6; uint256 constant internal BPS_ONE_PCT = 100; uint256 constant internal BPS_ONE_HUNDRED_PCT = 100 * BPS_ONE_PCT; uint256 constant internal RATES_ONE_HUNDRED_PCT = 1000000021979553151239153027; function add(uint256 x, uint256 y) internal pure returns (uint256 z) {} function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {} function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {} function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {} function dai() public view returns (address) { return getChangelogAddress("MCD_DAI"); } function vat() public view returns (address) { return getChangelogAddress("MCD_VAT"); } function cat() public view returns (address) { return getChangelogAddress("MCD_CAT"); } function dog() public view returns (address) { return getChangelogAddress("MCD_DOG"); } function jug() public view returns (address) { return getChangelogAddress("MCD_JUG"); } function pot() public view returns (address) { return getChangelogAddress("MCD_POT"); } function vow() public view returns (address) { return getChangelogAddress("MCD_VOW"); } function end() public view returns (address) { return getChangelogAddress("MCD_END"); } function esm() public view returns (address) { return getChangelogAddress("MCD_ESM"); } function reg() public view returns (address) { return getChangelogAddress("ILK_REGISTRY"); } function spotter() public view returns (address) { return getChangelogAddress("MCD_SPOT"); } function osmMom() public view returns (address) { return getChangelogAddress("OSM_MOM"); } function clipperMom() public view returns (address) { return getChangelogAddress("CLIPPER_MOM"); } function autoLine() public view returns (address) { return getChangelogAddress("MCD_IAM_AUTO_LINE"); } function daiJoin() public view returns (address) { return getChangelogAddress("MCD_JOIN_DAI"); } function lerpFab() public view returns (address) { return getChangelogAddress("LERP_FAB"); } function clip(bytes32 _ilk) public view returns (address _clip) {} function flip(bytes32 _ilk) public view returns (address _flip) {} function calc(bytes32 _ilk) public view returns (address _calc) {} function getChangelogAddress(bytes32 _key) public view returns (address) {} function setChangelogAddress(bytes32 _key, address _val) public {} function setChangelogVersion(string memory _version) public {} function authorize(address _base, address _ward) public {} function canCast(uint40 _ts, bool _officeHours) public pure returns (bool) {} function nextCastTime(uint40 _eta, uint40 _ts, bool _officeHours) public pure returns (uint256 castTime) {} function updateCollateralPrice(bytes32 _ilk) public {} function setContract(address _base, bytes32 _what, address _addr) public {} function setContract(address _base, bytes32 _ilk, bytes32 _what, address _addr) public {} function setValue(address _base, bytes32 _what, uint256 _amt) public {} function setValue(address _base, bytes32 _ilk, bytes32 _what, uint256 _amt) public {} function increaseGlobalDebtCeiling(uint256 _amount) public {} function setIlkDebtCeiling(bytes32 _ilk, uint256 _amount) public {} function setIlkAutoLineParameters(bytes32 _ilk, uint256 _amount, uint256 _gap, uint256 _ttl) public {} function setIlkAutoLineDebtCeiling(bytes32 _ilk, uint256 _amount) public {} function setIlkMinVaultAmount(bytes32 _ilk, uint256 _amount) public {} function setIlkLiquidationPenalty(bytes32 _ilk, uint256 _pct_bps) public {} function setIlkMaxLiquidationAmount(bytes32 _ilk, uint256 _amount) public {} function setIlkLiquidationRatio(bytes32 _ilk, uint256 _pct_bps) public {} function setStartingPriceMultiplicativeFactor(bytes32 _ilk, uint256 _pct_bps) public {} function setAuctionTimeBeforeReset(bytes32 _ilk, uint256 _duration) public {} function setAuctionPermittedDrop(bytes32 _ilk, uint256 _pct_bps) public {} function setKeeperIncentivePercent(bytes32 _ilk, uint256 _pct_bps) public {} function setKeeperIncentiveFlatRate(bytes32 _ilk, uint256 _amount) public {} function setLiquidationBreakerPriceTolerance(address _clip, uint256 _pct_bps) public {} function setIlkStabilityFee(bytes32 _ilk, uint256 _rate, bool _doDrip) public {} function setStairstepExponentialDecrease(address _calc, uint256 _duration, uint256 _pct_bps) public {} function whitelistOracleMedians(address _oracle) public {} function addReaderToWhitelist(address _oracle, address _reader) public {} function addReaderToWhitelistCall(address _oracle, address _reader) public {} function allowOSMFreeze(address _osm, bytes32 _ilk) public {} function addCollateralBase( bytes32 _ilk, address _gem, address _join, address _clip, address _calc, address _pip ) public {} function addNewCollateral(CollateralOpts memory co) public {} function sendPaymentFromSurplusBuffer(address _target, uint256 _amount) public {} function linearInterpolation(bytes32 _name, address _target, bytes32 _what, uint256 _startTime, uint256 _start, uint256 _end, uint256 _duration) public returns (address) {} function linearInterpolation(bytes32 _name, address _target, bytes32 _ilk, bytes32 _what, uint256 _startTime, uint256 _start, uint256 _end, uint256 _duration) public returns (address) {} } ////// lib/dss-exec-lib/src/DssAction.sol // // DssAction.sol -- DSS Executive Spell Actions // // Copyright (C) 2020 Maker Ecosystem Growth Holdings, Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity ^0.6.12; */ /* import { DssExecLib } from "./DssExecLib.sol"; */ /* import { CollateralOpts } from "./CollateralOpts.sol"; */ interface OracleLike_1 { function src() external view returns (address); } abstract contract DssAction { using DssExecLib for *; // Modifier used to limit execution time when office hours is enabled modifier limited { require(DssExecLib.canCast(uint40(block.timestamp), officeHours()), "Outside office hours"); _; } // Office Hours defaults to true by default. // To disable office hours, override this function and // return false in the inherited action. function officeHours() public virtual returns (bool) { return true; } // DssExec calls execute. We limit this function subject to officeHours modifier. function execute() external limited { actions(); } // DssAction developer must override `actions()` and place all actions to be called inside. // The DssExec function will call this subject to the officeHours limiter // By keeping this function public we allow simulations of `execute()` on the actions outside of the cast time. function actions() public virtual; // Provides a descriptive tag for bot consumption // This should be modified weekly to provide a summary of the actions // Hash: seth keccak -- "$(wget https://<executive-vote-canonical-post> -q -O - 2>/dev/null)" function description() external virtual view returns (string memory); // Returns the next available cast time function nextCastTime(uint256 eta) external returns (uint256 castTime) { require(eta <= uint40(-1)); castTime = DssExecLib.nextCastTime(uint40(eta), uint40(block.timestamp), officeHours()); } } ////// lib/dss-exec-lib/src/DssExec.sol // // DssExec.sol -- MakerDAO Executive Spell Template // // Copyright (C) 2020 Maker Ecosystem Growth Holdings, Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity ^0.6.12; */ interface PauseAbstract { function delay() external view returns (uint256); function plot(address, bytes32, bytes calldata, uint256) external; function exec(address, bytes32, bytes calldata, uint256) external returns (bytes memory); } interface Changelog { function getAddress(bytes32) external view returns (address); } interface SpellAction { function officeHours() external view returns (bool); function description() external view returns (string memory); function nextCastTime(uint256) external view returns (uint256); } contract DssExec { Changelog constant public log = Changelog(0xdA0Ab1e0017DEbCd72Be8599041a2aa3bA7e740F); uint256 public eta; bytes public sig; bool public done; bytes32 immutable public tag; address immutable public action; uint256 immutable public expiration; PauseAbstract immutable public pause; // Provides a descriptive tag for bot consumption // This should be modified weekly to provide a summary of the actions // Hash: seth keccak -- "$(wget https://<executive-vote-canonical-post> -q -O - 2>/dev/null)" function description() external view returns (string memory) { return SpellAction(action).description(); } function officeHours() external view returns (bool) { return SpellAction(action).officeHours(); } function nextCastTime() external view returns (uint256 castTime) { return SpellAction(action).nextCastTime(eta); } // @param _description A string description of the spell // @param _expiration The timestamp this spell will expire. (Ex. now + 30 days) // @param _spellAction The address of the spell action constructor(uint256 _expiration, address _spellAction) public { pause = PauseAbstract(log.getAddress("MCD_PAUSE")); expiration = _expiration; action = _spellAction; sig = abi.encodeWithSignature("execute()"); bytes32 _tag; // Required for assembly access address _action = _spellAction; // Required for assembly access assembly { _tag := extcodehash(_action) } tag = _tag; } function schedule() public { require(now <= expiration, "This contract has expired"); require(eta == 0, "This spell has already been scheduled"); eta = now + PauseAbstract(pause).delay(); pause.plot(action, tag, sig, eta); } function cast() public { require(!done, "spell-already-cast"); done = true; pause.exec(action, tag, sig, eta); } } ////// lib/dss-interfaces/src/dss/VestAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss-vest/blob/master/src/DssVest.sol interface VestAbstract { function TWENTY_YEARS() external view returns (uint256); function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function awards(uint256) external view returns (address, uint48, uint48, uint48, address, uint8, uint128, uint128); function ids() external view returns (uint256); function cap() external view returns (uint256); function usr(uint256) external view returns (address); function bgn(uint256) external view returns (uint256); function clf(uint256) external view returns (uint256); function fin(uint256) external view returns (uint256); function mgr(uint256) external view returns (address); function res(uint256) external view returns (uint256); function tot(uint256) external view returns (uint256); function rxd(uint256) external view returns (uint256); function file(bytes32, uint256) external; function create(address, uint256, uint256, uint256, uint256, address) external returns (uint256); function vest(uint256) external; function vest(uint256, uint256) external; function accrued(uint256) external view returns (uint256); function unpaid(uint256) external view returns (uint256); function restrict(uint256) external; function unrestrict(uint256) external; function yank(uint256) external; function yank(uint256, uint256) external; function move(uint256, address) external; function valid(uint256) external view returns (bool); } ////// src/DssSpell.sol // // Copyright (C) 2021 Dai Foundation // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity 0.6.12; */ /* pragma experimental ABIEncoderV2; */ /* import "dss-exec-lib/DssExec.sol"; */ /* import "dss-exec-lib/DssAction.sol"; */ /* import "dss-interfaces/dss/VestAbstract.sol"; */ contract DssSpellAction is DssAction { // Provides a descriptive tag for bot consumption // This should be modified weekly to provide a summary of the actions // Hash: seth keccak -- "$(wget https://raw.githubusercontent.com/makerdao/community/194592d74ae225132c1963527ae90190b8bfa476/governance/votes/Executive%20vote%20-%20November%2026,%202021.md -q -O - 2>/dev/null)" string public constant override description = "2021-11-26 MakerDAO Executive Spell | Hash: 0x7be806b3c9fa08603c0e25a1d73066384dcb0770407aeeb57668742321823d2c"; // Many of the settings that change weekly rely on the rate accumulator // described at https://docs.makerdao.com/smart-contract-modules/rates-module // To check this yourself, use the following rate calculation (example 8%): // // $ bc -l <<< 'scale=27; e( l(1.08)/(60 * 60 * 24 * 365) )' // // A table of rates can be found at // https://ipfs.io/ipfs/QmefQMseb3AiTapiAKKexdKHig8wroKuZbmLtPLv4u2YwW // // --- Rates --- uint256 constant ZERO_PCT_RATE = 1000000000000000000000000000; uint256 constant ONE_FIVE_PCT_RATE = 1000000000472114805215157978; // --- Math --- uint256 constant MILLION = 10 ** 6; uint256 constant RAD = 10 ** 45; // --- WBTC-C --- address constant MCD_JOIN_WBTC_C = 0x7f62f9592b823331E012D3c5DdF2A7714CfB9de2; address constant MCD_CLIP_WBTC_C = 0x39F29773Dcb94A32529d0612C6706C49622161D1; address constant MCD_CLIP_CALC_WBTC_C = 0x4fa2A328E7f69D023fE83454133c273bF5ACD435; // --- PSM-GUSD-A --- address constant MCD_JOIN_PSM_GUSD_A = 0x79A0FA989fb7ADf1F8e80C93ee605Ebb94F7c6A5; address constant MCD_CLIP_PSM_GUSD_A = 0xf93CC3a50f450ED245e003BFecc8A6Ec1732b0b2; address constant MCD_CLIP_CALC_PSM_GUSD_A = 0x7f67a68a0ED74Ea89A82eD9F243C159ed43a502a; address constant MCD_PSM_GUSD_A = 0x204659B2Fd2aD5723975c362Ce2230Fba11d3900; // --- Wallets + Dates --- address constant SAS_WALLET = 0xb1f950a51516a697E103aaa69E152d839182f6Fe; address constant IS_WALLET = 0xd1F2eEf8576736C1EbA36920B957cd2aF07280F4; address constant DECO_WALLET = 0xF482D1031E5b172D42B2DAA1b6e5Cbf6519596f7; address constant RWF_WALLET = 0x9e1585d9CA64243CE43D42f7dD7333190F66Ca09; address constant COM_WALLET = 0x1eE3ECa7aEF17D1e74eD7C447CcBA61aC76aDbA9; address constant MKT_WALLET = 0xDCAF2C84e1154c8DdD3203880e5db965bfF09B60; uint256 constant DEC_01_2021 = 1638316800; uint256 constant DEC_31_2021 = 1640908800; uint256 constant JAN_01_2022 = 1640995200; uint256 constant APR_30_2022 = 1651276800; uint256 constant JUN_30_2022 = 1656547200; uint256 constant AUG_01_2022 = 1659312000; uint256 constant NOV_30_2022 = 1669766400; uint256 constant DEC_31_2022 = 1672444800; uint256 constant SEP_01_2024 = 1725148800; function actions() public override { address WBTC = DssExecLib.getChangelogAddress("WBTC"); address PIP_WBTC = DssExecLib.getChangelogAddress("PIP_WBTC"); address GUSD = DssExecLib.getChangelogAddress("GUSD"); address PIP_GUSD = DssExecLib.getChangelogAddress("PIP_GUSD"); address MCD_VEST_DAI = DssExecLib.getChangelogAddress("MCD_VEST_DAI"); // Set Aave D3M Max Debt Ceiling // https://vote.makerdao.com/polling/QmZhvNu5?network=mainnet#poll-detail DssExecLib.setIlkAutoLineDebtCeiling("DIRECT-AAVEV2-DAI", 100 * MILLION); // Increase the Surplus Buffer via Lerp // https://vote.makerdao.com/polling/QmUqfZRv?network=mainnet#poll-detail DssExecLib.linearInterpolation({ _name: "Increase SB - 20211126", _target: DssExecLib.vow(), _what: "hump", _startTime: block.timestamp, _start: 60 * MILLION * RAD, _end: 90 * MILLION * RAD, _duration: 210 days }); // Add WBTC-C as a new Vault Type // https://vote.makerdao.com/polling/QmdVYMRo?network=mainnet#poll-detail DssExecLib.addNewCollateral( CollateralOpts({ ilk: "WBTC-C", gem: WBTC, join: MCD_JOIN_WBTC_C, clip: MCD_CLIP_WBTC_C, calc: MCD_CLIP_CALC_WBTC_C, pip: PIP_WBTC, isLiquidatable: true, isOSM: true, whitelistOSM: true, ilkDebtCeiling: 100 * MILLION, minVaultAmount: 7500, maxLiquidationAmount: 25 * MILLION, liquidationPenalty: 1300, ilkStabilityFee: ONE_FIVE_PCT_RATE, startingPriceFactor: 12000, breakerTolerance: 5000, auctionDuration: 90 minutes, permittedDrop: 4000, liquidationRatio: 17500, kprFlatReward: 300, kprPctReward: 10 }) ); DssExecLib.setStairstepExponentialDecrease(MCD_CLIP_CALC_WBTC_C, 90 seconds, 9900); DssExecLib.setIlkAutoLineParameters("WBTC-C", 1000 * MILLION, 100 * MILLION, 8 hours); // Add PSM-GUSD-A as a new Vault Type // https://vote.makerdao.com/polling/QmayeEjz?network=mainnet#poll-detail DssExecLib.addNewCollateral( CollateralOpts({ ilk: "PSM-GUSD-A", gem: GUSD, join: MCD_JOIN_PSM_GUSD_A, clip: MCD_CLIP_PSM_GUSD_A, calc: MCD_CLIP_CALC_PSM_GUSD_A, pip: PIP_GUSD, isLiquidatable: false, isOSM: false, whitelistOSM: false, ilkDebtCeiling: 10 * MILLION, minVaultAmount: 0, maxLiquidationAmount: 0, liquidationPenalty: 1300, ilkStabilityFee: ZERO_PCT_RATE, startingPriceFactor: 10500, breakerTolerance: 9500, // Allows for a 5% hourly price drop before disabling liquidations auctionDuration: 220 minutes, permittedDrop: 9000, liquidationRatio: 10000, kprFlatReward: 300, kprPctReward: 10 // 0.1% }) ); DssExecLib.setStairstepExponentialDecrease(MCD_CLIP_CALC_PSM_GUSD_A, 120 seconds, 9990); DssExecLib.setIlkAutoLineParameters("PSM-GUSD-A", 10 * MILLION, 10 * MILLION, 24 hours); // Core Unit Budget Distributions DssExecLib.sendPaymentFromSurplusBuffer(SAS_WALLET, 245_738); DssExecLib.sendPaymentFromSurplusBuffer(IS_WALLET, 195_443); DssExecLib.sendPaymentFromSurplusBuffer(DECO_WALLET, 465_625); VestAbstract(MCD_VEST_DAI).restrict( VestAbstract(MCD_VEST_DAI).create(RWF_WALLET, 1_860_000.00 * 10**18, JAN_01_2022, DEC_31_2022 - JAN_01_2022, 0, address(0)) ); VestAbstract(MCD_VEST_DAI).restrict( VestAbstract(MCD_VEST_DAI).create(COM_WALLET, 12_242.00 * 10**18, DEC_01_2021, DEC_31_2021 - DEC_01_2021, 0, address(0)) ); VestAbstract(MCD_VEST_DAI).restrict( VestAbstract(MCD_VEST_DAI).create(COM_WALLET, 257_500.00 * 10**18, JAN_01_2022, JUN_30_2022 - JAN_01_2022, 0, address(0)) ); VestAbstract(MCD_VEST_DAI).restrict( VestAbstract(MCD_VEST_DAI).create(SAS_WALLET, 1_130_393.00 * 10**18, DEC_01_2021, NOV_30_2022 - DEC_01_2021, 0, address(0)) ); VestAbstract(MCD_VEST_DAI).restrict( VestAbstract(MCD_VEST_DAI).create(IS_WALLET, 366_563.00 * 10**18, DEC_01_2021, AUG_01_2022 - DEC_01_2021, 0, address(0)) ); VestAbstract(MCD_VEST_DAI).restrict( VestAbstract(MCD_VEST_DAI).create(MKT_WALLET, 424_944.00 * 10**18, DEC_01_2021, APR_30_2022 - DEC_01_2021, 0, address(0)) ); VestAbstract(MCD_VEST_DAI).restrict( VestAbstract(MCD_VEST_DAI).create(DECO_WALLET, 5_121_875.00 * 10**18, DEC_01_2021, SEP_01_2024 - DEC_01_2021, 0, address(0)) ); // Changelog DssExecLib.setChangelogAddress("MCD_JOIN_WBTC_C", MCD_JOIN_WBTC_C); DssExecLib.setChangelogAddress("MCD_CLIP_WBTC_C", MCD_CLIP_WBTC_C); DssExecLib.setChangelogAddress("MCD_CLIP_CALC_WBTC_C", MCD_CLIP_CALC_WBTC_C); DssExecLib.setChangelogAddress("MCD_JOIN_PSM_GUSD_A", MCD_JOIN_PSM_GUSD_A); DssExecLib.setChangelogAddress("MCD_CLIP_PSM_GUSD_A", MCD_CLIP_PSM_GUSD_A); DssExecLib.setChangelogAddress("MCD_CLIP_CALC_PSM_GUSD_A", MCD_CLIP_CALC_PSM_GUSD_A); DssExecLib.setChangelogAddress("MCD_PSM_GUSD_A", MCD_PSM_GUSD_A); DssExecLib.setChangelogVersion("1.9.11"); } } contract DssSpell is DssExec { constructor() DssExec(block.timestamp + 30 days, address(new DssSpellAction())) public {} }
Office Hours defaults to true by default. To disable office hours, override this function and return false in the inherited action.
function officeHours() public virtual returns (bool) { return true; }
1,137,462
/*** * ███████╗██████╗ ██████╗███████╗██████╗ ██╗ ██╗ ██╗██████╗ * ██╔════╝██╔══██╗██╔════╝╚════██║╚════██╗███║ ██║ ██║╚════██╗ * █████╗ ██████╔╝██║ ██╔╝ █████╔╝╚██║ ██║ ██║ █████╔╝ * ██╔══╝ ██╔══██╗██║ ██╔╝ ██╔═══╝ ██║ ╚██╗ ██╔╝██╔═══╝ * ███████╗██║ ██║╚██████╗ ██║ ███████╗ ██║ ╚████╔╝ ███████╗ * ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚══════╝ ╚═╝ ╚═══╝ ╚══════╝ * * ██████╗ ██████╗ ██╗ ██╗ ███████╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗ * ██╔════╝██╔═══██╗██║ ██║ ██╔════╝██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║ * ██║ ██║ ██║██║ ██║ █████╗ ██║ ██║ ██║██║ ██║██╔██╗ ██║ * ██║ ██║ ██║██║ ██║ ██╔══╝ ██║ ██║ ██║██║ ██║██║╚██╗██║ * ╚██████╗╚██████╔╝███████╗███████╗███████╗╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║ * ╚═════╝ ╚═════╝ ╚══════╝╚══════╝╚══════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ * Written by MaxFlowO2, Senior Developer and Partner of G&M² Labs * Follow me on https://github.com/MaxflowO2 or Twitter @MaxFlowO2 * email: [email protected] * * Purpose: Chain ID #1-5 OpenSea compliant contracts with ERC2981 and whitelist * Gas Estimate as-is: 3,571,984 * * Rewritten to v2.1 standards (DeveloperV2 and ReentrancyGuard) * Rewritten to v2.1.1 standards, removal of ERC165Storage, msg.sender => _msgSender() * Rewritten to v2.1.2 standards, adding _msgValue() and _txOrigin() to ContextV2 this effects * ERC721.sol, ERC20.sol, Ownable.sol, Developer.sol, so all bases upgraded as of 31 Dec 2021 */ // SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./token/ERC721/ERC721.sol"; import "./access/OwnableV2.sol"; import "./access/DeveloperV2.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "./eip/2981/ERC2981Collection.sol"; import "./interface/IMAX721.sol"; import "./modules/Whitelist.sol"; import "./interface/IMAX721Whitelist.sol"; import "./modules/PaymentSplitter.sol"; import "./modules/BAYC.sol"; import "./modules/ContractURI.sol"; contract ERC721v2ETHCollectionWhitelist is ERC721, ERC2981Collection, BAYC, ContractURI, IMAX721, IMAX721Whitelist, ReentrancyGuard, Whitelist, PaymentSplitter, DeveloperV2, OwnableV2 { using Counters for Counters.Counter; Counters.Counter private _tokenIdCounter; Counters.Counter private _teamMintCounter; uint256 private mintStartID; uint256 private mintFees; uint256 private mintSize; uint256 private teamMintSize; uint256 private whitelistEndNumber; string private base; bool private enableMinter; bool private enableWhiteList; bool private lockedProvenance; bool private lockedPayees; event UpdatedBaseURI(string _old, string _new); event UpdatedMintFees(uint256 _old, uint256 _new); event UpdatedMintSize(uint _old, uint _new); event UpdatedMintStatus(bool _old, bool _new); event UpdatedRoyalties(address newRoyaltyAddress, uint256 newPercentage); event UpdatedTeamMintSize(uint _old, uint _new); event UpdatedWhitelistStatus(bool _old, bool _new); event UpdatedPresaleEnd(uint _old, uint _new); event ProvenanceLocked(bool _status); event PayeesLocked(bool _status); constructor() ERC721("ERC", "721") {} /*** * ███╗ ███╗██╗███╗ ██╗████████╗ * ████╗ ████║██║████╗ ██║╚══██╔══╝ * ██╔████╔██║██║██╔██╗ ██║ ██║ * ██║╚██╔╝██║██║██║╚██╗██║ ██║ * ██║ ╚═╝ ██║██║██║ ╚████║ ██║ * ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ */ // @notice this is the mint function, mint Fees in ERC20, // that locks tokens to contract, inable to withdrawl, public // nonReentrant() function. More comments within code. // @param uint amount - number of tokens minted function publicMint(uint256 amount) public payable nonReentrant() { // @notice using Checks-Effects-Interactions require(lockedProvenance, "Set Providence hashes"); require(enableMinter, "Minter not active"); require(_msgValue() == mintFees * amount, "Wrong amount of Native Token"); require(_tokenIdCounter.current() + amount <= mintSize, "Can not mint that many"); if(enableWhiteList) { require(isWhitelist[_msgSender()], "You are not Whitelisted"); // @notice remove from whitelist and emit (Whitelist.sol) _removeWhitelist(_msgSender()); for (uint i = 0; i < amount; i++) { _safeMint(_msgSender(), mintID()); _tokenIdCounter.increment(); } } else { for (uint i = 0; i < amount; i++) { _safeMint(_msgSender(), mintID()); _tokenIdCounter.increment(); } } } // @notice this is the team mint function, no mint Fees in ERC20, // public onlyOwner function. More comments within code // @param address _address - address to "airdropped" or team mint token function teamMint(address _address) public onlyOwner { require(lockedProvenance, "Set Providence hashes"); require(teamMintSize != 0, "Team minting not enabled"); require(_tokenIdCounter.current() < mintSize, "Can not mint that many"); require(_teamMintCounter.current() < teamMintSize, "Can not team mint anymore"); _safeMint(_address, mintID()); _tokenIdCounter.increment(); _teamMintCounter.increment(); } // @notice this shifts the _tokenIdCounter to proper mint number // @return the tokenID number using BAYC random start point on a // a fixed number of mints function mintID() internal view returns (uint256) { return (mintStartID + _tokenIdCounter.current()) % mintSize; } // Function to receive ether, msg.data must be empty receive() external payable { // From PaymentSplitter.sol emit PaymentReceived(_msgSender(), _msgValue()); } // Function to receive ether, msg.data is not empty fallback() external payable { // From PaymentSplitter.sol emit PaymentReceived(_msgSender(), _msgValue()); } // @notice this is a public getter for ETH blance on contract function getBalance() external view returns (uint) { return address(this).balance; } /*** * ██████╗ ██╗ ██╗███╗ ██╗███████╗██████╗ * ██╔═══██╗██║ ██║████╗ ██║██╔════╝██╔══██╗ * ██║ ██║██║ █╗ ██║██╔██╗ ██║█████╗ ██████╔╝ * ██║ ██║██║███╗██║██║╚██╗██║██╔══╝ ██╔══██╗ * ╚██████╔╝╚███╔███╔╝██║ ╚████║███████╗██║ ██║ * ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝ * This section will have all the internals set to onlyOwner */ // @notice this will use internal functions to set EIP 2981 // found in IERC2981.sol and used by ERC2981Collections.sol // @param address _royaltyAddress - Address for all royalties to go to // @param uint256 _percentage - Precentage in whole number of comission // of secondary sales function setRoyaltyInfo(address _royaltyAddress, uint256 _percentage) public onlyOwner { _setRoyalties(_royaltyAddress, _percentage); emit UpdatedRoyalties(_royaltyAddress, _percentage); } // @notice this will set the fees required to mint using // publicMint(), must enter in wei. So 1 ETH = 10**18. // @param uint256 _newFee - fee you set, if ETH 10**18, if // an ERC20 use token's decimals in calculation function setMintFees(uint256 _newFee) public onlyOwner { uint256 oldFee = mintFees; mintFees = _newFee; emit UpdatedMintFees(oldFee, mintFees); } // @notice this will enable publicMint() function enableMinting() public onlyOwner { bool old = enableMinter; enableMinter = true; emit UpdatedMintStatus(old, enableMinter); } // @notice this will disable publicMint() function disableMinting() public onlyOwner { bool old = enableMinter; enableMinter = false; emit UpdatedMintStatus(old, enableMinter); } // @notice this will enable whitelist or "if" in publicMint() function enableWhitelist() public onlyOwner { bool old = enableWhiteList; enableWhiteList = true; emit UpdatedWhitelistStatus(old, enableWhiteList); } // @notice this will disable whitelist or "else" in publicMint() function disableWhitelist() public onlyOwner { bool old = enableWhiteList; enableWhiteList = false; emit UpdatedWhitelistStatus(old, enableWhiteList); } // @notice adding an array/list of addresses to whitelist // uses internal function _addWhitelistBatch(address [] memory _addresses) // of Whitelist.sol to accomplish, will revert if duplicates exist in list // or array of addresses. // @param address [] memory _addresses - list/array of addresses function addWhitelistBatch(address [] memory _addresses) public onlyOwner { _addWhitelistBatch(_addresses); } // @notice adding one address to whitelist uses internal function // _addWhitelist(address _address) of Whitelist.sol to accomplish, // will revert if duplicates exists // @param address _address - solo address function addWhitelist(address _address) public onlyOwner { _addWhitelist(_address); } // @notice removing an array/list of addresses from whitelist // uses internal function _removeWhitelistBatch(address [] memory _addresses) // of Whitelist.sol to accomplish, will revert if duplicates exist in list // or array of addresses. // @param address [] memory _addresses - list/array of addresses function removeWhitelistBatch(address [] memory _addresses) public onlyOwner { _removeWhitelistBatch(_addresses); } // @notice removing one address to whitelist uses internal function // _removeWhitelist(address _address) of Whitelist.sol to accomplish, // will revert if duplicates exists // @param address _address - solo address function removeWhitelist(address _address) public onlyOwner { _removeWhitelist(_address); } /*** * ██████╗ ███████╗██╗ ██╗ * ██╔══██╗██╔════╝██║ ██║ * ██║ ██║█████╗ ██║ ██║ * ██║ ██║██╔══╝ ╚██╗ ██╔╝ * ██████╔╝███████╗ ╚████╔╝ * ╚═════╝ ╚══════╝ ╚═══╝ * This section will have all the internals set to onlyDev * also contains all overrides required for funtionality */ // @notice will add an address to PaymentSplitter by onlyDev role // @param address newAddy - address to recieve payments // @param uint newShares - number of shares they recieve function addPayee(address newAddy, uint newShares) public onlyDev { require(!lockedPayees, "Can not set, payees locked"); _addPayee(newAddy, newShares); } // @notice will lock payees on PaymentSplitter.sol function lockPayees() public onlyDev { require(!lockedPayees, "Can not set, payees locked"); lockedPayees = true; emit PayeesLocked(lockedPayees); } // @notice will set the ContractURI for OpenSea // @param string memory _contractURI - IPFS URI for contract function setContractURI(string memory _contractURI) public onlyDev { _setContractURI(_contractURI); } // @notice will set "team minting" by onlyDev role // @param uint256 _amount - set number to mint function setTeamMinting(uint256 _amount) public onlyDev { uint256 old = teamMintSize; teamMintSize = _amount; emit UpdatedTeamMintSize(old, teamMintSize); } // @notice will set mint size by onlyDev role // @param uint256 _amount - set number to mint function setMintSize(uint256 _amount) public onlyDev { uint256 old = mintSize; mintSize = _amount; emit UpdatedMintSize(old, mintSize); } // @notice this will set the Provenance Hashes // This will also set the starting order as well! // Only one shot to do this, otherwise it shows as invalid // @param string memory _images - Provenance Hash of images in sequence // @param string memory _json - Provenance Hash of metadata in sequence function setProvenance(string memory _images, string memory _json) public onlyDev { require(lockedPayees, "Can not set, payees unlocked"); require(!lockedProvenance, "Already Set!"); // This is the initial setting _setProvenanceImages(_images); _setProvenanceJSON(_json); // Now to psuedo-random the starting number // Your API should be a random before this step! mintStartID = uint(keccak256(abi.encodePacked(block.timestamp, _msgSender(), _images, _json, block.difficulty))) % mintSize; _setStartNumber(mintStartID); // @notice Locks sequence lockedProvenance = true; emit ProvenanceLocked(lockedProvenance); } // @notice this will set the reveal timestamp // This is more for your API and not on chain... // @param uint256 _time - uinx time stamp for reveal (use with API's only) function setRevealTimestamp(uint256 _time) public onlyDev { _setRevealTimestamp(_time); } // @notice function useful for accidental ETH transfers to contract (to user address) // wraps _user in payable to fix address -> address payable // @param address _user - user address to input // @param uint256 _amount - amount of ETH to transfer function sweepEthToAddress(address _user, uint256 _amount) public onlyDev { payable(_user).transfer(_amount); } /// /// Developer, these are the overrides /// // @notice solidity required override for _baseURI(), if you wish to // be able to set from API -> IPFS or vice versa using setBaseURI(string) // if cutting, destroy this getter, function setBaseURI(string), and // string memory private base above function _baseURI() internal view override returns (string memory) { return base; } // @notice solidity required override for supportsInterface(bytes4) // @param bytes4 interfaceId - bytes4 id per interface or contract // calculated by ERC165 standards automatically function supportsInterface(bytes4 interfaceId) public view override(ERC721, IERC165) returns (bool) { return ( interfaceId == type(ERC2981Collection).interfaceId || interfaceId == type(BAYC).interfaceId || interfaceId == type(ContractURI).interfaceId || interfaceId == type(IMAX721).interfaceId || interfaceId == type(IMAX721Whitelist).interfaceId || interfaceId == type(ReentrancyGuard).interfaceId || interfaceId == type(Whitelist).interfaceId || interfaceId == type(PaymentSplitter).interfaceId || interfaceId == type(DeveloperV2).interfaceId || interfaceId == type(OwnableV2).interfaceId || super.supportsInterface(interfaceId) ); } // @notice will return status of Minter function minterStatus() external view override(IMAX721) returns (bool) { return enableMinter; } // @notice will return minting fees function minterFees() external view override(IMAX721) returns (uint256) { return mintFees; } // @notice will return maximum mint capacity function minterMaximumCapacity() external view override(IMAX721) returns (uint256) { return mintSize; } // @notice will return maximum "team minting" capacity function minterMaximumTeamMints() external view override(IMAX721) returns (uint256) { return teamMintSize; } // @notice will return "team mints" left function minterTeamMintsRemaining() external view override(IMAX721) returns (uint256) { return teamMintSize - _teamMintCounter.current(); } // @notice will return "team mints" count function minterTeamMintsCount() external view override(IMAX721) returns (uint256) { return _teamMintCounter.current(); } // @notice will return current token count function totalSupply() external view override(IMAX721) returns (uint256) { return _tokenIdCounter.current(); } // @notice will return whitelist end number function whitelistEnd() external view override(IMAX721Whitelist) returns (uint256) { return whitelistEndNumber; } // @notice will return whitelist status of Minter function whitelistStatus() external view override(IMAX721Whitelist) returns (bool) { return enableWhiteList; } }
will return minting fees
function minterFees() external view override(IMAX721) returns (uint256) { return mintFees; }
909,656
./full_match/1/0x75740D9b5cA3BCCb356CA7f0D0dB71aBE427a835/sources/src/contracts/ERC20SwapToPay.sol
Authorizes the swap router to spend a new payment currency (ERC20). _erc20Address Address of an ERC20 used for payment/
function approveRouterToSpend(address _erc20Address) public { IERC20 erc20 = IERC20(_erc20Address); uint256 max = 2**256 - 1; erc20.safeApprove(address(swapRouter), max); } @param _path, path of ERC20 tokens to swap from requestedToken to spentToken. The first address of the path should be the payment currency. The last element should be the request currency.
8,332,900
./full_match/80001/0x0aCca12ade732F5Dc6afbad42ad1Eb5F0163e663/sources/contracts/dev/functions/AuthorizedOriginReceiverUpgradeable.sol
Remove the permission to request for the given wallet(s). senders The addresses of the wallet addresses to revoke access/ Remove from s_authorizedSendersList Copy last element and overwrite senders[i] to be deleted with it
function removeAuthorizedSenders(address[] calldata senders) external validateAuthorizedSenderSetter { if (senders.length == 0) { revert EmptySendersList(); } for (uint256 i = 0; i < senders.length; i++) { bool success = s_authorizedSenders.remove(senders[i]); if (success) { for (uint256 j = 0; j < s_authorizedSendersList.length; j++) { if (s_authorizedSendersList[j] == senders[i]) { address last = s_authorizedSendersList[s_authorizedSendersList.length - 1]; s_authorizedSendersList[i] = last; s_authorizedSendersList.pop(); } } } } emit AuthorizedSendersChanged(senders, msg.sender); }
5,561,719
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../libs/AddressSet.sol"; import "./ComplexPoolLib.sol"; import "../interfaces/INFTGemMultiToken.sol"; import "../interfaces/INFTComplexGemPoolData.sol"; import "../interfaces/INFTGemPoolData.sol"; contract NFTComplexGemPoolData is INFTComplexGemPoolData { using AddressSet for AddressSet.Set; using ComplexPoolLib for ComplexPoolLib.ComplexPoolData; ComplexPoolLib.ComplexPoolData internal poolData; /** * @dev Throws if called by any account not in authorized list */ modifier onlyController() { require( poolData.controllers[msg.sender] == true || msg.sender == poolData.governor || address(this) == msg.sender, "Controllable: caller is not a controller" ); _; } constructor() { poolData.controllers[msg.sender] = true; poolData.controllers[tx.origin] = true; } /** * @dev all the tokenhashes (both claim and gem) for this pool */ function tokenHashes() external view override returns (uint256[] memory) { return poolData.tokenHashes; } /** * @dev set all the token hashes for this pool */ function setTokenHashes(uint256[] memory _tokenHashes) external override onlyController { poolData.tokenHashes = _tokenHashes; } /** * @dev The symbol for this pool / NFT */ function symbol() external view override returns (string memory) { return poolData.symbol; } /** * @dev The ether price for this pool / NFT */ function ethPrice() external view override returns (uint256) { return poolData.ethPrice; } /** * @dev max allowable quantity per claim */ function maxQuantityPerClaim() external view override returns (uint256) { return poolData.maxQuantityPerClaim; } /** * @dev max claims that can be made on this NFT on any given account */ function maxClaimsPerAccount() external view override returns (uint256) { return poolData.maxClaimsPerAccount; } /** * @dev update max quantity per claim */ function setMaxQuantityPerClaim(uint256 _maxQuantityPerClaim) external override onlyController { poolData.maxQuantityPerClaim = _maxQuantityPerClaim; } /** * @dev update max claims that can be made on this NFT */ function setMaxClaimsPerAccount(uint256 _maxClaimsPerAccount) external override onlyController { poolData.maxClaimsPerAccount = _maxClaimsPerAccount; } /** * @dev returns if pool allows purchase */ function allowPurchase() external view override returns (bool) { return poolData.allowPurchase; } /** * @dev set whether pool allows purchase */ function setAllowPurchase(bool _allowPurchase) external override onlyController { poolData.allowPurchase = _allowPurchase; } /** * @dev is pool enabled (taking claim requests) */ function enabled() external view override returns (bool) { return poolData.enabled; } /** * @dev set the enabled status of this pool */ function setEnabled(bool _enabled) external override onlyController { poolData.enabled = _enabled; } /** * @dev return the appreciation curve of this pool. */ function priceIncrementType() external view override returns (PriceIncrementType) { return poolData.priceIncrementType; } /** * @dev set the appreciation curve of this pool. */ function setPriceIncrementType(PriceIncrementType _incrementType) external override onlyController { poolData.priceIncrementType = _incrementType; } /** * @dev return the number of claims made thus far */ function claimedCount() external view override returns (uint256) { return poolData.nextClaimIdVal; } /** * @dev return the number of gems made thus far */ function mintedCount() external view override returns (uint256) { return poolData.nextGemIdVal; } /** * @dev the total amopunt of staked eth in this pool */ function totalStakedEth() external view override returns (uint256) { return poolData.totalStakedEth; } /** * @dev get token type of hash - 1 is for claim, 2 is for gem */ function tokenType(uint256 _tokenHash) external view override returns (INFTGemMultiToken.TokenType) { return poolData.tokenTypes[_tokenHash]; } /** * @dev get the claim hash of the gem */ function gemClaimHash(uint256 _claimHash) external view override returns (uint256) { return poolData.gemClaims[_claimHash]; } /** * @dev get token id (serial #) of the given token hash. 0 if not a token, 1 if claim, 2 if gem */ function tokenId(uint256 _tokenHash) external view override returns (uint256) { return poolData.tokenIds[_tokenHash]; } /** * @dev returns a count of all token hashes */ function allTokenHashesLength() external view override returns (uint256) { return poolData.tokenHashes.length; } /** * @dev get the token hash at index */ function allTokenHashes(uint256 ndx) external view override returns (uint256) { return poolData.tokenHashes[ndx]; } /** * @dev return the next claim hash */ function nextClaimHash() external view override returns (uint256) { return poolData.nextClaimHash(); } /** * @dev return the next gem hash */ function nextGemHash() external view override returns (uint256) { return poolData.nextGemHash(); } /** * @dev return the next claim id */ function nextClaimId() external view override returns (uint256) { return poolData.nextClaimIdVal; } /** * @dev return the next gem id */ function nextGemId() external view override returns (uint256) { return poolData.nextGemIdVal; } /** * @dev return the count of allowed tokens */ function allowedTokensLength() external view override returns (uint256) { return poolData.allowedTokens.count(); } /** * @dev the allowed token address at index */ function allowedTokens(uint256 _index) external view override returns (address) { return poolData.allowedTokens.keyAtIndex(_index); } /** * @dev add an allowed token to the pool */ function addAllowedToken(address _tokenAddress) external override onlyController { poolData.allowedTokens.insert(_tokenAddress); } /** * @dev add an allowed token to the pool */ function removeAllowedToken(address _tokenAddress) external override onlyController { poolData.allowedTokens.remove(_tokenAddress); } /** * @dev is the token in the allowed tokens list */ function isTokenAllowed(address _tokenAddress) external view override returns (bool) { return poolData.allowedTokens.exists(_tokenAddress); } /** * @dev the claim amount for the given claim id */ function claimAmount(uint256 _claimHash) external view override returns (uint256) { return poolData.claimAmount(_claimHash); } /** * @dev the claim quantity (count of gems staked) for the given claim id */ function claimQuantity(uint256 _claimHash) external view override returns (uint256) { return poolData.claimQuantity(_claimHash); } /** * @dev the lock time for this claim. once past lock time a gema is minted */ function claimUnlockTime(uint256 _claimHash) external view override returns (uint256) { return poolData.claimUnlockTime(_claimHash); } /** * @dev claim token amount if paid using erc20 */ function claimTokenAmount(uint256 _claimHash) external view override returns (uint256) { return poolData.claimTokenAmount(_claimHash); } /** * @dev the staked token if staking with erc20 */ function stakedToken(uint256 _claimHash) external view override returns (address) { return poolData.stakedToken(_claimHash); } /** * @dev set market visibility */ function setVisible(bool _visible) external override onlyController { poolData.visible = _visible; } /** * @dev set market visibility */ function visible() external view override returns (bool) { return poolData.visible; } /** * @dev set category category */ function setCategory(uint256 _category) external override onlyController { poolData.category = _category; } /** * @dev get market category */ function category() external view override returns (uint256) { return poolData.category; } /** * @dev set description */ function setDescription(string memory desc) external override onlyController { poolData.description = desc; } /** * @dev get description */ function description() external view override returns (string memory) { return poolData.description; } /** * @dev set validate erc20 token against AMM */ function setValidateErc20(bool) external override onlyController { poolData.validateerc20 = true; } /** * @dev get validate erc20 token against AMM */ function validateErc20() external view override returns (bool) { return poolData.validateerc20; } /** * @dev add an input requirement for this token */ function addInputRequirement( address _tokenAddress, address _poolAddress, INFTComplexGemPool.RequirementType _inputType, uint256 _tokenId, uint256 _minAmount, bool _takeCustody, bool _burn, bool _exactAmount ) external override { poolData.addInputRequirement( _tokenAddress, _poolAddress, _inputType, _tokenId, _minAmount, _takeCustody, _burn, _exactAmount ); } /** * @dev add an input requirement for this token */ function updateInputRequirement( uint256 _index, address _tokenAddress, address _poolAddress, INFTComplexGemPool.RequirementType _inputType, uint256 _tokenId, uint256 _minAmount, bool _takeCustody, bool _burn, bool _exactAmount ) external override { poolData.updateInputRequirement( _index, _tokenAddress, _poolAddress, _inputType, _tokenId, _minAmount, _takeCustody, _burn, _exactAmount ); } /** * @dev all Input Requirements Length */ function allInputRequirementsLength() external view override returns (uint256) { return poolData.allInputRequirementsLength(); } /** * @dev all Input Requirements at element */ function allInputRequirements(uint256 _index) external view override returns ( address, address, INFTComplexGemPool.RequirementType, uint256, uint256, bool, bool, bool ) { return poolData.allInputRequirements(_index); } /** * @dev add an allowed token source */ function addAllowedTokenSource(address _allowedToken) external override { if (!poolData.allowedTokenSources.exists(_allowedToken)) { poolData.allowedTokenSources.insert(_allowedToken); } } /** * @dev remove an allowed token source */ function removeAllowedTokenSource(address _allowedToken) external override { if (poolData.allowedTokenSources.exists(_allowedToken)) { poolData.allowedTokenSources.remove(_allowedToken); } } /** * @dev returns an array of all allowed token sources */ function allowedTokenSources() external view override returns (address[] memory) { return poolData.allowedTokenSources.keyList; } /** * @dev delegate proxy method for multitoken allow */ function proxies(address) external view returns (address) { return address(this); } /** * @dev these settings defines how the pool behaves */ function settings() external view override returns ( string memory, string memory, string memory, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256 ) { return ( poolData.symbol, poolData.name, poolData.description, poolData.category, poolData.ethPrice, poolData.minTime, poolData.maxTime, poolData.diffstep, poolData.maxClaims, poolData.maxQuantityPerClaim, poolData.maxClaimsPerAccount ); } /** * @dev these stats reflect the current pool state */ function stats() external view override returns ( bool, uint256, uint256, uint256, uint256, uint256, uint256, uint256 ) { return ( poolData.visible, poolData.nextClaimIdVal, poolData.nextGemIdVal, poolData.totalStakedEth, poolData.nextClaimHash(), poolData.nextGemHash(), poolData.nextClaimIdVal, poolData.nextGemIdVal ); } /** * @dev return the claim details for the given claim hash */ function claim(uint256 claimHash) external view override returns ( uint256, uint256, uint256, uint256, address, uint256 ) { return ( poolData.claimAmount(claimHash), poolData.claimQuantity(claimHash), poolData.claimUnlockTime(claimHash), poolData.claimTokenAmount(claimHash), poolData.stakedToken(claimHash), poolData.nextClaimIdVal ); } /** * @dev return the token data for the given hash */ function token(uint256 _tokenHash) external view override returns ( INFTGemMultiToken.TokenType, uint256, address ) { return ( poolData.tokenTypes[_tokenHash], poolData.tokenIds[_tokenHash], poolData.tokenSources[_tokenHash] ); } /** * @dev import the legacy gem */ function importLegacyGem( address _poolAddress, address _legacyToken, uint256 _tokenHash, address _recipient, bool _burnOld ) external override { // this method is callable by anyone - this is used to import historical // gems into the new contracts. A gem can only be imported in once // per source require(_tokenHash > 0, "INVALID_TOKENHASH"); require(_poolAddress > address(0), "INVALID_POOL"); require(_legacyToken > address(0), "INVALID_TOKEN"); require(_recipient > address(0), "INVALID_RECIPIENT"); require( poolData.allowedTokenSources.exists(_legacyToken) == true, "INVALID_TOKENSOURCE" ); // get legacy token quantity uint256 quantity = IERC1155(_legacyToken).balanceOf( _recipient, _tokenHash ); // require some amount to import require(quantity > 0, "NOTHING_TO_IMPORT"); // if we are to burn old tokens do it now if (_burnOld == true) { INFTGemMultiToken(_legacyToken).burn( _recipient, _tokenHash, quantity ); // and exit if we have already imported them. this logic // lets us import without burning the old tokens first, // and then burn them afterwards if ( poolData.importedLegacyToken[_tokenHash][_recipient] >= quantity ) { return; } } // require that the token is not already imported require( poolData.importedLegacyToken[_tokenHash][_recipient] < quantity, "ALREADY_IMPORTED" ); // rebuild the poolhash to make sure its correct bytes32 importedSymHash = keccak256( abi.encodePacked(INFTGemPoolData(_poolAddress).symbol()) ); bytes32 poolSymHash = keccak256(abi.encodePacked(poolData.symbol)); require(importedSymHash == poolSymHash, "INVALID_POOLHASH"); // get the token type from the legacy token uint256 importTokenId = INFTGemPoolData(_poolAddress).tokenId( _tokenHash ); // store import data poolData.tokenTypes[_tokenHash] = INFTGemMultiToken.TokenType.GEM; poolData.tokenIds[_tokenHash] = importTokenId; poolData.tokenSources[_tokenHash] = _legacyToken; poolData.importedLegacyToken[_tokenHash][_recipient] = quantity; // mint the token hash on the new token INFTGemMultiToken(poolData.multitoken).mint( _recipient, _tokenHash, quantity ); // set the token data INFTGemMultiToken(poolData.multitoken).setTokenData( _tokenHash, INFTGemMultiToken.TokenType.GEM, address(this) ); emit NFTGemImported( msg.sender, address(this), _poolAddress, _legacyToken, _tokenHash, quantity ); } /** * @dev returns if legacy gem with given hash is imported */ function isLegacyGemImported(address _account, uint256 _tokenhash) external view override returns (bool) { return poolData.importedLegacyToken[_tokenhash][_account] > 0; } /** * @dev set the next claim and gem ids */ function setNextIds(uint256 _nextClaimId, uint256 _nextGemId) external override onlyController { poolData.nextClaimIdVal = _nextClaimId; poolData.nextGemIdVal = _nextGemId; } }
returns an array of all allowed token sources/
function allowedTokenSources() external view override returns (address[] memory) { return poolData.allowedTokenSources.keyList; }
1,040,403
./full_match/137/0xCB31Ea2A9233624f249248377c46C3095514B331/sources/project:/contracts/TokenizedBonds.sol
Set URI per token. ids[] Array of token ids cids[] Array of token content identifiers (CIDs) Requirements: - must be called by the contract owner. - `ids` and `cids` must have the same length./
function setURIs( uint256[] calldata ids, string[] calldata cids ) external virtual onlyOwner { uint256 count = ids.length; require( count == cids.length, "TokenizedBonds: ids and cids length mismatch" ); for (uint256 i = 0; i < count; i++) { _setURI(ids[i], cids[i]); } }
4,731,797
// Contracts/SupplyChain.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../emeraldaccesscontrol/MinerRole.sol"; import "../emeraldaccesscontrol/LaboratoryRole.sol"; import "../emeraldaccesscontrol/CustodianRole.sol"; import "../emeraldaccesscontrol/ManufacturerRole.sol"; import "../emeraldaccesscontrol/CustomerRole.sol"; import "./EmeraldStates.sol"; import "./Emerald.sol"; // Define a contract 'Supplychain' contract SupplyChain is Ownable, AccessControl, MinerRole, LaboratoryRole, CustodianRole, ManufacturerRole, CustomerRole{ // Define a variable called 'upc' for Universal Product Code (UPC) uint upc; // Define a variable called 'sku' for Stock Keeping Unit (SKU) uint sku; // Define a public mapping 'emeralds' that maps the UPC to an Emerald. mapping (uint => Emerald) emeralds; // Define a public mapping 'emeraldHistory' that maps the UPC to an array of TxHash, // that track its journey through the supply chain -- to be sent from DApp. mapping (uint => string[]) emeraldsHistory; EmeraldStates.State constant defaultState = EmeraldStates.State.Mined; // Define 17 events with the same 17 state values and accept 'upc' as input argument event Mined(uint upc); event Scaled(uint upc); event PackedForLab(uint upc); event ShipedToLab(uint upc); event LabReceived(uint upc); event Certified(uint upc); event ShippedToStore(uint upc); event StorageReceived(uint upc); event Stored(uint upc); event ForSale(uint upc); event Sold(uint upc); event ShipToManufacture(uint upc); event ManufacturerReceived(uint upc); event Manufactured(uint upc); event PackedForSale(uint upc); event Published(uint upc); event Buyed(uint upc); event ShippedToCustomer(uint upc); event Delivered(uint upc); // Define a modifer that verifies the Caller modifier verifyCaller (address _address) { require(msg.sender == _address); _; } // Define a modifier that checks if the paid amount is sufficient to cover the price modifier paidEnough(uint _price) { require(msg.value >= _price,"Not enought paid amount"); _; } // Define a modifier that checks the price and refunds the remaining balance modifier checkValue(uint _upc) { _; uint _price = emeralds[_upc].GetMarketPrice(); uint amountToReturn = msg.value - _price; msg.sender.transfer(amountToReturn); } // Checks if a emerald is Mined modifier mined(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Mined); _; } //Checks if an emerald was escaled modifier scaled(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Scaled); _; } //Checks if an emerald is packed modifier packedForLab(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.PackedForLab); _; } // Checks if an emerald was shipped to the laboratory modifier shipedToLab(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ShipedToLab); _; } // Checks if an emerald was received by the Laboratory modifier labReceived(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.LabReceived); _; } // Checks if an emerald was certified by the laboratory modifier certified(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Certified); _; } // Checks if an emerald was shipped to the storage y the laboratory modifier shippedToStore(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ShippedToStore); _; } // Checks if an emerald was received by the custodian service modifier storageReceived(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.StorageReceived); _; } // Checks if an emerald was stored by the custodian modifier stored(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Stored); _; } // Checks if a raw emerald is available for sale modifier forSale(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ForSale); _; } // Checks if a raw emerald was sold modifier sold(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Sold); _; } // Checks if a sold emerald was shipped to the buyer modifier shiptoManufacture(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ShipToManufacture); _; } // Checks if an emerald was received by the manufacturer modifier manufacturerReceived(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ManufacturerReceived); _; } // Checks if an emerald was proccesed by the manufacturer modifier manufactured(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Manufactured); _; } // Checks if a cut emerald was packed modifier packedForSale(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.PackedForSale); _; } // Checks if an proccesed emerald is ready for sale modifier published(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Published); _; } // Checks if a proccesed emerald was purshased modifier buyed(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Buyed); _; } // Checks if a cut emerald was shipped to the buyer modifier shippedToCustomer(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ShippedToCustomer); _; } // Checks if a cut emerald was received by the customer modifier delivered(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Delivered); _; } // In the constructor set 'owner' to the address that instantiated the contract // and set 'sku' to 1 // and set 'upc' to 1 constructor() { //owner = msg.sender; sku = 1; upc = 1; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } // Define a function 'kill' if required function kill() public onlyOwner{ selfdestruct(msg.sender); } // Define a function 'extractItem' that allows a Miner to mark an emerald as 'Mined' function extractEmerald( uint _sku, uint _upc, address payable _originMinerID, string memory _originMineName, string memory _originMineInformation, string memory _originMineLatitude, string memory _originMineLongitude ) public onlyMiner { //add emerald to emeralds list in the contract Emerald emerald = new Emerald(); emerald.SetExtractionInfo( _sku, _upc, _originMinerID, _originMineName, _originMineInformation, _originMineLatitude, _originMineLongitude ); emerald.SetEmeraldState(EmeraldStates.State.Mined); emeralds[_upc] = emerald; //Increment sku sku = sku + 1; // Emit the appropriate event emit Mined(_upc); } // Define a function 'scaleItem' that allows Miner to mark an item as 'Scaled' function scaleEmerald( uint _upc, string memory _scaleInfo ) public // Call modifier to check if upc has passed previous supply chain stage mined(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetOwnerID()) onlyMiner { // Update the appropriate fields emeralds[_upc].SetScaleInfo( _scaleInfo ); emeralds[_upc].SetEmeraldState(EmeraldStates.State.Scaled); // Emit the appropriate event emit Scaled(_upc); } //Define a function 'packScaledItem' that allows a Miner to mark an item 'Packed' function packScaledEmerald(uint _upc, address _laboratoryID, address _custodianID) public // Call modifier to check if upc has passed previous supply chain stage scaled(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetOwnerID()) onlyMiner { // Update the appropriate fields emeralds[_upc].AuthorizeLab(_laboratoryID); emeralds[_upc].AuthorizeCustodian(_custodianID); // Update Emerald state emeralds[_upc].SetEmeraldState(EmeraldStates.State.PackedForLab); // Emit the appropriate event emit PackedForLab(_upc); } // Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' function shipToLaboratory(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage packedForLab(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetOwnerID()) onlyMiner { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.ShipedToLab); // Emit the appropriate event emit ShipedToLab(_upc); } // Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' function laboratoryReceived(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage shipedToLab(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetLaboratoryID()) onlyLaboratory { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.LabReceived); // Emit the appropriate event emit LabReceived(_upc); } // Define a function 'scaleItem' that allows a Miner to mark an item 'Processed' function certifyEmerald( uint _upc, string memory _certifiedProperties ) public // Call modifier to check if upc has passed previous supply chain stage labReceived(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetLaboratoryID()) onlyLaboratory { // Update the appropriate fields emeralds[_upc].SetCertifiedInfo(_certifiedProperties); emeralds[_upc].SetEmeraldState(EmeraldStates.State.Certified); // Emit the appropriate event emit Certified(_upc); } // Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' function shipToSecureStore(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage certified(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetLaboratoryID()) onlyLaboratory { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.ShippedToStore); // Emit the appropriate event emit ShippedToStore(_upc); } // Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' function SecureStorageReceived(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage shippedToStore(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetCustodianID()) onlyCustodian { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.StorageReceived); // Emit the appropriate event emit StorageReceived(_upc); } // Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' function StoreEmerald(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage storageReceived(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetCustodianID()) onlyCustodian { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.Stored); // Emit the appropriate event emit Stored(_upc); } // Define a function 'registerForSale' that allows a Miner to mark an item 'ForSale' function registerForSale(uint _upc, uint _marketPrice) public // Call modifier to check if upc has passed previous supply chain stage stored(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetOwnerID()) onlyMiner { //Setup market price emeralds[_upc].SetMarketPrice(_marketPrice); // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.ForSale); // Emit the appropriate event emit ForSale(_upc); } // Define a function 'buyItem' that allows the Manufacturer to mark an item 'Sold' function buyFromMiner(uint _upc) public payable // Call modifier to check if upc has passed previous supply chain stage forSale(_upc) // Call modifer to check if buyer has paid enough paidEnough(emeralds[_upc].GetMarketPrice()) // Call modifer to send any excess ether back to buyer checkValue(_upc) onlyManufacturer { // Transfer money to Miner (bool success, ) = emeralds[_upc].getOriginMinerID().call{value: emeralds[_upc].GetMarketPrice()}(""); require(success, "Transfer failed"); // Tranfer emerald ownership emeralds[_upc].SetOwnerID(msg.sender); emeralds[_upc].SetManufacturerID(msg.sender); // Update emerald state emeralds[_upc].SetEmeraldState(EmeraldStates.State.Sold); // Emit the appropriate event emit Sold(_upc); } // Define a function 'shipItem' that allows laboratory confirm that the emerald was shipped function shipToManufacturer(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage sold(_upc) // Call modifier to verify caller of this function onlyCustodian { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.ShipToManufacture); // Emit the appropriate event emit ShipToManufacture(_upc); } // Define a function 'receiveFromStorage' that allows the manufacturer mark an item 'ManufacturerReceived' function receiveFromStorage(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage shiptoManufacture(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyManufacturer { // Update the appropriate fields - ownerID, retailerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.ManufacturerReceived); // Emit the appropriate event emit ManufacturerReceived(_upc); } // Define a function 'manufactureEmerald' that allows the manufacturer to mark an item 'Manufactured' function manufactureEmerald( uint _upc, string memory _manofactureInfo ) public // Call modifier to check if upc has passed previous supply chain stage manufacturerReceived(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyManufacturer { // Update the appropriate fields emeralds[_upc].SetManufacturedInfo(_manofactureInfo); // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.Manufactured); // Emit the appropriate event emit Manufactured(_upc); } // Define a function 'packCutEmerald' that allows the manufacturer to mark an emerald 'PackedForSale' function packCutEmerald(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage manufactured(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyManufacturer { // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.PackedForSale); // Emit the appropriate event emit PackedForSale(upc); } // Define a function 'publishEmerald' that allows the manufacturer to mark an item 'Published' function publishEmerald(uint _upc, uint _marketPrice) public // Call modifier to check if upc has passed previous supply chain stage packedForSale(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyManufacturer { //Setup market price emeralds[_upc].SetMarketPrice(_marketPrice); // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.Published); // Emit the appropriate event emit Published(_upc); } // Define a function 'buyFromManufacturer' that allows the manufacturer to mark an item 'Buyed' function buyFromManufacturer(uint _upc) public payable // Call modifier to check if upc has passed previous supply chain stage published(_upc) // Call modifer to check if buyer has paid enough paidEnough(emeralds[_upc].GetMarketPrice()) // Call modifer to send any excess ether back to buyer checkValue(_upc) onlyCustomer { // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.Buyed); // Transfer money to Manufacturer (bool success, ) = emeralds[_upc].getManufacturerID().call{value: emeralds[_upc].GetMarketPrice()}(""); require(success, "Transfer failed"); // Set the customerID value emeralds[_upc].SetCustomerID(msg.sender); // Transfer ownership emeralds[_upc].SetOwnerID(msg.sender); // Emit the appropriate event emit Buyed(_upc); } // Define a function 'shipEmeraldToCustomer' that allows the consumer to mark an item 'ShippedToCustomer' function shipEmeraldToCustomer(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage buyed(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyManufacturer { // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.ShippedToCustomer); // Emit the appropriate event emit ShippedToCustomer(_upc); } // Define a function 'deliverToCustomer' that allows the consumer to mark an item 'Delivered' function deliverToCustomer(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage shippedToCustomer(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyCustomer { // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.Delivered); // Emit the appropriate event emit Delivered(_upc); } // Define a function 'fetchItemBufferOne' that fetches the data function fetchItemBufferOne(uint _upc) public view returns (bytes memory) { return (emeralds[_upc].GetBasicInfo()); } // Define a function 'fetchItemBufferTwo' that fetches the data function fetchItemBufferTwo(uint _upc) public view returns (bytes memory) { return (emeralds[_upc].GetDetailedInfo()); } }
Define a function 'buyFromManufacturer' that allows the manufacturer to mark an item 'Buyed' Call modifier to check if upc has passed previous supply chain stage Call modifer to check if buyer has paid enough Call modifer to send any excess ether back to buyer Update the appropriate fields - ownerID, consumerID, itemState Transfer money to Manufacturer Set the customerID value Transfer ownership Emit the appropriate event
function buyFromManufacturer(uint _upc) public payable published(_upc) paidEnough(emeralds[_upc].GetMarketPrice()) checkValue(_upc) onlyCustomer { emeralds[_upc].SetEmeraldState(EmeraldStates.State.Buyed); require(success, "Transfer failed"); emeralds[_upc].SetCustomerID(msg.sender); emeralds[_upc].SetOwnerID(msg.sender); emit Buyed(_upc); }
5,454,288
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import { IPool } from "./balancer/IPool.sol"; import { PriceLibrary as Prices } from "./lib/PriceLibrary.sol"; import "./lib/FixedPoint.sol"; import "./lib/Babylonian.sol"; import { MCapSqrtLibrary as MCapSqrt } from "./lib/MCapSqrtLibrary.sol"; import { PoolFactory } from "./PoolFactory.sol"; import { PoolInitializer } from "./PoolInitializer.sol"; import { UnboundTokenSeller } from "./UnboundTokenSeller.sol"; import { DelegateCallProxyManager } from "./proxies/DelegateCallProxyManager.sol"; import { SaltyLib as Salty } from "./proxies/SaltyLib.sol"; import { MarketCapSortedTokenCategories, UniSwapV2PriceOracle } from "./MarketCapSortedTokenCategories.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title MarketCapSqrtController * @author d1ll0n * @dev This contract implements the market cap square root index management strategy. * * Index pools have a defined size which is used to select the top tokens from the pool's * category. * * REBALANCING * =============== * Every 2 weeks, pools are either re-weighed or re-indexed. * They are re-indexed once for every three re-weighs. * * Re-indexing involves selecting the top tokens from the pool's category and weighing them * by the square root of their market caps. * Re-weighing involves weighing the tokens which are already indexed by the pool by the * square root of their market caps. * When a pool is re-weighed, only the tokens with a desired weight above 0 are included. * =============== */ contract MarketCapSqrtController is MarketCapSortedTokenCategories { using FixedPoint for FixedPoint.uq112x112; using FixedPoint for FixedPoint.uq144x112; using Babylonian for uint144; using SafeMath for uint256; using Prices for Prices.TwoWayAveragePrice; /* --- Constants --- */ // Minimum number of tokens in an index. uint256 internal constant MIN_INDEX_SIZE = 2; // Maximum number of tokens in an index. uint256 internal constant MAX_INDEX_SIZE = 8; // Identifier for the pool initializer implementation on the proxy manager. bytes32 internal constant INITIALIZER_IMPLEMENTATION_ID = keccak256("PoolInitializer.sol"); // Identifier for the unbound token seller implementation on the proxy manager. bytes32 internal constant SELLER_IMPLEMENTATION_ID = keccak256("UnboundTokenSeller.sol"); // Identifier for the index pool implementation on the proxy manager. bytes32 internal constant POOL_IMPLEMENTATION_ID = keccak256("IPool.sol"); // Default total weight for a pool. uint256 internal constant WEIGHT_MULTIPLIER = 25e18; // Time between reweigh/reindex calls. uint256 internal constant POOL_REWEIGH_DELAY = 2 weeks; // The number of reweighs which occur before a pool is re-indexed. uint256 internal constant REWEIGHS_BEFORE_REINDEX = 3; // Pool factory contract PoolFactory internal immutable _factory; // Proxy manager & factory DelegateCallProxyManager internal immutable _proxyManager; /* --- Events --- */ /** @dev Emitted when a pool is initialized and made public. */ event PoolInitialized( address pool, address unboundTokenSeller, uint256 categoryID, uint256 indexSize ); /** @dev Emitted when a pool and its initializer are deployed. */ event NewPoolInitializer( address pool, address initializer, uint256 categoryID, uint256 indexSize ); /** @dev Emitted when a pool using the default implementation is deployed. */ event NewDefaultPool( address pool, address controller ); /** @dev Emitted when a pool using a non-default implementation is deployed. */ event NewNonDefaultPool( address pool, address controller, bytes32 implementationID ); /* --- Structs --- */ struct IndexPoolMeta { uint16 categoryID; uint8 indexSize; bool initialized; } /** * @dev Data structure with the number of times a pool has been * either reweighed or re-indexed, as well as the timestamp of * the last such action. * * If `++index % REWEIGHS_BEFORE_REINDEX + 1` is 0, the pool will * re-index, otherwise it will reweigh. * * @param index Number of times the pool has either re-weighed or * re-indexed. * @param timestamp Timestamp of last pool re-weigh or re-index. */ struct PoolUpdateRecord { uint128 index; uint128 timestamp; } /* --- Storage --- */ // Default slippage rate for token seller contracts. uint8 public defaultSellerPremium = 2; // Metadata about index pools mapping(address => IndexPoolMeta) internal _poolMeta; // Records of pool update statuses. mapping(address => PoolUpdateRecord) internal _poolUpdateRecords; /* --- Constructor --- */ /** * @dev Deploy the controller and configure the addresses * of the related contracts. */ constructor( UniSwapV2PriceOracle oracle, address owner, PoolFactory factory, DelegateCallProxyManager proxyManager ) public MarketCapSortedTokenCategories(oracle, owner) { _factory = factory; _proxyManager = proxyManager; } /* --- Pool Deployment --- */ /** * @dev Deploys an index pool and a pool initializer. * The initializer contract is a pool with specific token * balance targets which gives pool tokens in the finished * pool to users who provide the underlying tokens needed * to initialize it. */ function prepareIndexPool( uint256 categoryID, uint256 indexSize, uint256 initialWethValue, string calldata name, string calldata symbol ) external _owner_ returns (address poolAddress, address initializerAddress) { require(indexSize >= MIN_INDEX_SIZE, "ERR_MIN_INDEX_SIZE"); require(indexSize <= MAX_INDEX_SIZE, "ERR_MAX_INDEX_SIZE"); require(initialWethValue < uint144(-1), "ERR_MAX_UINT144"); poolAddress = _factory.deployIndexPool( keccak256(abi.encodePacked(categoryID, indexSize)), name, symbol ); _poolMeta[poolAddress] = IndexPoolMeta({ categoryID: uint8(categoryID), indexSize: uint8(indexSize), initialized: false }); initializerAddress = _proxyManager.deployProxyManyToOne( INITIALIZER_IMPLEMENTATION_ID, keccak256(abi.encodePacked(poolAddress)) ); PoolInitializer initializer = PoolInitializer(initializerAddress); // Get the initial tokens and balances for the pool. ( address[] memory tokens, uint256[] memory balances ) = getInitialTokensAndBalances(categoryID, indexSize, uint144(initialWethValue)); initializer.initialize(poolAddress, tokens, balances); emit NewPoolInitializer( poolAddress, initializerAddress, categoryID, indexSize ); } /** * @dev Initializes a pool which has been deployed but not initialized * and transfers the underlying tokens from the initialization pool to * the actual pool. */ function finishPreparedIndexPool( address poolAddress, address[] calldata tokens, uint256[] calldata balances ) external { require( msg.sender == computeInitializerAddress(poolAddress), "ERR_NOT_PRE_DEPLOY_POOL" ); uint256 len = tokens.length; require(balances.length == len, "ERR_ARR_LEN"); IndexPoolMeta memory meta = _poolMeta[poolAddress]; require(!meta.initialized, "ERR_INITIALIZED"); uint96[] memory denormalizedWeights = new uint96[](len); uint256 valueSum; uint144[] memory ethValues = oracle.computeAverageAmountsOut( tokens, balances ); for (uint256 i = 0; i < len; i++) { valueSum = valueSum.add(ethValues[i]); } for (uint256 i = 0; i < len; i++) { denormalizedWeights[i] = _denormalizeFractionalWeight( FixedPoint.fraction(uint112(ethValues[i]), uint112(valueSum)) ); } address sellerAddress = _proxyManager.deployProxyManyToOne( SELLER_IMPLEMENTATION_ID, keccak256(abi.encodePacked(poolAddress)) ); IPool(poolAddress).initialize( tokens, balances, denormalizedWeights, msg.sender, sellerAddress ); _poolMeta[poolAddress].initialized = true; emit PoolInitialized( poolAddress, sellerAddress, meta.categoryID, meta.indexSize ); UnboundTokenSeller(sellerAddress).initialize( IPool(poolAddress), defaultSellerPremium ); } /* --- Pool Management --- */ /** * @dev Sets the default premium rate for token seller contracts. */ function setDefaultSellerPremium( uint8 _defaultSellerPremium ) external _owner_ { require( _defaultSellerPremium > 0 && _defaultSellerPremium < 20, "ERR_PREMIUM" ); defaultSellerPremium = _defaultSellerPremium; } /** * @dev Update the premium rate on `sellerAddress` with the current * default rate. */ function updateSellerPremiumToDefault( address sellerAddress ) external { UnboundTokenSeller(sellerAddress).setPremiumPercent(defaultSellerPremium); } /** * @dev Update the premium rate on each unbound token seller in * `sellerAddresses` with the current default rate. */ function updateSellerPremiumToDefault( address[] calldata sellerAddresses ) external { for (uint256 i = 0; i < sellerAddresses.length; i++) { UnboundTokenSeller( sellerAddresses[i] ).setPremiumPercent(defaultSellerPremium); } } /** * @dev Sets the maximum number of pool tokens that can be minted * for a particular pool. * * This value will be used in the alpha to limit the maximum damage * that can be caused by a catastrophic error. It can be gradually * increased as the pool continues to not be exploited. * * If it is set to 0, the limit will be removed. * * @param poolAddress Address of the pool to set the limit on. * @param maxPoolTokens Maximum LP tokens the pool can mint. */ function setMaxPoolTokens( address poolAddress, uint256 maxPoolTokens ) external _owner_ { IPool(poolAddress).setMaxPoolTokens(maxPoolTokens); } /** * @dev Sets the swap fee on an index pool. */ function setSwapFee(address poolAddress, uint256 swapFee) external _owner_ { require(_havePool(poolAddress), "ERR_POOL_NOT_FOUND"); IPool(poolAddress).setSwapFee(swapFee); } /** * @dev Updates the minimum balance of an uninitialized token, which is * useful when the token's price on the pool is too low relative to * external prices for people to trade it in. */ function updateMinimumBalance(IPool pool, address tokenAddress) external { require(_havePool(address(pool)), "ERR_POOL_NOT_FOUND"); IPool.Record memory record = pool.getTokenRecord(tokenAddress); require(!record.ready, "ERR_TOKEN_READY"); uint256 poolValue = _estimatePoolValue(pool); Prices.TwoWayAveragePrice memory price = oracle.computeTwoWayAveragePrice(tokenAddress); uint256 minimumBalance = price.computeAverageTokensForEth(poolValue) / 100; pool.setMinimumBalance(tokenAddress, minimumBalance); } /* --- Pool Rebalance Actions --- */ /** * @dev Re-indexes a pool by setting the underlying assets to the top * tokens in its category by market cap. */ function reindexPool(address poolAddress) external { IndexPoolMeta memory meta = _poolMeta[poolAddress]; require(meta.initialized, "ERR_POOL_NOT_FOUND"); PoolUpdateRecord memory record = _poolUpdateRecords[poolAddress]; require( now - record.timestamp >= POOL_REWEIGH_DELAY, "ERR_POOL_REWEIGH_DELAY" ); require( (++record.index % (REWEIGHS_BEFORE_REINDEX + 1)) == 0, "ERR_REWEIGH_INDEX" ); uint256 size = meta.indexSize; address[] memory tokens = getTopCategoryTokens(meta.categoryID, size); Prices.TwoWayAveragePrice[] memory prices = oracle.computeTwoWayAveragePrices(tokens); FixedPoint.uq112x112[] memory weights = MCapSqrt.computeTokenWeights(tokens, prices); uint256[] memory minimumBalances = new uint256[](size); uint96[] memory denormalizedWeights = new uint96[](size); uint144 totalValue = _estimatePoolValue(IPool(poolAddress)); for (uint256 i = 0; i < size; i++) { // The minimum balance is the number of tokens worth the minimum weight // of the pool. The minimum weight is 1/100, so we divide the total value // by 100 to get the desired weth value, then multiply by the price of eth // in terms of that token to get the minimum balance. minimumBalances[i] = prices[i].computeAverageTokensForEth(totalValue) / 100; denormalizedWeights[i] = _denormalizeFractionalWeight(weights[i]); } IPool(poolAddress).reindexTokens( tokens, denormalizedWeights, minimumBalances ); record.timestamp = uint128(now); _poolUpdateRecords[poolAddress] = record; } /** * @dev Reweighs the assets in a pool by market cap and sets the * desired new weights, which will be adjusted over time. */ function reweighPool(address poolAddress) external { require(_havePool(poolAddress), "ERR_POOL_NOT_FOUND"); PoolUpdateRecord memory record = _poolUpdateRecords[poolAddress]; require( now - record.timestamp >= POOL_REWEIGH_DELAY, "ERR_POOL_REWEIGH_DELAY" ); require( (++record.index % (REWEIGHS_BEFORE_REINDEX + 1)) != 0, "ERR_REWEIGH_INDEX" ); address[] memory tokens = IPool(poolAddress).getCurrentDesiredTokens(); Prices.TwoWayAveragePrice[] memory prices = oracle.computeTwoWayAveragePrices(tokens); FixedPoint.uq112x112[] memory weights = MCapSqrt.computeTokenWeights(tokens, prices); uint96[] memory denormalizedWeights = new uint96[](tokens.length); for (uint256 i = 0; i < tokens.length; i++) { denormalizedWeights[i] = _denormalizeFractionalWeight(weights[i]); } IPool(poolAddress).reweighTokens(tokens, denormalizedWeights); record.timestamp = uint128(now); _poolUpdateRecords[poolAddress] = record; } /* --- Pool Queries --- */ /** * @dev Compute the create2 address for a pool initializer. */ function computeInitializerAddress(address poolAddress) public view returns (address initializerAddress) { initializerAddress = Salty.computeProxyAddressManyToOne( address(_proxyManager), address(this), INITIALIZER_IMPLEMENTATION_ID, keccak256(abi.encodePacked(poolAddress)) ); } /** * @dev Compute the create2 address for a pool's unbound token seller. */ function computeSellerAddress(address poolAddress) public view returns (address sellerAddress) { sellerAddress = Salty.computeProxyAddressManyToOne( address(_proxyManager), address(this), SELLER_IMPLEMENTATION_ID, keccak256(abi.encodePacked(poolAddress)) ); } /** * @dev Compute the create2 address for a pool. */ function computePoolAddress(uint256 categoryID, uint256 indexSize) public view returns (address poolAddress) { poolAddress = Salty.computeProxyAddressManyToOne( address(_proxyManager), address(_factory), POOL_IMPLEMENTATION_ID, keccak256(abi.encodePacked( address(this), keccak256(abi.encodePacked(categoryID, indexSize)) )) ); } /** * @dev Queries the top `indexSize` tokens in a category from the market oracle, * computes their relative weights by market cap square root and determines * the weighted balance of each token to meet a specified total value. */ function getInitialTokensAndBalances( uint256 categoryID, uint256 indexSize, uint144 wethValue ) public view returns ( address[] memory tokens, uint256[] memory balances ) { tokens = getTopCategoryTokens(categoryID, indexSize); Prices.TwoWayAveragePrice[] memory prices = oracle.computeTwoWayAveragePrices(tokens); FixedPoint.uq112x112[] memory weights = MCapSqrt.computeTokenWeights(tokens, prices); balances = new uint256[](indexSize); for (uint256 i = 0; i < indexSize; i++) { balances[i] = MCapSqrt.computeWeightedBalance(wethValue, weights[i], prices[i]); } } /* --- Internal Pool Utility Functions --- */ function _havePool(address pool) internal view returns (bool) { return _poolMeta[pool].initialized; } /** * @dev Estimate the total value of a pool by taking its first token's * "virtual balance" (balance * (totalWeight/weight)) and multiplying * by that token's average ether price from UniSwap. */ function _estimatePoolValue(IPool pool) internal view returns (uint144) { (address token, uint256 value) = pool.extrapolatePoolValueFromToken(); FixedPoint.uq112x112 memory price = oracle.computeAverageTokenPrice(token); return price.mul(value).decode144(); } /* --- General Utility Functions --- */ /** * @dev Converts a fixed point fraction to a denormalized weight. * Multiply the fraction by the max weight and decode to an unsigned integer. */ function _denormalizeFractionalWeight(FixedPoint.uq112x112 memory fraction) internal pure returns (uint96) { return uint96(fraction.mul(WEIGHT_MULTIPLIER).decode144()); } /** * @dev Re-assigns a uint128 array to a uint256 array. * This does not affect memory allocation as all Solidity * uint arrays take 32 bytes per item. */ function _to256Array(uint128[] memory arr) internal pure returns (uint256[] memory outArr) { assembly { outArr := arr } } }
Estimate the total value of a pool by taking its first token's "virtual balance" (balance (totalWeight/weight)) and multiplying by that token's average ether price from UniSwap./
function _estimatePoolValue(IPool pool) internal view returns (uint144) { (address token, uint256 value) = pool.extrapolatePoolValueFromToken(); FixedPoint.uq112x112 memory price = oracle.computeAverageTokenPrice(token); return price.mul(value).decode144(); }
1,766,714
// File @openzeppelin/contracts/math/[email protected] pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File @openzeppelin/contracts/math/[email protected] pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File @openzeppelin/contracts/token/ERC20/[email protected] 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/token/ERC20/[email protected] pragma solidity ^0.5.0; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } // File @openzeppelin/contracts/utils/[email protected] 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/[email protected] 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/base/interface/IController.sol pragma solidity 0.5.16; interface IController { event SharePriceChangeLog( address indexed vault, address indexed strategy, uint256 oldSharePrice, uint256 newSharePrice, uint256 timestamp ); // [Grey list] // An EOA can safely interact with the system no matter what. // If you're using Metamask, you're using an EOA. // Only smart contracts may be affected by this grey list. // // This contract will not be able to ban any EOA from the system // even if an EOA is being added to the greyList, he/she will still be able // to interact with the whole system as if nothing happened. // Only smart contracts will be affected by being added to the greyList. // This grey list is only used in Vault.sol, see the code there for reference function greyList(address _target) external view returns(bool); function addVaultAndStrategy(address _vault, address _strategy) external; function doHardWork(address _vault) external; function hasVault(address _vault) external returns(bool); function salvage(address _token, uint256 amount) external; function salvageStrategy(address _strategy, address _token, uint256 amount) external; function notifyFee(address _underlying, uint256 fee) external; function profitSharingNumerator() external view returns (uint256); function profitSharingDenominator() external view returns (uint256); function feeRewardForwarder() external view returns(address); function setFeeRewardForwarder(address _value) external; function addHardWorker(address _worker) external; } // File contracts/base/interface/IFeeRewardForwarderV6.sol pragma solidity 0.5.16; interface IFeeRewardForwarderV6 { function poolNotifyFixedTarget(address _token, uint256 _amount) external; function notifyFeeAndBuybackAmounts(uint256 _feeAmount, address _pool, uint256 _buybackAmount) external; function notifyFeeAndBuybackAmounts(address _token, uint256 _feeAmount, address _pool, uint256 _buybackAmount) external; function profitSharingPool() external view returns (address); function configureLiquidation(address[] calldata _path, bytes32[] calldata _dexes) external; } // File contracts/base/inheritance/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/base/inheritance/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 contracts/base/inheritance/Controllable.sol pragma solidity 0.5.16; contract Controllable is Governable { constructor(address _storage) Governable(_storage) public { } modifier onlyController() { require(store.isController(msg.sender), "Not a controller"); _; } modifier onlyControllerOrGovernance(){ require((store.isController(msg.sender) || store.isGovernance(msg.sender)), "The caller must be controller or governance"); _; } function controller() public view returns (address) { return store.controller(); } } // File contracts/base/inheritance/RewardTokenProfitNotifier.sol pragma solidity 0.5.16; contract RewardTokenProfitNotifier is Controllable { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public profitSharingNumerator; uint256 public profitSharingDenominator; address public rewardToken; constructor( address _storage, address _rewardToken ) public Controllable(_storage){ rewardToken = _rewardToken; // persist in the state for immutability of the fee profitSharingNumerator = 30; //IController(controller()).profitSharingNumerator(); profitSharingDenominator = 100; //IController(controller()).profitSharingDenominator(); require(profitSharingNumerator < profitSharingDenominator, "invalid profit share"); } event ProfitLogInReward(uint256 profitAmount, uint256 feeAmount, uint256 timestamp); event ProfitAndBuybackLog(uint256 profitAmount, uint256 feeAmount, uint256 timestamp); function notifyProfitInRewardToken(uint256 _rewardBalance) internal { if( _rewardBalance > 0 ){ uint256 feeAmount = _rewardBalance.mul(profitSharingNumerator).div(profitSharingDenominator); emit ProfitLogInReward(_rewardBalance, feeAmount, block.timestamp); IERC20(rewardToken).safeApprove(controller(), 0); IERC20(rewardToken).safeApprove(controller(), feeAmount); IController(controller()).notifyFee( rewardToken, feeAmount ); } else { emit ProfitLogInReward(0, 0, block.timestamp); } } function notifyProfitAndBuybackInRewardToken(uint256 _rewardBalance, address pool, uint256 _buybackRatio) internal { if( _rewardBalance > 0 ){ uint256 feeAmount = _rewardBalance.mul(profitSharingNumerator).div(profitSharingDenominator); address forwarder = IController(controller()).feeRewardForwarder(); emit ProfitAndBuybackLog(_rewardBalance, feeAmount, block.timestamp); IERC20(rewardToken).safeApprove(forwarder, 0); IERC20(rewardToken).safeApprove(forwarder, _rewardBalance); IFeeRewardForwarderV6(forwarder).notifyFeeAndBuybackAmounts( rewardToken, feeAmount, pool, _rewardBalance.sub(feeAmount).mul(_buybackRatio).div(10000) ); } else { emit ProfitAndBuybackLog(0, 0, block.timestamp); } } } // File contracts/base/interface/IStrategy.sol pragma solidity 0.5.16; interface IStrategy { function unsalvagableTokens(address tokens) external view returns (bool); function governance() external view returns (address); function controller() external view returns (address); function underlying() external view returns (address); function vault() external view returns (address); function withdrawAllToVault() external; function withdrawToVault(uint256 amount) external; function investedUnderlyingBalance() external view returns (uint256); // itsNotMuch() // should only be called by controller function salvage(address recipient, address token, uint256 amount) external; function doHardWork() external; function depositArbCheck() external view returns(bool); } // File contracts/base/interface/ILiquidator.sol // SPDX-License-Identifier: MIT pragma solidity 0.5.16; interface ILiquidator { event Swap( address indexed buyToken, address indexed sellToken, address indexed target, address initiator, uint256 amountIn, uint256 slippage, uint256 total ); function swapTokenOnMultipleDEXes( uint256 amountIn, uint256 amountOutMin, address target, bytes32[] calldata dexes, address[] calldata path ) external; function swapTokenOnDEX( uint256 amountIn, uint256 amountOutMin, address target, bytes32 dexName, address[] calldata path ) external; function getAllDexes() external view returns (bytes32[] memory); } // File contracts/base/interface/ILiquidatorRegistry.sol // SPDX-License-Identifier: MIT pragma solidity 0.5.16; interface ILiquidatorRegistry { function universalLiquidator() external view returns(address); function setUniversalLiquidator(address _ul) external; function getPath( bytes32 dex, address inputToken, address outputToken ) external view returns(address[] memory); function setPath( bytes32 dex, address inputToken, address outputToken, address[] calldata path ) external; } // File contracts/base/StrategyBaseUL.sol //SPDX-License-Identifier: Unlicense pragma solidity 0.5.16; contract StrategyBaseUL is IStrategy, RewardTokenProfitNotifier { using SafeMath for uint256; using SafeERC20 for IERC20; event ProfitsNotCollected(address); event Liquidating(address, uint256); address public underlying; address public vault; mapping (address => bool) public unsalvagableTokens; address public universalLiquidatorRegistry; modifier restricted() { require(msg.sender == vault || msg.sender == address(controller()) || msg.sender == address(governance()), "The sender has to be the controller or vault or governance"); _; } constructor( address _storage, address _underlying, address _vault, address _rewardToken, address _universalLiquidatorRegistry ) RewardTokenProfitNotifier(_storage, _rewardToken) public { underlying = _underlying; vault = _vault; unsalvagableTokens[_rewardToken] = true; unsalvagableTokens[_underlying] = true; universalLiquidatorRegistry = _universalLiquidatorRegistry; } function universalLiquidator() public view returns(address) { return ILiquidatorRegistry(universalLiquidatorRegistry).universalLiquidator(); } } // File contracts/base/interface/IVault.sol pragma solidity 0.5.16; interface IVault { function initializeVault( address _storage, address _underlying, uint256 _toInvestNumerator, uint256 _toInvestDenominator ) external ; function balanceOf(address) external view returns (uint256); function underlyingBalanceInVault() external view returns (uint256); function underlyingBalanceWithInvestment() external view returns (uint256); // function store() external view returns (address); function governance() external view returns (address); function controller() external view returns (address); function underlying() external view returns (address); function strategy() external view returns (address); function setStrategy(address _strategy) external; function announceStrategyUpdate(address _strategy) external; function setVaultFractionToInvest(uint256 numerator, uint256 denominator) external; function deposit(uint256 amountWei) external; function depositFor(uint256 amountWei, address holder) external; function withdrawAll() external; function withdraw(uint256 numberOfShares) external; function getPricePerFullShare() external view returns (uint256); function underlyingBalanceWithInvestmentForHolder(address holder) view external returns (uint256); // hard work should be callable only by the controller (by the hard worker) or by governance function doHardWork() external; } // File contracts/base/interface/IRewardDistributionSwitcher.sol pragma solidity 0.5.16; contract IRewardDistributionSwitcher { function switchingAllowed(address) external returns(bool); function returnOwnership(address poolAddr) external; function enableSwitchers(address[] calldata switchers) external; function setSwithcer(address switcher, bool allowed) external; function setPoolRewardDistribution(address poolAddr, address newRewardDistributor) external; } // File contracts/base/interface/INoMintRewardPool.sol pragma solidity 0.5.16; interface INoMintRewardPool { function withdraw(uint) external; function getReward() external; function stake(uint) external; function balanceOf(address) external view returns (uint256); function earned(address account) external view returns (uint256); function exit() external; function rewardDistribution() external view returns (address); function lpToken() external view returns(address); function rewardToken() external view returns(address); // only owner function setRewardDistribution(address _rewardDistributor) external; function transferOwnership(address _owner) external; function notifyRewardAmount(uint256 _reward) external; } // File contracts/strategies/basis/interfaces/IBASPool.sol pragma solidity 0.5.16; interface IBASPool { /* ================= CALLS ================= */ function tokenOf(uint256 _pid) external view returns (address); function poolIdsOf(address _token) external view returns (uint256[] memory); function totalSupply(uint256 _pid) external view returns (uint256); function balanceOf(uint256 _pid, address _owner) external view returns (uint256); function rewardRatePerPool(uint256 _pid) external view returns (uint256); function rewardPerToken(uint256 _pid) external view returns (uint256); function rewardEarned(uint256 _pid, address _target) external view returns (uint256); /* ================= TXNS ================= */ function update(uint256 _pid) external; function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function claimReward(uint256 _pid) external; function exit(uint256 _pid) external; } // File contracts/strategies/basis/Basis2FarmStrategyV3.sol pragma solidity 0.5.16; /* * This is a general strategy for yields that are based on the synthetix reward contract * for example, yam, spaghetti, ham, shrimp. * * One strategy is deployed for one underlying asset, but the design of the contract * should allow it to switch between different reward contracts. * * It is important to note that not all SNX reward contracts that are accessible via the same interface are * suitable for this Strategy. One concrete example is CREAM.finance, as it implements a "Lock" feature and * would not allow the user to withdraw within some timeframe after the user have deposited. * This would be problematic to user as our "invest" function in the vault could be invoked by anyone anytime * and thus locking/reverting on subsequent withdrawals. Another variation is the YFI Governance: it can * activate a vote lock to stop withdrawal. * * Ref: * 1. CREAM https://etherscan.io/address/0xc29e89845fa794aa0a0b8823de23b760c3d766f5#code * 2. YAM https://etherscan.io/address/0x8538E5910c6F80419CD3170c26073Ff238048c9E#code * 3. SHRIMP https://etherscan.io/address/0x9f83883FD3cadB7d2A83a1De51F9Bf483438122e#code * 4. BASED https://etherscan.io/address/0x5BB622ba7b2F09BF23F1a9b509cd210A818c53d7#code * 5. YFII https://etherscan.io/address/0xb81D3cB2708530ea990a287142b82D058725C092#code * 6. YFIGovernance https://etherscan.io/address/0xBa37B002AbaFDd8E89a1995dA52740bbC013D992#code * * * * Respecting the current system design of choosing the best strategy under the vault, and also rewarding/funding * the public key that invokes the switch of strategies, this smart contract should be deployed twice and linked * to the same vault. When the governance want to rotate the crop, they would set the reward source on the strategy * that is not active, then set that apy higher and this one lower. * * Consequently, in the smart contract we restrict that we can only set a new reward source when it is not active. * */ contract Basis2FarmStrategyV3 is StrategyBaseUL { using SafeMath for uint256; using SafeERC20 for IERC20; address public farm; address public distributionPool; address public distributionSwitcher; address public rewardToken; bool public pausedInvesting = false; // When this flag is true, the strategy will not be able to invest. But users should be able to withdraw. IBASPool public rewardPool; // a flag for disabling selling for simplified emergency exit bool public sell = true; uint256 public sellFloor = 1e6; // Instead of trying to pass in the detailed liquidation path and different dexes to the liquidator, // we just pass in the input output of the liquidation path: // [ MIC, WETH, FARM ] , [SUSHI, UNI] // // This means that: // the first dex is sushi, the input is MIC and output is WETH. // the second dex is uni, the input is WETH and the output is FARM. // the universal liquidator itself would record the best path to liquidate from MIC to WETH on Sushiswap // provides the path for liquidating a token address [] public liquidationPath; // specifies which DEX is the token liquidated on bytes32 [] public liquidationDexes; // if the flag is set, then it would read the previous reward distribution from the pool // otherwise, it would read from `setRewardDistributionTo` and ask the distributionSwitcher to set to it. bool public autoRevertRewardDistribution; address public defaultRewardDistribution; uint poolId; event ProfitsNotCollected(); // This is only used in `investAllUnderlying()` // The user can still freely withdraw from the strategy modifier onlyNotPausedInvesting() { require(!pausedInvesting, "Action blocked as the strategy is in emergency state"); _; } constructor( address _storage, address _underlying, address _vault, address _rewardPool, uint _rewardPoolId, address _rewardToken, address _universalLiquidatorRegistry, address _farm, address _distributionPool, address _distributionSwitcher ) StrategyBaseUL(_storage, _underlying, _vault, _farm, _universalLiquidatorRegistry) public { require(_vault == INoMintRewardPool(_distributionPool).lpToken(), "distribution pool's lp must be the vault"); require(_farm == INoMintRewardPool(_distributionPool).rewardToken(), "distribution pool's reward must be FARM"); farm = _farm; distributionPool = _distributionPool; rewardToken = _rewardToken; distributionSwitcher = _distributionSwitcher; rewardPool = IBASPool(_rewardPool); poolId = _rewardPoolId; } function depositArbCheck() public view returns(bool) { return true; } /* * In case there are some issues discovered about the pool or underlying asset * Governance can exit the pool properly * The function is only used for emergency to exit the pool */ function emergencyExit() public onlyGovernance { if (rewardPool.balanceOf(poolId, address(this)) > 0) { rewardPool.withdraw(poolId, rewardPool.balanceOf(poolId, address(this))); } pausedInvesting = true; } /* * Resumes the ability to invest into the underlying reward pools */ function continueInvesting() public onlyGovernance { pausedInvesting = false; } function setLiquidationPaths(address [] memory _liquidationPath, bytes32[] memory _dexes) public onlyGovernance { liquidationPath = _liquidationPath; liquidationDexes = _dexes; } function _liquidateReward() internal { uint256 rewardBalance = IERC20(rewardToken).balanceOf(address(this)); if (!sell || rewardBalance < sellFloor) { // Profits can be disabled for possible simplified and rapid exit emit ProfitsNotCollected(); return; } // sell reward token to FARM // we can accept 1 as minimum because this is called only by a trusted role address uliquidator = universalLiquidator(); IERC20(rewardToken).safeApprove(uliquidator, 0); IERC20(rewardToken).safeApprove(uliquidator, rewardBalance); ILiquidator(uliquidator).swapTokenOnMultipleDEXes( rewardBalance, 1, address(this), // target liquidationDexes, liquidationPath ); uint256 farmAmount = IERC20(farm).balanceOf(address(this)); // Use farm as profit sharing base, sending it notifyProfitInRewardToken(farmAmount); // The remaining farms should be distributed to the distribution pool farmAmount = IERC20(farm).balanceOf(address(this)); // Switch reward distribution temporarily, notify reward, switch it back address prevRewardDistribution; if(autoRevertRewardDistribution) { prevRewardDistribution = INoMintRewardPool(distributionPool).rewardDistribution(); } else { prevRewardDistribution = defaultRewardDistribution; } IRewardDistributionSwitcher(distributionSwitcher).setPoolRewardDistribution(distributionPool, address(this)); // transfer and notify with the remaining farm amount IERC20(farm).safeTransfer(distributionPool, farmAmount); INoMintRewardPool(distributionPool).notifyRewardAmount(farmAmount); IRewardDistributionSwitcher(distributionSwitcher).setPoolRewardDistribution(distributionPool, prevRewardDistribution); } /* * Stakes everything the strategy holds into the reward pool */ function investAllUnderlying() internal onlyNotPausedInvesting { // this check is needed, because most of the SNX reward pools will revert if // you try to stake(0). if(IERC20(underlying).balanceOf(address(this)) > 0) { IERC20(underlying).approve(address(rewardPool), IERC20(underlying).balanceOf(address(this))); rewardPool.deposit(poolId, IERC20(underlying).balanceOf(address(this))); } } /* * Withdraws all the asset to the vault */ function withdrawAllToVault() public restricted { if (rewardPool.balanceOf(poolId, address(this)) > 0) { rewardPool.exit(poolId); } _liquidateReward(); if (IERC20(underlying).balanceOf(address(this)) > 0) { IERC20(underlying).safeTransfer(vault, IERC20(underlying).balanceOf(address(this))); } } /* * Withdraws all the asset to the vault */ function withdrawToVault(uint256 amount) public restricted { // Typically there wouldn't be any amount here // however, it is possible because of the emergencyExit if(amount > IERC20(underlying).balanceOf(address(this))){ // While we have the check above, we still using SafeMath below // for the peace of mind (in case something gets changed in between) uint256 needToWithdraw = amount.sub(IERC20(underlying).balanceOf(address(this))); rewardPool.withdraw(poolId, Math.min(rewardPool.balanceOf(poolId, address(this)), needToWithdraw)); } IERC20(underlying).safeTransfer(vault, amount); } /* * Note that we currently do not have a mechanism here to include the * amount of reward that is accrued. */ function investedUnderlyingBalance() external view returns (uint256) { // Adding the amount locked in the reward pool and the amount that is somehow in this contract // both are in the units of "underlying" // The second part is needed because there is the emergency exit mechanism // which would break the assumption that all the funds are always inside of the reward pool return rewardPool.balanceOf(poolId, address(this)).add(IERC20(underlying).balanceOf(address(this))); } /* * Governance or Controller can claim coins that are somehow transferred into the contract * Note that they cannot come in take away coins that are used and defined in the strategy itself * Those are protected by the "unsalvagableTokens". To check, see where those are being flagged. */ function salvage(address recipient, address token, uint256 amount) external onlyControllerOrGovernance { // To make sure that governance cannot come in and take away the coins require(!unsalvagableTokens[token], "token is defined as not salvagable"); IERC20(token).safeTransfer(recipient, amount); } /* * Get the reward, sell it in exchange for underlying, invest what you got. * It's not much, but it's honest work. * * Note that although `onlyNotPausedInvesting` is not added here, * calling `investAllUnderlying()` affectively blocks the usage of `doHardWork` * when the investing is being paused by governance. */ function doHardWork() external onlyNotPausedInvesting restricted { rewardPool.claimReward(poolId); _liquidateReward(); investAllUnderlying(); } /** * Can completely disable claiming UNI rewards and selling. Good for emergency withdraw in the * simplest possible way. */ function setSell(bool s) public onlyGovernance { sell = s; } /** * Sets the minimum amount of CRV needed to trigger a sale. */ function setSellFloor(uint256 floor) public onlyGovernance { sellFloor = floor; } function setRewardPool(address _rewardPool, uint256 _pid) public onlyGovernance { require(IBASPool(_rewardPool).tokenOf(_pid) == underlying, "Pool underlying missmatch"); if (rewardPool.balanceOf(poolId, address(this)) > 0) { rewardPool.exit(poolId); } _liquidateReward(); poolId = _pid; rewardPool = IBASPool(_rewardPool); investAllUnderlying(); } } // File contracts/strategies/basis/Basis2FarmStrategyMainnet_DAI_BASV3.sol pragma solidity 0.5.16; contract Basis2FarmStrategyMainnet_DAI_BASV3 is Basis2FarmStrategyV3 { address public constant __dai = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); address public __basv2 = address(0x106538CC16F938776c7c180186975BCA23875287); address public __dai_basv2 = address(0x3E78F2E7daDe07ea685F8612F00477FD97162F1e); address public constant __rewardPool = address(0x818F83333244bA4BB72Dab0b60b1901158402f2E); address public constant __universalLiquidatorRegistry = address(0x7882172921E99d590E097cD600554339fBDBc480); address public constant __farm = address(0xa0246c9032bC3A600820415aE600c6388619A14D); address public constant __weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address public constant __notifyHelper = address(0xE20c31e3d08027F5AfACe84A3A46B7b3B165053c); constructor( address _storage, address _vault, address _distributionPool, address _distributionSwitcher ) Basis2FarmStrategyV3( _storage, __dai_basv2, _vault, __rewardPool, 2, // pool ID __basv2, __universalLiquidatorRegistry, __farm, _distributionPool, _distributionSwitcher ) public { require(IVault(_vault).underlying() == __dai_basv2, "Underlying mismatch"); liquidationPath = [__basv2, farm]; liquidationDexes.push(bytes32(uint256(keccak256("uni")))); defaultRewardDistribution = __notifyHelper; } }
function store() external view returns (address); hard work should be callable only by the controller (by the hard worker) or by governance
interface IVault { function initializeVault( address _storage, address _underlying, uint256 _toInvestNumerator, uint256 _toInvestDenominator ) external ; function balanceOf(address) external view returns (uint256); function underlyingBalanceInVault() external view returns (uint256); function underlyingBalanceWithInvestment() external view returns (uint256); function governance() external view returns (address); function controller() external view returns (address); function underlying() external view returns (address); function strategy() external view returns (address); function setStrategy(address _strategy) external; function announceStrategyUpdate(address _strategy) external; function setVaultFractionToInvest(uint256 numerator, uint256 denominator) external; function deposit(uint256 amountWei) external; function depositFor(uint256 amountWei, address holder) external; function withdrawAll() external; function withdraw(uint256 numberOfShares) external; function getPricePerFullShare() external view returns (uint256); function underlyingBalanceWithInvestmentForHolder(address holder) view external returns (uint256); function doHardWork() external; }
169,400
// SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract UniqlyClaimingByAdmin is Ownable{ /// ----- VARIABLES ----- /// /// Settings /// @dev Claiming Price uint internal _standardClaimingPrice; /// @dev Owner Changing price uint internal _standardOwnerChangingPrice; /// @dev Verification price uint internal _standardPriceForVerification; /// @dev address of ERC20 token address internal _ERC20tokenAddress; /// NFT Contracts /// @dev Contract Addresses Accepted By Uniqly mapping(address => bool) internal _acceptedContracts; /// @dev Price for claiming in Native ERC20 token mapping(address => uint) internal _pricesForClaiming; /// @dev Change Onwer mapping(address => uint) internal _pricesForOwnerChanging; /// @dev isBurable mapping(address => bool) internal _isBurnable; /// Token /// @dev Returns true if token was claimed mapping(address => mapping(uint => bool)) internal _isTokenClaimed; /// @dev Claimed ids of contract mapping(address => uint[]) internal _claimedIds; /// @dev Owners addresses Array mapping(address => mapping(uint => mapping(uint => address))) internal _ownersAddresses; /// @dev Owners array count mapping(address => mapping(uint => uint)) internal _ownersCount; /// Name verification /// @dev Nonce for verification mapping(uint => bool) internal _isNonceRedeemed; /// @dev Addresses owners mapping(address => string) internal _addressesOwners; /// @dev Is onwer verified mapping(address => bool) internal _isAddressesOwnerVerified; /// @dev Is address was used mapping(address => bool) internal _isAddressUsed; /// ----- EVENTS ----- /// event Claim( address indexed _contractAddress, address indexed _claimer, uint256 indexed _tokenId, string _claimersName ); event ChangeOwner( address indexed _contractAddress, uint indexed _id, address _newOwner, address indexed _prevOwner, string _newOwnersName ); event PayedForClaim( address indexed _claimer, address indexed _contractAddress, uint256 indexed _tokenId ); event RequestedVerification( address indexed _requester, string _name ); /// ----- VIEWS ----- /// /// @notice Returns true if token was claimed function isTokenClaimed(address _address, uint _tokenId) external view returns(bool){ return _isTokenClaimed[_address][_tokenId]; } /// @notice Returns true for authorized contract addresses function isContractAuthorized(address _address) external view returns(bool){ return _acceptedContracts[_address]; } /// @notice Returns last owners address, name and verification status /// @dev this functions is tested by other functions' test function getLastOwnerOf(address _address, uint _id) external view returns(address, string memory, bool){ uint len = _ownersCount[_address][_id] - 1; address ownerAddress = _ownersAddresses[_address][_id][len]; return(ownerAddress, _addressesOwners[ownerAddress], _isAddressesOwnerVerified[ownerAddress]); } /// @notice Returns true when nonce was redeemed function isNonceRedeemed(uint _nonce) external view returns(bool){ return _isNonceRedeemed[_nonce]; } /// @notice Returns owners count of token function getOwnersCountOfToken(address _address, uint _id) external view returns(uint){ return(_ownersCount[_address][_id]); } /// @notice Returns owners name and verification status /// @dev this functions is tested by other functions' test function getAddressOwnerInfo(address _address) external view returns(string memory, bool){ require(_isAddressUsed[_address],"Address not used yet"); return (_addressesOwners[_address], _isAddressesOwnerVerified[_address]); } /// @notice Returns address and name of token owner by position in array function getOwnerOfTokenByPosition(address _address, uint _id, uint _position) external view returns(address, string memory){ address ownerAddress = _ownersAddresses[_address][_id][_position]; return(ownerAddress, _addressesOwners[ownerAddress] ); } /// @notice Returns all token holders names function getAllTokenHoldersNamesHistory(address _address, uint _id) external view returns(string[] memory){ uint len = _ownersCount[_address][_id]; if (len == 0){ return new string[](0); } string[] memory res = new string[](len); uint index; for(index=0; index < len; index++){ res[index] = _addressesOwners[_ownersAddresses[_address][_id][index]]; } return res; } /// @notice Returns all token holders addresses function getAllTokenHoldersAddressesHistory(address _address, uint _id) external view returns(address[] memory){ uint len = _ownersCount[_address][_id]; if (len == 0){ return new address[](0); } address[] memory res = new address[](len); uint index; for(index=0; index < len; index++){ res[index] = _ownersAddresses[_address][_id][index]; } return res; } /// @notice Returns all claimed ids of selected collection function getClaimedIdsOfCollection(address _address) external view returns(uint[] memory){ uint len = _claimedIds[_address].length; if (len == 0){ return new uint[](0); } uint[] memory res = new uint[](len); uint index; for(index=0; index < len; index++){ res[index] = _claimedIds[_address][index]; } return res; } /// @notice Returns how many items of collection was claimed function getClaimedCountOf(address _address) external view returns(uint){ return _claimedIds[_address].length; } /// @notice Returns Claiming Standard price function getStandardClaimingPrice() external view returns(uint){ return _standardClaimingPrice; } /// @notice Returns Claiming Price For selected contract function getClaimingPriceForContract(address _address) external view returns(uint){ return _getCorrectPrice(_pricesForClaiming[_address], _standardClaimingPrice); } /// @notice Returns Holders Change Rate For selected contract function getChangeOwnerPriceForContract(address _address) external view returns(uint){ return _getCorrectPrice(_pricesForOwnerChanging[_address], _standardOwnerChangingPrice); } /// @notice Returns Standard Price For Verification function getPriceForVerification() external view returns(uint){ return _standardPriceForVerification; } /// @notice Returns true for burnable tokens in contract function isBurnable(address _address) external view returns(bool){ return _isBurnable[_address]; } /// ----- PUBLIC METHODS ----- /// //TODO Change to internal /// @notice Used for verification /// @dev not test about functions related signature function getMessageHashForOwnerChange( address _address, string memory _claimersName, uint _nonce ) public pure returns (bytes32) { return keccak256(abi.encodePacked(_address, _claimersName, _nonce)); } /// @notice Pays For Claim function payForClaim( address _contractAddress, uint256 _tokenId ) external { require(_acceptedContracts[_contractAddress], "Contract address is not authorized"); uint claimingPrice = _getCorrectPrice(_pricesForClaiming[_contractAddress], _standardClaimingPrice); if(claimingPrice != 0){ IERC20 nativeToken = IERC20(_ERC20tokenAddress); require(nativeToken.transferFrom(msg.sender, address(this), claimingPrice)); } emit PayedForClaim(msg.sender, _contractAddress, _tokenId); } /// @notice Claim Function function claimByAdmin( address _contractAddress, uint256 _tokenId, string memory _claimersName, address _claimer, bool _isVerified ) external onlyOwner{ require(!_isTokenClaimed[_contractAddress][_tokenId], "Can't be claimed again"); IERC721 token = IERC721(_contractAddress); require(token.ownerOf(_tokenId) == _claimer, "Claimer needs to own this token"); if(_isBurnable[_contractAddress]){ IERC721Burnable(_contractAddress).burn(_tokenId); } else{ token.transferFrom(_claimer, address(this), _tokenId); } _isTokenClaimed[_contractAddress][_tokenId] = true; _claimedIds[_contractAddress].push(_tokenId); _ownersAddresses[_contractAddress][_tokenId][0] = _claimer; require(_tryToSetNewName(_claimer, _claimersName)); _isAddressesOwnerVerified[_claimer] = _isVerified; _ownersCount[_contractAddress][_tokenId]++; emit Claim(_contractAddress, _claimer, _tokenId, _claimersName); } /// @notice Change Onwer function changeOwner(address _contractAddress, uint _tokenId, string memory _newOwnersName, address _newOwnerAddress ) external{ require(_isTokenClaimed[_contractAddress][_tokenId], "Not claimed yet"); uint len = _ownersCount[_contractAddress][_tokenId]; address ownerAddress = _ownersAddresses[_contractAddress][_tokenId][len - 1]; require(ownerAddress == msg.sender, "Not owner"); uint changingPrice = _getCorrectPrice(_pricesForOwnerChanging[_contractAddress], _standardOwnerChangingPrice); if(changingPrice != 0){ IERC20 nativeToken = IERC20(_ERC20tokenAddress); require(nativeToken.transferFrom(msg.sender, address(this), changingPrice)); } _ownersAddresses[_contractAddress][_tokenId][len] = _newOwnerAddress; require(_tryToSetNewName(_newOwnerAddress, _newOwnersName)); _ownersCount[_contractAddress][_tokenId]++; emit ChangeOwner(_contractAddress, _tokenId, _newOwnerAddress, msg.sender, _newOwnersName); } /// @notice Verify Owner function verifyOwner(string memory _claimersName, uint _nonce, bytes memory _signature) external{ require( verifySignForAuthOwner(msg.sender, _claimersName, _nonce, _signature), "Signature is not valid" ); // require(!_isAddressesOwnerVerified[msg.sender], "Already verified"); require(!_isNonceRedeemed[_nonce], "Nonce redeemed"); _addressesOwners[msg.sender] = _claimersName; _isAddressesOwnerVerified[msg.sender] = true; _isAddressUsed[msg.sender] = true; _isNonceRedeemed[_nonce] = true; } /// @notice Takes a fee for verification function requestVerification(string memory _nameToVerify) external{ IERC20 nativeToken = IERC20(_ERC20tokenAddress); require(nativeToken.transferFrom(msg.sender, address(this), _standardPriceForVerification)); require(_tryToSetNewName(msg.sender, _nameToVerify)); emit RequestedVerification(msg.sender, _nameToVerify); } /// ----- OWNER METHODS ----- /// constructor(uint _standardPriceForClaiming, uint _standardVerificationPrice, uint _standardPriceForOwnerChanging, address _nativeTokenAddress){ _standardClaimingPrice = _standardPriceForClaiming; _standardPriceForVerification = _standardVerificationPrice; _standardOwnerChangingPrice = _standardPriceForOwnerChanging; _ERC20tokenAddress = _nativeTokenAddress; } /// @notice Change verification price function setVerificationPrice(uint _newPrice) external onlyOwner{ _standardPriceForVerification = _newPrice; } /// @notice Verify owner by admin function verifyByAdmin(address _userAddress, string memory _newName, bool _isVerifyed, bool _isUsed) external onlyOwner{ _addressesOwners[_userAddress] = _newName; _isAddressesOwnerVerified[_userAddress] = _isVerifyed; _isAddressUsed[msg.sender] = _isUsed; } /// @notice Change erc20 token using for payments function setErc20Token(address _contractAddress) external onlyOwner{ _ERC20tokenAddress = _contractAddress; } /// @notice Contract settings /// @param _claimingPrice Set to 1 if you want to use Standard Claiming Price /// @param _changeOwnerPrice Set to 1 if you want to use Stanrad Owner Changing Price function setContractAtributes(address _address, bool _enable, uint _claimingPrice, uint _changeOwnerPrice, bool _isBurnble) external onlyOwner{ _acceptedContracts[_address] = _enable; _pricesForClaiming[_address] = _claimingPrice; _pricesForOwnerChanging[_address] = _changeOwnerPrice; _isBurnable[_address] = _isBurnble; } /// @notice Edit standard price for claiming function editStandardClaimingPrice(uint _price) external onlyOwner{ _standardClaimingPrice = _price; } /// @notice Edit standard price for claiming function editStandardChangeOwnerPrice(uint _price) external onlyOwner{ _standardOwnerChangingPrice = _price; } /// @notice Withdraw/rescue erc20 tokens to owners address function withdrawERC20(address _address) external onlyOwner{ uint val = IERC20(_address).balanceOf(address(this)); Ierc20(_address).transfer(msg.sender, val); } /// @notice Owner change by admin function changeOwnerByAdmin(address _address, uint _id, address _newOwnerAddress, string memory _newOwnersName, bool _verificationStatus) external onlyOwner{ require(_isTokenClaimed[_address][_id], "Not claimed yet"); uint len = _ownersCount[_address][_id]; _ownersAddresses[_address][_id][len] = _newOwnerAddress; _addressesOwners[_newOwnerAddress] = _newOwnersName; _isAddressUsed[_newOwnerAddress] = true; _isAddressesOwnerVerified[_newOwnerAddress] = _verificationStatus; emit ChangeOwner(_address, _id, _newOwnerAddress, address(0), _newOwnersName); } /// ----- PRIVATE METHODS ----- /// /// @dev Return true when owner names equals function _tryToSetNewName(address _addressToSet, string memory _claimersName) internal returns(bool){ if(_isAddressUsed[_addressToSet] == true){ require (keccak256(abi.encodePacked(_addressesOwners[_addressToSet])) == keccak256(abi.encodePacked(_claimersName)), "Name mismatch for already used address"); return true; } else { _addressesOwners[_addressToSet] = _claimersName; _isAddressUsed[_addressToSet] = true; return true; } } /// @dev Return second argument when first equals 1 function _getCorrectPrice(uint _priceForContract, uint _standardPrice) internal pure returns(uint){ if(_priceForContract == 1){ return _standardPrice; } else return _priceForContract; } function getEthSignedMessageHash(bytes32 _messageHash) internal pure returns (bytes32) { return keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", _messageHash ) ); } function verifySignForAuthOwner( address _address, string memory _claimersName, uint _nonce, bytes memory _signature ) internal view returns (bool) { bytes32 messageHash = getMessageHashForOwnerChange(_address, _claimersName, _nonce); bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash); return recoverSigner(ethSignedMessageHash, _signature) == owner(); } function recoverSigner( bytes32 _ethSignedMessageHash, bytes memory _signature ) internal pure returns (address) { require(_signature.length == 65, "invalid signature length"); bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := byte(0, mload(add(_signature, 96))) } return ecrecover(_ethSignedMessageHash, v, r, s); } } interface Ierc20 { function transfer(address, uint256) external; } interface IERC721Burnable{ function burn(uint) external; }
Returns all token holders addresses
function getAllTokenHoldersAddressesHistory(address _address, uint _id) external view returns(address[] memory){ uint len = _ownersCount[_address][_id]; if (len == 0){ return new address[](0); } address[] memory res = new address[](len); uint index; for(index=0; index < len; index++){ res[index] = _ownersAddresses[_address][_id][index]; } return res; }
6,407,575
/* __ __ .__ .___ _____ / \ / \___________| | __| _/ _____/ ____\ \ \/\/ / _ \_ __ \ | / __ | / _ \ __\ \ ( <_> ) | \/ |__/ /_/ | ( <_> ) | \__/\ / \____/|__| |____/\____ | \____/|__| \/ \/ __ __.__ .__ __ ________ .___ / \ / \ |__ |__|/ |_ ____ \______ \ __ __ __| _/____ ______ \ \/\/ / | \| \ __\/ __ \ | | \| | \/ __ |/ __ \ / ___/ \ /| Y \ || | \ ___/ | ` \ | / /_/ \ ___/ \___ \ \__/\ / |___| /__||__| \___ > /_______ /____/\____ |\___ >____ > \/ \/ \/ \/ \/ \/ \/ More like World of White DAOudes imho */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; library SafeCast { function toUint224(uint256 value) internal pure returns (uint224) { require( value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits" ); return uint224(value); } function toUint128(uint256 value) internal pure returns (uint128) { require( value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits" ); return uint128(value); } function toUint96(uint256 value) internal pure returns (uint96) { require( value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits" ); return uint96(value); } function toUint64(uint256 value) internal pure returns (uint64) { require( value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits" ); return uint64(value); } function toUint32(uint256 value) internal pure returns (uint32) { require( value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits" ); return uint32(value); } function toUint16(uint256 value) internal pure returns (uint16) { require( value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits" ); return uint16(value); } function toUint8(uint256 value) internal pure returns (uint8) { require( value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits" ); return uint8(value); } function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } function toInt128(int256 value) internal pure returns (int128) { require( value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits" ); return int128(value); } function toInt64(int256 value) internal pure returns (int64) { require( value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits" ); return int64(value); } function toInt32(int256 value) internal pure returns (int32) { require( value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits" ); return int32(value); } function toInt16(int256 value) internal pure returns (int16) { require( value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits" ); return int16(value); } function toInt8(int256 value) internal pure returns (int8) { require( value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits" ); return int8(value); } function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require( value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256" ); return int256(value); } } 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"); } } 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); } } function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } 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); } function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } 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); } 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; } 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) ); } function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); } } abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator( typeHash, hashedName, hashedVersion ); _TYPE_HASH = typeHash; } function _domainSeparatorV4() internal view returns (bytes32) { if (block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator( _TYPE_HASH, _HASHED_NAME, _HASHED_VERSION ); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256( abi.encode( typeHash, nameHash, versionHash, block.chainid, address(this) ) ); } function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } library Address { 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; } 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" ); } 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" ); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}( data ); return _verifyCallResult(success, returndata, errorMessage); } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) 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); } } } } library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; 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); } } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { _setOwner(_msgSender()); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } 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); } } interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } abstract contract ERC165 is IERC165 { function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } library Timers { struct Timestamp { uint64 _deadline; } function getDeadline(Timestamp memory timer) internal pure returns (uint64) { return timer._deadline; } function setDeadline(Timestamp storage timer, uint64 timestamp) internal { timer._deadline = timestamp; } function reset(Timestamp storage timer) internal { timer._deadline = 0; } function isUnset(Timestamp memory timer) internal pure returns (bool) { return timer._deadline == 0; } function isStarted(Timestamp memory timer) internal pure returns (bool) { return timer._deadline > 0; } function isPending(Timestamp memory timer) internal view returns (bool) { return timer._deadline > block.timestamp; } function isExpired(Timestamp memory timer) internal view returns (bool) { return isStarted(timer) && timer._deadline <= block.timestamp; } struct BlockNumber { uint64 _deadline; } function getDeadline(BlockNumber memory timer) internal pure returns (uint64) { return timer._deadline; } function setDeadline(BlockNumber storage timer, uint64 timestamp) internal { timer._deadline = timestamp; } function reset(BlockNumber storage timer) internal { timer._deadline = 0; } function isUnset(BlockNumber memory timer) internal pure returns (bool) { return timer._deadline == 0; } function isStarted(BlockNumber memory timer) internal pure returns (bool) { return timer._deadline > 0; } function isPending(BlockNumber memory timer) internal view returns (bool) { return timer._deadline > block.number; } function isExpired(BlockNumber memory timer) internal view returns (bool) { return isStarted(timer) && timer._deadline <= block.number; } } abstract contract IGovernor is IERC165 { enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } /** * @dev Emitted when a proposal is created. */ event ProposalCreated( uint256 proposalId, address proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 startBlock, uint256 endBlock, string description ); /** * @dev Emitted when a proposal is canceled. */ event ProposalCanceled(uint256 proposalId); /** * @dev Emitted when a proposal is executed. */ event ProposalExecuted(uint256 proposalId); /** * @dev Emitted when a vote is cast. * * Note: `support` values should be seen as buckets. There interpretation depends on the voting module used. */ event VoteCast( address indexed voter, uint256 proposalId, uint8 support, uint256 weight, string reason ); event Shout(string mouthVomit); /** * @notice module:core * @dev Name of the governor instance (used in building the ERC712 domain separator). */ function name() public view virtual returns (string memory); /** * @notice module:core * @dev Version of the governor instance (used in building the ERC712 domain separator). Default: "1" */ function version() public view virtual returns (string memory); /** * @notice module:voting * @dev A description of the possible `support` values for {castVote} and the way these votes are counted, meant to * be consumed by UIs to show correct vote options and interpret the results. The string is a URL-encoded sequence of * key-value pairs that each describe one aspect, for example `support=bravo&quorum=for,abstain`. * * There are 2 standard keys: `support` and `quorum`. * * - `support=bravo` refers to the vote options 0 = For, 1 = Against, 2 = Abstain, as in `GovernorBravo`. * - `quorum=bravo` means that only For votes are counted towards quorum. * - `quorum=for,abstain` means that both For and Abstain votes are counted towards quorum. * * NOTE: The string can be decoded by the standard * https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams[`URLSearchParams`] * JavaScript class. */ // solhint-disable-next-line func-name-mixedcase function COUNTING_MODE() public pure virtual returns (string memory); /** * @notice module:core * @dev Hashing function used to (re)build the proposal id from the proposal details.. */ function hashProposal( address[] calldata targets, uint256[] calldata values, bytes[] calldata calldatas, bytes32 descriptionHash ) public pure virtual returns (uint256); /** * @notice module:core * @dev Current state of a proposal, following Compound's convention */ function state(uint256 proposalId) public view virtual returns (ProposalState); /** * @notice module:core * @dev block number used to retrieve user's votes and quorum. */ function proposalSnapshot(uint256 proposalId) public view virtual returns (uint256); /** * @notice module:core * @dev timestamp at which votes close. */ function proposalDeadline(uint256 proposalId) public view virtual returns (uint256); /** * @notice module:user-config * @dev delay, in number of block, between the proposal is created and the vote starts. This can be increassed to * leave time for users to buy voting power, of delegate it, before the voting of a proposal starts. */ function votingDelay() public view virtual returns (uint256); /** * @notice module:user-config * @dev delay, in number of blocks, between the vote start and vote ends. * * Note: the {votingDelay} can delay the start of the vote. This must be considered when setting the voting * duration compared to the voting delay. */ function votingPeriod() public view virtual returns (uint256); /** * @notice module:user-config * @dev Minimum number of cast voted required for a proposal to be successful. * * Note: The `blockNumber` parameter corresponds to the snaphot used for counting vote. This allows to scale the * quroum depending on values such as the totalSupply of a token at this block (see {ERC20Votes}). */ function quorum(uint256 blockNumber) public view virtual returns (uint256); /** * @notice module:reputation * @dev Voting power of an `account` at a specific `blockNumber`. * * Note: this can be implemented in a number of ways, for example by reading the delegated balance from one (or * multiple), {ERC20Votes} tokens. */ function getVotes(address account, uint256 blockNumber) public view virtual returns (uint256); /** * @notice module:voting * @dev Returns weither `account` has cast a vote on `proposalId`. */ function hasVoted(uint256 proposalId, address account) public view virtual returns (bool); /** * @dev Create a new proposal. Vote start {IGovernor-votingDelay} blocks after the proposal is created and ends * {IGovernor-votingPeriod} blocks after the voting starts. * * Emits a {ProposalCreated} event. */ function propose( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description ) public virtual returns (uint256 proposalId); /** * @dev Execute a successful proposal. This requires the quorum to be reached, the vote to be successful, and the * deadline to be reached. * * Emits a {ProposalExecuted} event. * * Note: some module can modify the requirements for execution, for example by adding an additional timelock. */ function execute( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) public payable virtual returns (uint256 proposalId); /** * @dev Cast a vote * * Emits a {VoteCast} event. */ function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256 balance); /** * @dev Cast a with a reason * * Emits a {VoteCast} event. */ function castVoteWithReason( uint256 proposalId, uint8 support, string calldata reason ) public virtual returns (uint256 balance); /** * @dev Cast a vote using the user cryptographic signature. * * Emits a {VoteCast} event. */ function castVoteBySig( uint256 proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s ) public virtual returns (uint256 balance); } interface IWorldOfWhiteDudes { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); function totalSupply() external view returns (uint256); function maxSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); /** * @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); function walletOfOwner(address owner) external view returns (uint256[] memory); } abstract contract BoolPacker { function getBoolean(uint256 _packedBools, uint256 _boolNumber) internal pure returns (bool) { uint256 flag = (_packedBools >> _boolNumber) & uint256(1); return (flag == 1 ? true : false); } function setBoolean( uint256 _packedBools, uint256 _boolNumber, bool _value ) internal pure returns (uint256) { if (_value) return _packedBools | (uint256(1) << _boolNumber); else return _packedBools & ~(uint256(1) << _boolNumber); } } abstract contract Governor is Ownable, ERC165, EIP712, IGovernor, BoolPacker { using SafeCast for uint256; using Timers for Timers.BlockNumber; IWorldOfWhiteDudes public immutable token = IWorldOfWhiteDudes(0xD00D1e06a2680E02919f4F5c5EC5dC45d67bB0b5); bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)"); struct ProposalVote { Timers.BlockNumber voteStart; Timers.BlockNumber voteEnd; bool executed; bool canceled; uint16 againstVotes; uint16 forVotes; uint16 abstainVotes; uint16 maxVotes; //mapping(address => uint16) voteCount; //mapping(uint256 => bool) tokenHasVoted; //uint8[10000] tokenHasVoted; uint256[40] tokenHasVoted; } function getTokenHasVoted(uint256 proposalId, uint256 tokenId) public view returns (bool hasTokenVoted) { ProposalVote storage proposalvote = _proposals[proposalId]; return getBoolean(proposalvote.tokenHasVoted[tokenId / 40], tokenId % 256); } string private _name; uint256 public totalProposals; mapping(uint256 => uint256) public proposalIndexes; mapping(uint256 => string) public proposalTitles; mapping(uint256 => ProposalVote) internal _proposals; /** * @dev Restrict access to governor executing address. Some module might override the _executor function to make * sure this modifier is consistant with the execution model. */ modifier onlyGovernance() { require(_msgSender() == _executor(), "Governor: onlyGovernance"); _; } uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status = _NOT_ENTERED; modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } /** * @dev Sets the value for {name} and {version} */ constructor(string memory name_) EIP712(name_, version()) { _name = name_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) { return interfaceId == type(IGovernor).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IGovernor-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IGovernor-version}. */ function version() public view virtual override returns (string memory) { return "1"; } /** * @dev See {IGovernor-hashProposal}. * * The proposal id is produced by hashing the RLC encoded `targets` array, the `values` array, the `calldatas` array * and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id * can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in * advance, before the proposal is submitted. * * Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the * same proposal (with same operation and same description) will have the same id if submitted on multiple governors * accross multiple networks. This also means that in order to execute the same operation twice (on the same * governor) the proposer will have to change the description in order to avoid proposal id conflicts. */ function hashProposal( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) public pure virtual override returns (uint256) { return uint256( keccak256( abi.encode(targets, values, calldatas, descriptionHash) ) ); } function state(uint256 proposalId) public view virtual override returns (ProposalState) { ProposalVote storage proposal = _proposals[proposalId]; if (proposal.executed) { return ProposalState.Executed; } else if (proposal.canceled) { return ProposalState.Canceled; } else if (proposal.voteStart.isPending()) { return ProposalState.Pending; } else if (proposal.voteEnd.isPending()) { return ProposalState.Active; } else if (proposal.voteEnd.isExpired()) { return _quorumReached(proposalId) && _voteSucceeded(proposalId) ? ProposalState.Succeeded : ProposalState.Defeated; } else { revert("Governor: unknown proposal id"); } } function proposalSnapshot(uint256 proposalId) public view virtual override returns (uint256) { return _proposals[proposalId].voteStart.getDeadline(); } function proposalDeadline(uint256 proposalId) public view virtual override returns (uint256) { return _proposals[proposalId].voteEnd.getDeadline(); } /** * @dev Amount of votes already cast passes the threshold limit. */ function _quorumReached(uint256 proposalId) internal view virtual returns (bool); /** * @dev Is the proposal successful or not. */ function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool); function _countVote( uint256 proposalId, address account, uint8 support ) internal virtual returns (uint16); function propose( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description ) public virtual override returns (uint256) { string memory blank; return NewPropose(targets, values, calldatas, blank, description); } function NewPropose( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory title, string memory description ) public virtual returns (uint256) { uint256 proposalId = hashProposal( targets, values, calldatas, keccak256(bytes(description)) ); require( targets.length == values.length, "Governor: invalid proposal length" ); require( targets.length == calldatas.length, "Governor: invalid proposal length" ); require(targets.length > 0, "Governor: empty proposal"); ProposalVote storage proposal = _proposals[proposalId]; require( proposal.voteStart.isUnset(), "Governor: proposal already exists" ); uint64 snapshot = block.number.toUint64() + votingDelay().toUint64(); uint64 deadline = snapshot + votingPeriod().toUint64(); proposal.voteStart.setDeadline(snapshot); proposal.voteEnd.setDeadline(deadline); proposal.maxVotes = uint16(token.totalSupply()); proposalIndexes[totalProposals] = proposalId; proposalTitles[proposalId] = title; totalProposals += 1; emit ProposalCreated( proposalId, _msgSender(), targets, values, new string[](targets.length), calldatas, snapshot, deadline, description ); return proposalId; } function execute( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) public payable virtual override nonReentrant returns (uint256) { uint256 proposalId = hashProposal( targets, values, calldatas, descriptionHash ); ProposalState status = state(proposalId); require( status == ProposalState.Succeeded || status == ProposalState.Queued, "Governor: proposal not successful" ); _proposals[proposalId].executed = true; emit ProposalExecuted(proposalId); _execute(proposalId, targets, values, calldatas, descriptionHash); return proposalId; } function _execute( uint256, /* proposalId */ address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 /*descriptionHash*/ ) internal virtual { string memory errorMessage = "Governor: call reverted without message"; for (uint256 i = 0; i < targets.length; ++i) { (bool success, bytes memory returndata) = targets[i].call{ value: values[i] }(calldatas[i]); Address._verifyCallResult(success, returndata, errorMessage); } } /** * @dev Internal cancel mechanism: locks up the proposal timer, preventing it from being re-submitted. Marks it as * canceled to allow distinguishing it from executed proposals. * * Emits a {IGovernor-ProposalCanceled} event. */ function _cancel( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) internal virtual returns (uint256) { uint256 proposalId = hashProposal( targets, values, calldatas, descriptionHash ); ProposalState status = state(proposalId); require( status != ProposalState.Canceled && status != ProposalState.Expired && status != ProposalState.Executed, "Governor: proposal not active" ); _proposals[proposalId].canceled = true; emit ProposalCanceled(proposalId); return proposalId; } /** * @dev See {IGovernor-castVote}. */ function castVote(uint256 proposalId, uint8 support) public virtual override returns (uint256) { address voter = _msgSender(); return _castVote(proposalId, voter, support, ""); } /** * @dev See {IGovernor-castVoteWithReason}. */ function castVoteWithReason( uint256 proposalId, uint8 support, string calldata reason ) public virtual override returns (uint256) { address voter = _msgSender(); return _castVote(proposalId, voter, support, reason); } /** * @dev See {IGovernor-castVoteBySig}. */ function castVoteBySig( uint256 proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s ) public virtual override returns (uint256) { address voter = ECDSA.recover( _hashTypedDataV4( keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support)) ), v, r, s ); return _castVote(proposalId, voter, support, ""); } /** * @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve * voting weight using {IGovernor-getVotes} and call the {_countVote} internal function. * * Emits a {IGovernor-VoteCast} event. */ function _castVote( uint256 proposalId, address account, uint8 support, string memory reason ) internal virtual returns (uint256) { require( state(proposalId) == ProposalState.Active, "Governor: vote not currently active" ); uint256 weight = _countVote(proposalId, account, support); emit VoteCast(account, proposalId, support, weight, reason); return weight; } /** * @dev Address through which the governor executes action. Will be overloaded by module that execute actions * through another contract such as a timelock. */ function _executor() internal view virtual returns (address) { return address(this); } } abstract contract GovernorProposalThreshold is Governor { /** * @dev See {IGovernor-propose}. */ function propose( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description ) public virtual override returns (uint256) { require( getVotes(msg.sender, block.number - 1) >= proposalThreshold(), "GovernorCompatibilityBravo: proposer votes below proposal threshold" ); return super.propose(targets, values, calldatas, description); } /** * @dev Part of the Governor Bravo's interface: _"The number of votes required in order for a voter to become a proposer"_. */ function proposalThreshold() public view virtual returns (uint256); } abstract contract GovernorCountingSimple is Governor { /** * @dev Supported vote types. Matches Governor Bravo ordering. */ enum VoteType { Against, For, Abstain } /** * @dev See {IGovernor-COUNTING_MODE}. */ // solhint-disable-next-line func-name-mixedcase function COUNTING_MODE() public pure virtual override returns (string memory) { return "support=bravo&quorum=for,abstain"; } function getVotes(address account, uint256) public view virtual override returns (uint256) { return token.balanceOf(account); } function votesLeft(uint256 proposalId, address account) public view virtual returns (uint256 voteAmount) { uint256 tokenCount = token.balanceOf(account); uint256 tokenId; ProposalVote storage proposalvote = _proposals[proposalId]; for (uint256 i = 0; i < tokenCount; i++) { tokenId = token.tokenOfOwnerByIndex(account, i); if ( !getTokenHasVoted(proposalId, tokenId) && //proposalvote.tokenHasVoted[tokenId] == 0 && tokenId < proposalvote.maxVotes ) { voteAmount += 1; } } return voteAmount; } /** * @dev See {IGovernor-hasVoted}. */ function hasVoted(uint256, address) public view virtual override returns (bool) { require(false, "Don't use this method"); return false; //return _proposals[proposalId].voteCount[account] > 0; } /** * @dev Accessor to the internal vote counts. */ function proposalVotes(uint256 proposalId) public view virtual returns ( uint256 againstVotes, uint256 forVotes, uint256 abstainVotes ) { ProposalVote storage proposalvote = _proposals[proposalId]; return ( proposalvote.againstVotes, proposalvote.forVotes, proposalvote.abstainVotes ); } function getProposal(uint256 proposalId) public view virtual returns ( string memory title, string memory currentState, uint256 againstVotes, uint256 forVotes, uint256 abstainVotes, uint256 totalVotes, uint256 currentQuorum, uint256 minQuorum, uint256 maxVotes ) { string[8] memory proposalStates; proposalStates = [ "Pending", "Active", "Canceled", "Defeated", "Succeeded", "Queued", "Expired", "Executed" ]; ProposalVote storage proposalvote = _proposals[proposalId]; return ( proposalTitles[proposalId], proposalStates[uint256(state(proposalId))], proposalvote.againstVotes, proposalvote.forVotes, proposalvote.abstainVotes, proposalvote.againstVotes + proposalvote.forVotes + proposalvote.abstainVotes, proposalvote.forVotes + proposalvote.abstainVotes, quorum(proposalvote.maxVotes), proposalvote.maxVotes ); } /* function getProposalAccountVotes(uint256 proposalId, address owner) public view virtual returns (uint256 ownerVoteCount) { ProposalVote storage proposalvote = _proposals[proposalId]; return (proposalvote.voteCount[owner]); } */ function hasTokenVoted(uint256 proposalId, uint256 tokenId) public view virtual returns (bool tokenVoted) { //ProposalVote storage proposalvote = _proposals[proposalId]; //return (proposalvote.tokenHasVoted[tokenId] == 1); return getTokenHasVoted(proposalId, tokenId); } function _quorumReached(uint256 proposalId) internal view virtual override returns (bool) { ProposalVote storage proposalvote = _proposals[proposalId]; return quorum(_proposals[proposalId].maxVotes) <= proposalvote.forVotes + proposalvote.abstainVotes; } function _voteSucceeded(uint256 proposalId) internal view virtual override returns (bool) { ProposalVote storage proposalvote = _proposals[proposalId]; return proposalvote.forVotes > proposalvote.againstVotes; } function _countVote( uint256 proposalId, address account, uint8 support ) internal virtual override returns (uint16 voteAmount) { ProposalVote storage proposalvote = _proposals[proposalId]; uint256[40] storage vState = proposalvote.tokenHasVoted; uint256[] memory tokens = token.walletOfOwner(account); uint256 tokenId; uint256 idxInt; uint256 idxBool; for (uint256 i = 0; i < tokens.length; i++) { tokenId = tokens[i]; idxInt = tokenId / 40; idxBool = tokenId % 256; if ( ((vState[idxInt] >> idxBool) & uint256(1)) != 1 && tokenId < proposalvote.maxVotes ) { vState[idxInt] = vState[idxInt] | (uint256(1) << idxBool); voteAmount += 1; } } require(voteAmount > 0, "GovernorVotingSimple: No votes left"); if (support == uint8(VoteType.Against)) { proposalvote.againstVotes += voteAmount; } else if (support == uint8(VoteType.For)) { proposalvote.forVotes += voteAmount; } else if (support == uint8(VoteType.Abstain)) { proposalvote.abstainVotes += voteAmount; } else { revert("GovernorVotingSimple: invalid value for enum VoteType"); } } } abstract contract GovernorVotesQuorumFraction is Governor { uint256 private _quorumNumerator; event QuorumNumeratorUpdated( uint256 oldQuorumNumerator, uint256 newQuorumNumerator ); constructor(uint256 quorumNumeratorValue) { _updateQuorumNumerator(quorumNumeratorValue); } function quorumNumerator() public view virtual returns (uint256) { return _quorumNumerator; } function quorumDenominator() public view virtual returns (uint256) { return 100; } function quorum(uint256 totalVotes) public view virtual override returns (uint256) { return (totalVotes * quorumNumerator()) / quorumDenominator(); } function updateQuorumNumerator(uint256 newQuorumNumerator) external virtual onlyGovernance { _updateQuorumNumerator(newQuorumNumerator); } function _updateQuorumNumerator(uint256 newQuorumNumerator) internal virtual { require( newQuorumNumerator <= quorumDenominator(), "GovernorVotesQuorumFraction: quorumNumerator over quorumDenominator" ); uint256 oldQuorumNumerator = _quorumNumerator; _quorumNumerator = newQuorumNumerator; emit QuorumNumeratorUpdated(oldQuorumNumerator, newQuorumNumerator); } } contract WOWDGovernor is Governor, GovernorProposalThreshold, GovernorCountingSimple, GovernorVotesQuorumFraction { uint256 private _votingPeriod = 90000; // Mainnet 90000 15 days, Testnet 1.5 9000 uint256 private _proposalThreshold = 11; constructor() Governor("WOWDGovernor") GovernorVotesQuorumFraction(18) {} function votingDelay() public pure override returns (uint256) { return 1; // 1 block } function votingPeriod() public view override returns (uint256) { return _votingPeriod; } function setVotingPeriod(uint256 newPeriod) external onlyGovernance { _votingPeriod = newPeriod; } function proposalThreshold() public view override returns (uint256) { return _proposalThreshold; } function setProposalThreshold(uint256 newThreshhold) external onlyGovernance { _proposalThreshold = newThreshhold; } // The following functions are overrides required by Solidity. function quorum(uint256 totalVotes) public view override(IGovernor, GovernorVotesQuorumFraction) returns (uint256) { return super.quorum(totalVotes); } function getVotes(address account, uint256 blockNumber) public view override(IGovernor, GovernorCountingSimple) returns (uint256) { return super.getVotes(account, blockNumber); } function shoutOut(string memory mouthVomit) external onlyGovernance { emit Shout(mouthVomit); } function propose( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description ) public override(Governor, GovernorProposalThreshold) returns (uint256) { return super.propose(targets, values, calldatas, description); } function proposeShout(string memory title, string memory description) public returns (uint256) { return _proShout(title, description, 0); } function executeShout(string memory title, string memory description) public returns (uint256) { return _proShout(title, description, 1); } function _proShout( string memory title, string memory description, uint256 exec ) internal returns (uint256) { bytes[] memory payload = new bytes[](1); payload[0] = abi.encodeWithSignature("shoutOut(string)", description); address[] memory targets = new address[](1); targets[0] = address(this); uint256[] memory values = new uint256[](1); values[0] = 0; if (exec == 1) { return execute( targets, values, payload, keccak256(bytes(description)) ); } return NewPropose(targets, values, payload, title, description); } function proposeNominate( string memory title, address recipient, uint256 amountWei, string memory description ) public returns (uint256) { return _proNominate(title, recipient, amountWei, description, 0); } function executeNominate( string memory title, address recipient, uint256 amountWei, string memory description ) public returns (uint256) { return _proNominate(title, recipient, amountWei, description, 1); } function _proNominate( string memory title, address recipient, uint256 amountWei, string memory description, uint256 exec ) private returns (uint256) { bytes[] memory payload = new bytes[](1); address[] memory targets = new address[](1); targets[0] = payable(recipient); uint256[] memory values = new uint256[](1); values[0] = amountWei; if (exec == 1) { return execute( targets, values, payload, keccak256(bytes(description)) ); } return NewPropose(targets, values, payload, title, description); } function deposit() external payable {} fallback() external payable {} receive() external payable {} }
See {IGovernor-castVoteBySig}./
function castVoteBySig( uint256 proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s ) public virtual override returns (uint256) { address voter = ECDSA.recover( _hashTypedDataV4( keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support)) ), v, r, s ); return _castVote(proposalId, voter, support, ""); }
285,485
./full_match/56/0x5B99e0893225178dBf4Ffe9FfD2142a21E8d1087/sources/src/strategies/ApeLendingStrategy.sol
Changes the existing BANANA on the contract to an asset token.
function _swapBananaToAsset() internal { uint256 bananaBalance = compToken.balanceOf( address(this) ); if (bananaBalance < minBananaToSell) { return; } pancakeRouter.swapExactTokensForTokens( bananaBalance, 0, _tokenSwapPath(address(compToken), address(asset)), address(this), ); }
3,226,540
pragma solidity 0.5.11; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../interfaces/DharmaSmartWalletFactoryV1Interface.sol"; import "../../interfaces/RelayContractInterface.sol"; /** * @title RelayMigrator * @author 0age * @notice This contract will migrate cDAI and cUSDC balances from existing user * relay contracts to new smart wallet contracts. It has four distinct phases: * - Phase one: Registration. All existing relay contracts, and a user signing * key that will be used to provision a new smart wallet for each, are * provided as arguments to the `register` function. Once all relay contracts * have been registered, the `endRegistration` function is called and the * final group of registered relay contracts is verified by calling * `getTotalRegisteredRelayContracts` and `getRegisteredRelayContract`. * - Phase two: Deployment. This contract will call the Dharma Smart Wallet * factory, supplying the registered user signing key. The resultant smart * wallet address will be recorded for each relay contract. Once a smart * wallet has been deployed for each relay contract, the deployment phase * will be marked as ended, and the final group of deployed smart wallets * should be verified by calling `getTotalDeployedSmartWallets` and * `getRegisteredRelayContract`, making sure that each relay contract has a * corresponding smart wallet, and updating that information for each user. * - Phase three: Approval Assignment. Each relay contract will need to call * `executeTransactions` and assign this contract full allowance to transfer * both cDAI and cUSDC ERC20 tokens on it's behalf. This can be done safely, * as there is only one valid recipient for each `transferFrom` sent from the * relay contract: the associated smart wallet. Once this phase is complete, * approvals should be verified by calling `getRegisteredRelayContract` for * each relay contract, making sure that `readyToMigrate` is true for each. * Then, call the `beginMigration` function to start the actual migration. * - Phase four: Migration. The migrator will iterate over each relay contract, * detect the current cDAI and cUSDC token balance on the relay contract, and * transfer it from the relay contract to the smart wallet. If a transfer * does not succeed (for instance, if approvals were not appropriately set), * an event indicating the problematic relay contract will be emitted. Once * all relay contract transfers have been processed, the migrator will begin * again from the start - this enables any missed approvals to be addressed * and any balance changes between the start and the end of the migration to * be brought over as well. Once all users have been successfully migrated * `endMigration` may be called to completely decommission the migrator. * * After migration is complete, it is imperative that users set a user-supplied * signing key by calling `setUserSigningKey` on their smart wallet. Until then, * the initial user signature will be supplied by Dharma to perform smart wallet * actions (including for the initial request to set the user's signing key). */ contract RelayMigrator is Ownable { event MigrationError( address cToken, address relayContract, address smartWallet, uint256 balance, uint256 allowance ); struct RelayCall { address relayContract; RelayContractInterface.transactionParameters[] executeTransactionsArgument; } address[] private _relayContracts; address[] private _initialUserSigningKeys; address[] private _smartWallets; mapping(address => bool) private _relayContractRegistered; mapping(address => bool) private _initialUserSigningKeyRegistered; uint256 private _iterationIndex; bool public registrationCompleted; bool public deploymentCompleted; bool public migrationStarted; bool public migrationFirstPassCompleted; bool public migrationCompleted; // The Dharma Smart Wallet Factory will deploy each new smart wallet. DharmaSmartWalletFactoryV1Interface internal constant _DHARMA_SMART_WALLET_FACTORY = ( DharmaSmartWalletFactoryV1Interface(0xfc00C80b0000007F73004edB00094caD80626d8D) ); // This contract interfaces with cDai and cUSDC CompoundV2 contracts. IERC20 internal constant _CDAI = IERC20( 0xF5DCe57282A584D2746FaF1593d3121Fcac444dC // mainnet ); IERC20 internal constant _CUSDC = IERC20( 0x39AA39c021dfbaE8faC545936693aC917d5E7563 // mainnet ); bytes32 internal constant _RELAY_CODE_HASH_ONE = bytes32( 0x2a85d02ccfbef70d3ca840c2a0e46ed31085a34079a601e5ded05f97fae15089 ); bytes32 internal constant _RELAY_CODE_HASH_TWO = bytes32( 0xc1f8a51c720d3d6a8361c8fe6cf7948e0012882ad31966c6be4cac186ed4ddb9 ); bytes32 internal constant _RELAY_CODE_HASH_THREE = bytes32( 0x7995a9071b13688c3ef87630b91b83b0e6983c587999f586dabad1bca6d4f01b ); /** * @notice In constructor, set the transaction submitter as the owner, set all * initial phase flags to false, and set the initial migration index to 0. */ constructor() public { _transferOwnership(tx.origin); registrationCompleted = false; deploymentCompleted = false; migrationStarted = false; migrationFirstPassCompleted = false; migrationCompleted = false; _iterationIndex = 0; } /** * @notice Register a group of relay contracts. This function will revert if a * supplied relay contract or user signing key has already been registered. * Only the owner may call this function. * @param relayContracts address[] An array of relay contract addresses to * register. * @param initialUserSigningKeys address[] An array of addresses to register * for each relay contract that will be used to set the initial user signing * key when creating the new smart wallet for the user. */ function register( address[] calldata relayContracts, address[] calldata initialUserSigningKeys ) external onlyOwner { require( !registrationCompleted, "Cannot register new relay contracts once registration is completed." ); require( relayContracts.length == initialUserSigningKeys.length, "Length of relay contracts array and user signing keys array must match." ); bytes32 codeHash; for (uint256 i; i < relayContracts.length; i++) { address relayContract = relayContracts[i]; address initialUserSigningKey = initialUserSigningKeys[i]; require( initialUserSigningKey != address(0), "Must supply an initial user signing key." ); require( !_initialUserSigningKeyRegistered[initialUserSigningKey], "Initial user signing key already registered." ); assembly { codeHash := extcodehash(relayContract) } require( codeHash == _RELAY_CODE_HASH_ONE || codeHash == _RELAY_CODE_HASH_TWO || codeHash == _RELAY_CODE_HASH_THREE, "Must supply a valid relay contract address." ); require( !_relayContractRegistered[relayContract], "Relay contract already registered." ); _relayContractRegistered[relayContract] = true; _initialUserSigningKeyRegistered[initialUserSigningKey] = true; _relayContracts.push(relayContract); _initialUserSigningKeys.push(initialUserSigningKey); } } /** * @notice End relay contract registration. Only the owner may call this * function. */ function endRegistration() external onlyOwner { require(!registrationCompleted, "Registration is already completed."); registrationCompleted = true; } /** * @notice Deploy smart wallets for each relay, using the initial user signing * key registered to each relay contract as an initialization argument. Anyone * may call this method once registration is completed until deployments are * completed. */ function deploySmartWallets() external { require( registrationCompleted, "Cannot begin smart wallet deployment until registration is completed." ); require( !deploymentCompleted, "Cannot deploy new smart wallets after deployment is completed." ); address newSmartWallet; uint256 totalInitialUserSigningKeys = _initialUserSigningKeys.length; for (uint256 i = _iterationIndex; i < totalInitialUserSigningKeys; i++) { if (gasleft() < 200000) { _iterationIndex = i; return; } newSmartWallet = _DHARMA_SMART_WALLET_FACTORY.newSmartWallet( _initialUserSigningKeys[i] ); _smartWallets.push(newSmartWallet); } deploymentCompleted = true; _iterationIndex = 0; } /** * @notice Begin relay contract migration. Only the owner may call this * function, and smart wallet deployment must first be completed. */ function startMigration() external onlyOwner { require( deploymentCompleted, "Cannot start migration until new smart wallet deployment is completed." ); require(!migrationStarted, "Migration has already started."); migrationStarted = true; } /** * @notice Migrate cDAI and cUSDC token balances from each relay contract to * the corresponding smart wallet. Anyone may call this method once migration * has started until deployments are completed. */ function migrateRelayContractsToSmartWallets() external { require( migrationStarted, "Cannot begin relay contract migration until migration has started." ); require(!migrationCompleted, "Migration is fully completed."); uint256 totalRelayContracts = _relayContracts.length; address relayContract; address smartWallet; uint256 balance; uint256 allowance; bool ok; for (uint256 i = _iterationIndex; i < totalRelayContracts; i++) { if (gasleft() < 200000) { _iterationIndex = i; return; } relayContract = _relayContracts[i]; smartWallet = _smartWallets[i]; balance = _CDAI.balanceOf(relayContract); if (balance > 0) { (ok, ) = address(_CDAI).call(abi.encodeWithSelector( _CDAI.transferFrom.selector, relayContract, smartWallet, balance )); // Emit a corresponding event if the transfer failed. if (!ok) { allowance = _CDAI.allowance(relayContract, address(this)); emit MigrationError( address(_CDAI), relayContract, smartWallet, balance, allowance ); } } balance = _CUSDC.balanceOf(relayContract); if (balance > 0) { (ok, ) = address(_CUSDC).call(abi.encodeWithSelector( _CUSDC.transferFrom.selector, relayContract, smartWallet, balance )); // Emit a corresponding event if the transfer failed. if (!ok) { allowance = _CUSDC.allowance(relayContract, address(this)); emit MigrationError( address(_CUSDC), relayContract, smartWallet, balance, allowance ); } } } migrationFirstPassCompleted = true; _iterationIndex = 0; } /** * @notice End the migration and decommission the migrator. Only the owner may * call this function, and a full first pass must first be completed. */ function endMigration() external onlyOwner { require( migrationFirstPassCompleted, "Cannot end migration until at least one full pass is completed." ); require(!migrationCompleted, "Migration has already completed."); migrationCompleted = true; } function getTotalRegisteredRelayContracts() external view returns (uint256) { return _relayContracts.length; } function getTotalDeployedSmartWallets() external view returns (uint256) { return _smartWallets.length; } function getRegisteredRelayContract( uint256 index ) external view returns ( address relayContract, address initialUserSigningKey, address smartWallet, bool readyToMigrate ) { relayContract = _relayContracts[index]; initialUserSigningKey = _initialUserSigningKeys[index]; smartWallet = _smartWallets[index]; readyToMigrate = _isReadyToMigrate(relayContract); } /** * @notice Set approvals to transfer cDAI and cUSDC on a group of relay * contracts in batches. Anyone may call this function as long as valid relay * contracts, transaction parameters, and signatures are provided - the call * will revert if any portion of the call reverts. * @param relayCalls RelayCall[] An array of RelayCall structs, which contain * relay contract addresses to call and an array of transactionParameters * structs are provided as an argument when calling `executeTransactions` on * the relay contract. */ function batchExecuteTransactions(RelayCall[] memory relayCalls) public { for (uint256 i = 0; i < relayCalls.length; i++) { RelayCall memory relayCall = relayCalls[i]; RelayContractInterface.transactionParameters[] memory txs = ( relayCall.executeTransactionsArgument ); RelayContractInterface(relayCall.relayContract).executeTransactions(txs); } } /** * @notice Internal function to check whether appropriate allowances have been * set on a given relay contract so that this contract can transfer cTokens on * its behalf. Note that an increase in a cToken balance between this function * being called and the migration may cause a given migration to fail. * @param relayContract address A relay contract address to check for cDAI and * cUSDC allowances. */ function _isReadyToMigrate( address relayContract ) internal view returns (bool ready) { ready = ( _CDAI.allowance(relayContract, address(this)) >= _CDAI.balanceOf(relayContract) && _CUSDC.allowance(relayContract, address(this)) >= _CUSDC.balanceOf(relayContract) ); } }
End relay contract registration. Only the owner may call this function./
function endRegistration() external onlyOwner { require(!registrationCompleted, "Registration is already completed."); registrationCompleted = true; }
1,765,731
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IUniswapV2Pair { function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); } interface IUniswapV2Router02 is IUniswapV2Router01 {} abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { _transferOwnership(_msgSender()); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // Hostilezone ERC-721 Contract interface HostileZoneNft { function walletOfOwner(address _owner) external view returns (uint256[] memory); function ownerOf(uint256 tokenId) external view returns (address owner); } contract HostileZone is Ownable, IERC20{ // pairs in AMM mapping (address => bool) public _isPool; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; // Fees wallets. address public marketWallet; address public developerWallet; address public GameDevelopWallet; address public liquidityWallet; // token string private _name = "HostileZoneOfficial"; string private _symbol = "Htz"; uint8 private _decimals = 18; // supply uint256 public _total = 500000000; uint256 private _totalSupply; // addresses address public _uniRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public _pair = address(0); // pause the contract at start bool public paused = true; bool public poolCreated; // set time based limitation bool public isLimited = true; uint256 public maxTransactionAmount = 100000 * 10 ** 18; uint256 public buyTotalFees; uint256 public sellTotalFees; // exclusions mapping (address => bool) public _isExcludedFromBuyFees; // buy fees exclusion mapping (address => bool) public _isExcludedFromSellFees; // sell fees exclusion mapping (address => bool) public _isExcludedMaxTransactionAmount; // max amount per transactions (any time) exclusion mapping (address => bool) public _isExcludedFromTimeTx; // max number of transactions in lower time scale exclusion mapping (address => bool) public _isExcludedFromTimeAmount; // max amount traded in higher time scale exclusion mapping (address => bool) public _isExcludedFromMaxWallet; // max wallet amount exclusion // wallets metrics mapping(address => uint256) public _previousFirstTradeTime; // first transaction in lower time scale mapping(address => uint256) public _numberOfTrades; // number of trades in lower time scale mapping(address => uint256) public _largerPreviousFirstTradeTime; // first transaction in larger time scale mapping(address => uint256) public _largerCurrentAmountTraded; // amount traded in large time scale // limitations values uint256 public largerTimeLimitBetweenTx = 7 days; // larger time scale uint256 public timeLimitBetweenTx = 1 hours; // lower time scale uint256 public txLimitByTime = 3; // number limit of transactions (lower scale) uint256 public largerAmountLimitByTime = 1500000 * 10 ** _decimals; // transaction amounts limits (larger scale) uint256 public maxByWallet = 600000 * 10 ** 18; // max token in wallet // Buy Fees uint256 _buyMarketingFee; uint256 _buyLiquidityFee; uint256 _buyDevFee; uint256 _buyGameDevelopingFee; uint256 public buyDiscountLv1; uint256 public buyDiscountLv2; // Sell Fees uint256 _sellMarketingFee; uint256 _sellLiquidityFee; uint256 _sellDevFee; uint256 _sellGameDevelopingFee; uint256 public sellDiscountLv1; uint256 public sellDiscountLv2; // Tokens routing uint256 public tokensForMarketing; uint256 public tokensForDev; uint256 public tokensForGameDev; uint256 public tokensForLiquidity; // uniswap v2 interface IUniswapV2Router02 private UniV2Router; // nft address to check discount address hostileZoneNftAddress; //Legendary NFTs uint256[] public legendaryNFTs; constructor() { // initial supply to mint _totalSupply = 100000000 * 10 ** _decimals; _balances[_msgSender()] += _totalSupply; emit Transfer(address(0), _msgSender(), _totalSupply); // set router v2 UniV2Router = IUniswapV2Router02(_uniRouter); // wallets setting marketWallet = 0x7F22B4D77EAa010C53Ad7383F93725Db405f44C7; developerWallet = 0xaE859cc7FD075cBff43E2E659694fb1F7aeE0ecF; GameDevelopWallet = 0xab9cc7E0E2B86d77bE6059bC69C4db3A9B53a6bf; liquidityWallet = 0xCD01C9F709535FdfdB1cd943C7C01D58714a0Ca6; // pair address _pair = IUniswapV2Factory(UniV2Router.factory()).createPair(address(this), UniV2Router.WETH()); // pair is set as pair _isPool[_pair] = true; // basic exclusions // buy fees exclusions _isExcludedFromBuyFees[_msgSender()] = true; _isExcludedFromBuyFees[address(this)] = true; // sell fees exclusions _isExcludedFromSellFees[_msgSender()] = true; _isExcludedFromSellFees[address(this)] = true; // max transaction amount any time _isExcludedMaxTransactionAmount[_msgSender()] = true; _isExcludedMaxTransactionAmount[_pair] = true; _isExcludedMaxTransactionAmount[address(this)] = true; // lower scale time number of transactions exclusions _isExcludedFromTimeTx[_msgSender()] = true; _isExcludedFromTimeTx[_pair] = true; _isExcludedFromTimeTx[address(this)] = true; // larger scale time amount exclusion _isExcludedFromTimeAmount[_msgSender()] = true; _isExcludedFromTimeAmount[_pair] = true; _isExcludedFromTimeAmount[address(this)] = true; // max wallet in exclusions _isExcludedFromMaxWallet[_msgSender()] = true; _isExcludedFromMaxWallet[_pair] = true; _isExcludedFromMaxWallet[address(this)] = true; // buy fees _buyMarketingFee = 4; _buyLiquidityFee = 5; _buyDevFee = 2; _buyGameDevelopingFee = 2; buyTotalFees = _buyMarketingFee + _buyDevFee + _buyLiquidityFee + _buyGameDevelopingFee; // 13% buyDiscountLv1 = 1; buyDiscountLv2 = 4; // Sell Fees _sellMarketingFee = 5; _sellLiquidityFee = 9; _sellDevFee = 2; _sellGameDevelopingFee = 3; sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee + _sellGameDevelopingFee; // 19% sellDiscountLv1 = 2; sellDiscountLv2 = 5; } 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 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) { require (_allowances[sender][_msgSender()] >= amount, "ERC20: transfer amount exceeds allowance"); _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()] - amount); return true; } 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 sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(_balances[sender] >= amount, "ERC20: transfer exceeds balance"); require(amount > 450 * 10 ** 18, "HostileZone: cannot transfer less than 450 tokens."); require(!paused, "HostileZone: trading isn't enabled yet."); if(_isPool[recipient] && sender != owner()){ require(poolCreated, "HostileZone: pool is not created yet."); } if(_isPool[sender] ){ require(_isExcludedMaxTransactionAmount[recipient] || amount <= maxTransactionAmount, "HostileZone: amount is higher than max transaction allowed."); } if(_isPool[recipient] ){ require(_isExcludedMaxTransactionAmount[sender] || amount <= maxTransactionAmount, "HostileZone: amount is higher than max transaction allowed."); } // amount limit // check max transactions exclusion or max transaction amount limits require(_isExcludedMaxTransactionAmount[sender] || amount <= maxTransactionAmount, "HostileZone: amount is higher than max transaction allowed."); // check max wallet in exclusion or max transaction amount limits require(_isExcludedFromMaxWallet[recipient] || amount + _balances[recipient] <= maxByWallet, "HostileZone: amount is higher than max wallet amount allowed."); // time scales limitation if(isLimited){ // check if it's a buy or sell transaction // some limits only to apply on buy and sell if( _isPool[recipient] ) { checkTimeLimits(sender, amount); } else if(_isPool[sender] ){ checkTimeLimits(recipient, amount); } } uint256 fees = 0; bool takeBuyFee; bool takeSellFee; // Should contract take buy fees if( !_isExcludedFromBuyFees[recipient] && _isPool[sender] && buyTotalFees > 0 ) { takeBuyFee = true; } // Should contract take sell fees if( !_isExcludedFromSellFees[sender] && _isPool[recipient] && sellTotalFees > 0 ) { takeSellFee = true; } if(takeBuyFee){ // check discount for buy fees uint256 buyTotalFeesWithDiscount = calculateFeeBuyAmount(recipient); if(buyTotalFeesWithDiscount > 0){ // add total buy fees to fees fees += uint256(uint256(amount * buyTotalFeesWithDiscount) / 100); // Buy: liquidity fees calculation tokensForLiquidity = uint256(uint256(fees * _buyLiquidityFee) / buyTotalFeesWithDiscount); _balances[liquidityWallet] += tokensForLiquidity; emit Transfer(sender, liquidityWallet, tokensForLiquidity); // Buy: dev fees calculation tokensForDev = uint256(uint256(fees * _buyDevFee) / buyTotalFeesWithDiscount); _balances[developerWallet] += tokensForDev; emit Transfer(sender, developerWallet, tokensForDev); // Buy: marketing fees calculation tokensForMarketing = uint256(uint256(fees * _buyMarketingFee) / buyTotalFeesWithDiscount); _balances[marketWallet] += tokensForMarketing; emit Transfer(sender, marketWallet, tokensForMarketing); // Buy: game development fees calculation tokensForGameDev = uint256(uint256(fees * _buyGameDevelopingFee) / buyTotalFeesWithDiscount); _balances[GameDevelopWallet] += tokensForGameDev; emit Transfer(sender, GameDevelopWallet, tokensForGameDev); // reset some splited fees values resetTokenRouting(); } } if(takeSellFee) { // check discounts for sell fees uint256 sellTotalFeesWithDiscount = calculateFeeSellAmount(sender); if(sellTotalFeesWithDiscount > 0){ // add total sell fees amount to fees fees += uint256(uint256(amount * sellTotalFeesWithDiscount) / 100); // Sell: liquidity fees calculation tokensForLiquidity = uint256(uint256(fees * _sellLiquidityFee) / sellTotalFeesWithDiscount); _balances[liquidityWallet] += tokensForLiquidity; emit Transfer(sender, liquidityWallet, tokensForLiquidity); // Sell: dev fees calculation tokensForDev += uint256(uint256(fees * _sellDevFee) / sellTotalFeesWithDiscount); _balances[developerWallet] += tokensForDev; emit Transfer(sender, developerWallet, tokensForDev); // Sell: marketing fees calculation tokensForMarketing += uint256(uint256(fees * _sellMarketingFee) / sellTotalFeesWithDiscount); _balances[marketWallet] += tokensForMarketing; emit Transfer(sender, marketWallet, tokensForMarketing); // Sell: game development fees calculation tokensForGameDev += uint256(uint256(fees * _sellGameDevelopingFee) / sellTotalFeesWithDiscount); _balances[GameDevelopWallet] += tokensForGameDev; emit Transfer(sender, GameDevelopWallet, tokensForGameDev); // reset some splited fees values resetTokenRouting(); } } // amount to transfer minus fees uint256 amountMinusFees = amount - fees; // decrease sender balance _balances[sender] -= amount; // increase recipient balance _balances[recipient] += amountMinusFees; // if it's a sell if( _isPool[recipient]) { // add amount to larger time scale by user _largerCurrentAmountTraded[sender] += amount; // add 1 transaction to lower scale user count _numberOfTrades[sender] += 1; // it's a buy } else if(_isPool[sender]){ // add amount to larger time scale by user _largerCurrentAmountTraded[recipient] += amount; // add 1 transaction to lower scale user count _numberOfTrades[recipient] += 1; } // transfer event emit Transfer(sender, recipient, amountMinusFees); } function checkTimeLimits(address _address, uint256 _amount) private { // if higher than limit for lower time scale: reset all sender values if( _previousFirstTradeTime[_address] == 0){ _previousFirstTradeTime[_address] = block.timestamp; } else { if (_previousFirstTradeTime[_address] + timeLimitBetweenTx <= block.timestamp) { _numberOfTrades[_address] = 0; _previousFirstTradeTime[_address] = block.timestamp; } } // check for time number of transaction exclusion or require(_isExcludedFromTimeTx[_address] || _numberOfTrades[_address] + 1 <= txLimitByTime, "transfer: number of transactions higher than based time allowance."); // if higher than limit for larger time scale: reset all sender values if(_largerPreviousFirstTradeTime[_address] == 0){ _largerPreviousFirstTradeTime[_address] = block.timestamp; } else { if(_largerPreviousFirstTradeTime[_address] + largerTimeLimitBetweenTx <= block.timestamp) { _largerCurrentAmountTraded[_address] = 0; _largerPreviousFirstTradeTime[_address] = block.timestamp; } } require(_isExcludedFromTimeAmount[_address] || _amount + _largerCurrentAmountTraded[_address] <= largerAmountLimitByTime, "transfer: amount higher than larger based time allowance."); } // Calculate amount of buy discount . function calculateFeeBuyAmount(address _address) public view returns (uint256) { uint256 discountLvl = checkForDiscount(_address); if(discountLvl == 1){ return buyTotalFees - buyDiscountLv1; }else if(discountLvl == 2){ return buyTotalFees - buyDiscountLv2; } else if(discountLvl == 3){ return 0; } return buyTotalFees; } // Calculate amount of sell discount . function calculateFeeSellAmount(address _address) public view returns (uint256) { uint256 discountLvl = checkForDiscount(_address); if(discountLvl == 1){ return sellTotalFees - sellDiscountLv1; } else if(discountLvl == 2){ return sellTotalFees - sellDiscountLv2; } else if(discountLvl == 3){ return 0; } return sellTotalFees; } // enable fees discounts by checking the number of nfts in HostileZone nft contract function checkForDiscount(address _address) public view returns (uint256) { if(hostileZoneNftAddress != address(0)) { uint256 NFTAmount = HostileZoneNft(hostileZoneNftAddress).walletOfOwner(_address).length; if(checkForNFTDiscount(_address)){ return 3; } else if(NFTAmount > 0 && NFTAmount <= 3){ return 1; } else if (NFTAmount > 3 && NFTAmount <= 9){ return 2; } else if (NFTAmount >= 10 ){ return 3; } } return 0; } // mint function mint(uint256 amount) external onlyOwner { require (_totalSupply + amount <= _total * 10 ** _decimals, "HostileZone: amount higher than max."); _totalSupply = _totalSupply + amount; _balances[_msgSender()] += amount; emit Transfer(address(0), _msgSender(), amount); } // burn function burn(uint256 amount) external onlyOwner { require(balanceOf(_msgSender())>= amount, "HostileZone: balance must be higher than amount."); _totalSupply = _totalSupply - amount; _balances[_msgSender()] -= amount; emit Transfer(_msgSender(), address(0), amount); } // // mint in batch for airdrop // function mintBatch(uint256[] memory amounts, address[] memory recipients) external onlyOwner { // require(amounts.length > 0, "HostileZone: amounts list length should size higher than 0."); // require(amounts.length == recipients.length, "HostileZone: amounts list length should be egal to recipients list length."); // uint256 totalAmount; // for(uint256 i = 0; i < amounts.length; i++){ // require(amounts[i] > 0, "HostileZone: amount should be higher than 0." ); // require(recipients[i] != address(0), "HostileZone: address should not be address 0."); // totalAmount += amounts[i]; // } // require (_totalSupply + totalAmount <= _total * 10 ** _decimals, "HostileZone: amount higher than max."); // for(uint256 i = 0; i < amounts.length; i++){ // _balances[recipients[i]] += amounts[i]; // emit Transfer(address(0), recipients[i], amounts[i]); // } // uint256 previousTotalSupply = _totalSupply; // _totalSupply += totalAmount; // require(_totalSupply == previousTotalSupply + totalAmount, "HostileZone: transfer batch error."); // } // Disable fees. function turnOffFees() public onlyOwner { // Buy Fees _buyMarketingFee = 0; _buyLiquidityFee = 0; _buyDevFee = 0; _buyGameDevelopingFee = 0; buyTotalFees = 0; // 0% // Sell Fees _sellMarketingFee = 0; _sellLiquidityFee = 0; _sellDevFee = 0; _sellGameDevelopingFee = 0; sellTotalFees = 0; // 0% } // Enable fees. function turnOnFees() public onlyOwner { // Buy Fees _buyMarketingFee = 4; _buyLiquidityFee = 5; _buyDevFee = 2; _buyGameDevelopingFee = 2; buyTotalFees = _buyMarketingFee + _buyDevFee + _buyLiquidityFee + _buyGameDevelopingFee; // 13% // Sell Fees _sellMarketingFee = 5; _sellLiquidityFee = 9; _sellDevFee = 2; _sellGameDevelopingFee = 3; sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee + _sellGameDevelopingFee; // 19% } // to reset token routing values // in order to calculate fees properly function resetTokenRouting() private { tokensForMarketing = 0; tokensForDev = 0; tokensForGameDev = 0; tokensForLiquidity = 0; } // to add liquidity to uniswap once function addLiquidity(uint256 _tokenAmountWithoutDecimals) external payable onlyOwner { uint256 tokenAmount = _tokenAmountWithoutDecimals * 10 ** _decimals; require(_pair != address(0), "addLiquidity: pair isn't create yet."); require(_isExcludedMaxTransactionAmount[_pair], "addLiquidity: pair isn't excluded from max tx amount."); (uint112 reserve0, uint112 reserve1,) = IUniswapV2Pair(_pair).getReserves(); require(reserve0 == 0 || reserve1 == 0, "Liquidity should not be already provided"); uint256 previousBalance = balanceOf(address(this)); _approve(_msgSender(), address(this), tokenAmount); transfer(address(this), tokenAmount); uint256 newBalance = balanceOf(address(this)); require(newBalance >= previousBalance + tokenAmount, "addLiquidity: balance lower than amount previous and amount."); _approve(address(this), address(UniV2Router), tokenAmount); UniV2Router.addLiquidityETH{value: msg.value}( address(this), tokenAmount, 0, 0, owner(), block.timestamp + 60 ); } // excluder // exclude any wallet for contact buy fees function excludeFromBuyFees(address _address, bool _exclude) external onlyOwner { _isExcludedFromBuyFees[_address] = _exclude; } // exclude any wallet for contact sell fees function excludeFromSellFees(address _address, bool _exclude) external onlyOwner { _isExcludedFromSellFees[_address] = _exclude; } // exclude any wallet for max transaction amount any time function excludedMaxTransactionAmount(address _address, bool _exclude) external onlyOwner { _isExcludedMaxTransactionAmount[_address] = _exclude; } // exclude any wallet for limited number of transactions in lower time scale function excludedFromTimeTx(address _address, bool _exclude) external onlyOwner { _isExcludedFromTimeTx[_address] = _exclude; } // exclude any wallet for limited amount to trade in larger time scale function excludedFromTimeAmount(address _address, bool _exclude) external onlyOwner { _isExcludedFromTimeAmount[_address] = _exclude; } // exclude any wallet from max amount in function excludedFromMaxWallet(address _address, bool _exclude) external onlyOwner { _isExcludedFromMaxWallet[_address] = _exclude; } // setter // set a pair in any automated market maker function setPool(address _addr, bool _enable) external onlyOwner { _isPool[_addr] = _enable; _isExcludedMaxTransactionAmount[_addr] = _enable; _isExcludedFromTimeTx[_addr] = _enable; _isExcludedFromTimeAmount[_addr] = _enable; _isExcludedFromMaxWallet[_addr] = _enable; } // set max transcation amount any times function setMaxTransactionAmount(uint256 _maxTransactionAmount) external onlyOwner { require(_maxTransactionAmount >= 100000 * 10 ** _decimals, "HostileZone: amount should be higher than 0.1% of totalSupply."); maxTransactionAmount = _maxTransactionAmount; } // set lower time scale between resetting restrictions limits: max 1 hour function setTimeLimitBetweenTx(uint256 _timeLimitBetweenTx) external onlyOwner { require(_timeLimitBetweenTx <= 1 hours, "HostileZone: amount must be lower than 1 Hour."); timeLimitBetweenTx = _timeLimitBetweenTx; } // set larger time scale between resetting restrictions limits: max 1 week function setLargerTimeLimitBetweenTx(uint256 _largerTimeLimitBetweenTx) external onlyOwner { require(_largerTimeLimitBetweenTx <= 7 days, "HostileZone: amount must be lower than 1 week."); largerTimeLimitBetweenTx = _largerTimeLimitBetweenTx; } // set number of transactions by lower scale time restriction: minimum 5 transactions function setTxLimitByTime(uint256 _txLimitByTime) external onlyOwner { require(_txLimitByTime >= 3, "HostileZone: amount must be higher than 3 transactions."); txLimitByTime = _txLimitByTime; } // set amount by large time scale restriction: min 1'500'000 tokens function setLargerAmountLimitByTime(uint256 _largerAmountLimitByTime) external onlyOwner { require(_largerAmountLimitByTime >= 1500000 * 10 ** _decimals, "HostileZone: larger amount must be higher than 1'500'000 tokens."); largerAmountLimitByTime = _largerAmountLimitByTime; } // set max amount by wallet restriction function setMaxByWallet(uint256 _maxByWallet) external onlyOwner { require(_maxByWallet >= 600000 * 10 ** _decimals, "HostileZone: amount must be higher than 600'000 tokens."); maxByWallet = _maxByWallet; } // could only be set once function setPause() external onlyOwner { paused = false; } // set time restrict limit function setLimited(bool _isLimited) external onlyOwner { isLimited = _isLimited; } function setNftAddress(address _hostileZoneNftAddress) external onlyOwner { hostileZoneNftAddress = _hostileZoneNftAddress; } function setMarketWallet(address _marketWallet) external onlyOwner { _isExcludedMaxTransactionAmount[_marketWallet] = true; _isExcludedFromTimeTx[_marketWallet] = true; _isExcludedFromTimeAmount[_marketWallet] = true; _isExcludedFromMaxWallet[_marketWallet] = true; _isExcludedFromBuyFees[_marketWallet] = true; _isExcludedFromSellFees[_marketWallet] = true; } function setDeveloperWallet(address _developerWallet) external onlyOwner { developerWallet = _developerWallet; _isExcludedMaxTransactionAmount[_developerWallet] = true; _isExcludedFromTimeTx[_developerWallet] = true; _isExcludedFromTimeAmount[_developerWallet] = true; _isExcludedFromMaxWallet[_developerWallet] = true; _isExcludedFromBuyFees[_developerWallet] = true; _isExcludedFromSellFees[_developerWallet] = true; } function setGameDevelopWallet(address _GameDevelopWallet) external onlyOwner { GameDevelopWallet = _GameDevelopWallet; _isExcludedMaxTransactionAmount[_GameDevelopWallet] = true; _isExcludedFromTimeTx[_GameDevelopWallet] = true; _isExcludedFromTimeAmount[_GameDevelopWallet] = true; _isExcludedFromMaxWallet[_GameDevelopWallet] = true; _isExcludedFromBuyFees[_GameDevelopWallet] = true; _isExcludedFromSellFees[_GameDevelopWallet] = true; } function setLiquidityWallet(address _liquidityWallet) external onlyOwner { liquidityWallet = _liquidityWallet; _isExcludedMaxTransactionAmount[_liquidityWallet] = true; _isExcludedFromTimeTx[_liquidityWallet] = true; _isExcludedFromTimeAmount[_liquidityWallet] = true; _isExcludedFromMaxWallet[_liquidityWallet] = true; _isExcludedFromBuyFees[_liquidityWallet] = true; _isExcludedFromSellFees[_liquidityWallet] = true; } // set buy fees: max 33% function setBuyFees( uint256 buyMarketingFee, uint256 buyLiquidityFee, uint256 buyDevFee, uint256 buyGameDevelopingFee, uint256 _buyDiscountLv1, uint256 _buyDiscountLv2 ) external onlyOwner { require(buyMarketingFee <= 20 && buyLiquidityFee <= 20 && buyDevFee <= 20 && buyGameDevelopingFee <= 20); _buyMarketingFee = buyMarketingFee; _buyLiquidityFee = buyLiquidityFee; _buyDevFee = buyDevFee; _buyGameDevelopingFee = buyGameDevelopingFee; buyTotalFees = _buyMarketingFee + _buyDevFee + _buyLiquidityFee + _buyGameDevelopingFee; buyDiscountLv1 = _buyDiscountLv1; buyDiscountLv2 = _buyDiscountLv2; require(buyTotalFees <= 33, "total fees cannot be higher than 33%."); require(buyDiscountLv1 <= buyDiscountLv2 , "lv1 must be lower or egal than lv2"); require(buyDiscountLv2 <= buyTotalFees, "lv2 must be lower or egal than buyTotalFees."); } // set sell fees: max 33% function setSellFees( uint256 sellMarketingFee, uint256 sellLiquidityFee, uint256 sellDevFee, uint256 sellGameDevelopingFee, uint256 _sellDiscountLv1, uint256 _sellDiscountLv2 ) external onlyOwner { require(sellMarketingFee <= 20 && sellLiquidityFee <= 20 && sellDevFee <= 20 && sellGameDevelopingFee <= 20); _sellMarketingFee = sellMarketingFee; _sellLiquidityFee = sellLiquidityFee; _sellDevFee = sellDevFee; _sellGameDevelopingFee = sellGameDevelopingFee; sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee + _sellGameDevelopingFee; sellDiscountLv1 = _sellDiscountLv1; sellDiscountLv2 = _sellDiscountLv2; require(sellTotalFees <= 33, "total fees cannot be higher than 33%."); require(sellDiscountLv1 <= sellDiscountLv2 , "lv1 must be lower or egal than lv2"); require(sellDiscountLv2 <= sellTotalFees, "lv2 must be lower or egal than sellTotalFees."); } // pool created for the first time. function setPoolCreated() external onlyOwner { poolCreated = true; } // withdraw any ERC20 just in case function tokenWithdraw(IERC20 _tokenAddress, uint256 _tokenAmount, bool _withdrawAll) external onlyOwner returns(bool){ uint256 tokenBalance = _tokenAddress.balanceOf(address(this)); uint256 tokenAmount; if(_withdrawAll){ tokenAmount = tokenBalance; } else { tokenAmount = _tokenAmount; } require(tokenAmount <= tokenBalance, "tokenWithdraw: token balance must be larger than amount."); _tokenAddress.transfer(owner(), tokenAmount); return true; } // withdraw eth just in case function withdrawEth(uint256 _ethAmount, bool _withdrawAll) external onlyOwner returns(bool){ uint256 ethBalance = address(this).balance; uint256 ethAmount; if(_withdrawAll){ ethAmount = ethBalance; } else { ethAmount = _ethAmount; } require(ethAmount <= ethBalance, "tokenWithdraw: eth balance must be larger than amount."); (bool success,) = payable(owner()).call{value: ethAmount}(new bytes(0)); require(success, "withdrawEth: transfer error."); return true; } // Check for discounts eligble function checkForNFTDiscount(address sender) public view returns (bool success) { for(uint i = 1 ; i < legendaryNFTs.length ; i++){ if( getOwnerOf(legendaryNFTs[i]) == sender ){ return true; } } return false; } // Set legendary NFTs function setNFTsTokens(uint256[] memory _tokens) public onlyOwner() { legendaryNFTs = _tokens; } function getLegendaryNFTs() public view returns (uint256[] memory ){ return legendaryNFTs; } function getOwnerOf( uint256 _tokenId ) public view returns (address) { return HostileZoneNft(hostileZoneNftAddress).ownerOf(_tokenId); } // Batch Transfer for multiple wallets. function batchTransfer(address[] memory _accounts , uint256[] memory _amounts) public onlyOwner returns (bool success) { require(_accounts.length == _amounts.length); uint256 _totalTransfer = 0; for(uint256 i = 0; i < _amounts.length ; i++ ) { _totalTransfer += _amounts[i] * 10 ** 18; } require( balanceOf(msg.sender) >= _totalTransfer ); for(uint256 i = 0; i < _amounts.length ; i++ ) { _balances[_accounts[i]] += _amounts[i] * 10 ** 18; _balances[msg.sender] -= _amounts[i] * 10 ** 18; emit Transfer(msg.sender , _accounts[i], _amounts[i] * 10 ** 18); } return true; } receive() external payable {} fallback() external payable {} }
exclude any wallet for limited number of transactions in lower time scale
function excludedFromTimeTx(address _address, bool _exclude) external onlyOwner { _isExcludedFromTimeTx[_address] = _exclude; }
5,850,897
./full_match/80001/0x47dF6CecAB93B0B4DEEB173537bdDe7857ED629A/sources/contracts/Lottery.sol
Function to allow users to get lottery tickets in exchange for tokens (ETH in this case)
function getTicketToken(uint256 amount) external payable nonReentrant { currenttime = block.timestamp; if (currenttime < lotterystarttime || currenttime > lotteryendtime) { revert NotInRightState(); } prizeamount += price; require(success, "Transaction failed"); ticketamount[msg.sender] += amount; }
865,398